简体   繁体   English

如何设置select2 ajax预选值?

[英]How to set select2 ajax preselected value?

Currently I followed this answer to make Ajaxselectmultiple field of Flask form to work. 当前,我按照答案使Flask表单的Ajaxselectmultiple字段起作用。 This works well with event create form. 这适用于事件创建表单。 Like it automatically searches for the tag in backend through the api call. 像它一样,它通过api调用自动在后端搜索标签。

On update (update form invoked through js button click function), I want to display the preselected values. 在更新(通过js按钮单击功能调用的更新表单)上,我想显示预选的值。 So I tried this solution given on their select2 official site, but I can't make it possible. 因此,我尝试了在他们的select2官方网站上给出的解决方案,但我无法实现。

forms.py

from flask_admin.model.fields import AjaxSelectMultipleField
class EventCreateForm(FlaskForm):
    title = StringField(
        'Title',
        validators=[
            DataRequired(),
            Length(max=128),
        ],
    )
    start_date = DateField('Start Date', validators=[DataRequired(),])
    end_date = DateField('End Date', validators=[DataRequired(),])
    start_time = TimeField('Start Time', default=time())
    end_time = TimeField('End Time', default=time())
    location= StringField('Location')
    description = StringField('Description')
    tags = AjaxSelectMultipleField(
        loader=get_loader_by_name('tag')
    )

admin.py

class EventView(ModelView):
    can_create = False
    can_edit = False
    can_delete = False
    list_template = 'admin/events_list.html'

    def render(self, template, **kwargs):
            from teamup.forms import EventCreateForm

            kwargs.update(
                {
                    'event_create_form': EventCreateForm(),
                    'tag_form': TagForm(),
                    'events_url': url_for('api.list_events'),
                    'current_user': flask_login.current_user
                }
            )
            return super().render(template, **kwargs)

events.html

<div class="row">
    <div class="col-md-9">
        {{wtf.form_field(event_create_form.tags, class="form-control")}}
        </div>
        <div class="col-md-3">
        <button type="button" class="btn btn-default" data-target="#createTagModal" data-toggle="modal">Create Tag</button>
        </div>
        </div>
        {{wtf.form_field(event_create_form.description)}}

events.js

var calender = $('#calendar').fullCalendar({
        header: {
          left: 'prev,next today',
          center: 'title',
          right: 'month,agendaWeek,agendaDay,listWeek'
        },
        defaultDate: today,
        navLinks: true, // can click day/week names to navigate views
        weekNumbers: true,
        weekNumbersWithinDays: true,
        weekNumberCalculation: 'ISO',
        editable: true,
        eventLimit: true, // allow "more" link when too many events
        events: events_url,
        timezone: "America/Los_angeles",
        eventClick: function(event, element) {
          // reset form
          if($("#updateForm")[0] === undefined) {
            return;
          }
          $("#updateForm")[0].reset();
          $('#updateModal').modal('show');
          $('#updateForm input#id').val(event.id);
          $('#updateForm input#title').val(event.title);
          $('#updateForm input#location').val(event.location);
          $('#updateForm input#description').val(event.description);
          $('#updateForm input#interests').val(event.interests);
          $('#updateForm select#schools').val(event.school_id);

          var selinput = $('#updateForm input[data-json]')
          selinput.select2({
            ajax: {
                url: '/admin/event/ajax/lookup/?name=tag'
            }
          });
          // // Fetch the preselected item, and add to the control
          var studentSelect = selinput;
          $.ajax({
            type: 'GET',
            url: '/admin/event/ajax/lookup/?name=tag&query=cricket'
          }).then(function (data) {
            console.log(data);
            var val = data[0]
            var id = val[0]
            var text = val[1]
            // create the option and append to Select2
            var option = new Option(text, id, true, true);
            studentSelect.append(option).trigger('change.select2');

            // manually trigger the `select2:select` event
            studentSelect.trigger({
                type: 'select2:select',
                params: {
                    data: data
                }
            });
          });
          //
          start_date = event.start.toDate();
          $('#updateForm #start_date').datetimepicker('update', new Date(start_date.getUTCFullYear(), start_date.getUTCMonth(), start_date.getUTCDate()));
          $('#updateForm #start_time').val(getValidTimeFormat(start_date))
          if(event.end) {
            end_date = event.end.toDate();
            $('#updateForm #end_date').datetimepicker('update', new Date(end_date.getUTCFullYear(), end_date.getUTCMonth(), end_date.getUTCDate()));
            $('#updateForm #end_time').val(getValidTimeFormat(end_date))
          }
        }
      });

manually filling the update form through js since the filled values should get changed based on the event in which the user clicks. 通过js手动填写更新表单,因为填写的值应根据用户单击的事件进行更改。

The thing is, in all other answers they mentioned about adding option ele to existing select element but in my case, there was not select tag exists instead I have one input tag and ul , li tags. 问题是,在他们提到的所有其他关于将option ele添加到现有select元素的答案中,但是在我的情况下,不存在select标记,而是有一个input标记和ulli标记。

<div class="form-group "><label class="control-label" for="tags">Tags</label>
      <div class="select2-container select2-container-multi form-control" id="s2id_tags" style="width: 100%;">
     <ul class="select2-choices">  
      <li class="select2-search-choice">    
      <div>cricket</div>    
      <a href="#" class="select2-search-choice-close" tabindex="-1">
</a>
</li>
<li class="select2-search-field">    
<label for="s2id_autogen2" class="select2-offscreen">TagsTags</label>    

<input type="text" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" class="select2-input" id="s2id_autogen2" placeholder="" style="width: 34px;" aria-activedescendant="select2-result-label-4">  
  </li>
  </ul>
  </div>
  <input class="form-control" data-json="[]" data-multiple="1" data-placeholder="Select a tag" data-role="select2-ajax" data-url="/admin/event/ajax/lookup/?name=tag" id="tags" name="tags" type="hidden" value="1" tabindex="-1" style="display: none;">

 </div>

Note If I reinitialise the same input ele with select2 ( selinput.select2({ ), existing ajax select is not working. 注意如果我用select2( selinput.select2({ )重新初始化相同的输入ele,则现有的ajax select无法正常工作。

我通过将json对象设置为select2 data属性的值来实现这一点,

$("#updateForm input[data-json]").select2("data", [{id: "CA", text: "California"},{id:"MA", text: "Massachusetts"}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM