简体   繁体   中英

How to set select2 ajax preselected value?

Currently I followed this answer to make Ajaxselectmultiple field of Flask form to work. This works well with event create form. Like it automatically searches for the tag in backend through the api call.

On update (update form invoked through js button click function), I want to display the preselected values. So I tried this solution given on their select2 official site, but I can't make it possible.

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.

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.

<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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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