D
D
Diversia2018-06-05 12:50:09
Web development
Diversia, 2018-06-05 12:50:09

How to select default items in select2?

There is a form with select and select2 plugin:

<?
while($arFieldsPers = $res->Fetch())
{
  $personList[$arFieldsPers['ID']] = array(
        'id' => $arFieldsPers['ID'],
    'text' => $name,
    'status' => $status,
    'img' => $img,
    'date' => $date
  );
}
?>
      <select class="personActor form-control" name="actorsMain[]" multiple>
        <option></option>
        <?
        foreach ($arProps['actorsMain']["VALUE"] as $v) {
          echo "<option value='".$personList[$v]['id']."' selected>".$personList[$v]['text']." ".$personList[$v]['date']."</option>";
        }
        ?>
      </select>

javascript
function formatDetail(detail) {
    if (!detail.id) { 
      return detail.text; 
    }
  
    var $detail = $(
      '<div><div class="img"><img src="' + detail.img + '"></div><div class="info">' + detail.text + '<br><small>' + detail.date + '' + detail.status + '</small></div></div>'
    );
    return $detail;
  };
  $('.personActor').select2({

    width: '100%',
    placeholder: 'Имя персоны',
    language: "ru",
    theme: "bootstrap",
    allowClear: true,
    //tags: true,
    minimumInputLength: 3,
    //closeOnSelect: false,
    tokenSeparators: [',',';'],

    ajax: {
      url: "/local/ajax.php",
      dataType: 'json',
      delay: 500,
      data: function (params, page) {
        return {
          q: params.term,
        };
      },
      processResults: function (data) {
        return {
          results: data
        };
      },
      cache: true
    },

    templateResult: formatDetail,
    templateSelection: formatDetail
  });

When I enter into the field, the data is loaded via ajax - everything is displayed correctly. Output formatting is done using the formatDetail function.
The problem is that initially the select field should already contain data from the array formatted with the formatDetail function. Formatting doesn't work.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question