我使用karthik yii2 widget渲染select2。我使用的是更新版本。 我尝试使用initSelection设置初始值,它工作正常。但是当我尝试添加另一个值时,它会将预先选择的值更改为通过initSelection设置的ID。
<?php
$initScript = <<< SCRIPT
function (element, callback) {
var id = \$(element).val();
if (id !== "") {
var url = "{$url}";
\$.ajax(url.replace('idreplace', id), {dataType: "json"}).done(
function(data) {
callback(data.results);
});
}
}
SCRIPT;
echo Select2::widget([
'language' => 'en',
'name' => 'to',
'value' => ['1'],
'options' => [
'placeholder' => 'Choose...',
'id' => "to",
'multiple' => true,
'data-validation'=>'required',
],
'pluginOptions' => [
'language' => [
'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
],
'allowClear' => true,
'minimumInputLength' => 3,
'multiple' => true,
'ajax' => [
'url' => $url,
'dataType' => 'json',
'tags' => true,
'data' => new JsExpression('function(params) { return {search:params.term}; }'),
'results' => new JsExpression('function(data,page) {return { results:data.results }; }'),
],
'initSelection' => new JsExpression($initScript)
],
]);
?>
答案 0 :(得分:0)
最后我解决了我的问题。 select2 4.0中不推荐使用initselection。我试图使用“initValueText”
设置初始值 echo Select2::widget([
'language' => 'en',
'initValueText' => ['intialvaluetext'],//text of initial value
'name' => 'to',
'value' => ['1'],//matching id for initial value text
'options' => [
'placeholder' => 'Choose...',
'id' => "to",
'multiple' => true,
'data-validation'=>'required',
],
'pluginOptions' => [
'language' => [
'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
],
'allowClear' => true,
'minimumInputLength' => 3,
'multiple' => true,
'ajax' => [
'url' => $url,
'dataType' => 'json',
'tags' => true,
'data' => new JsExpression('function(params) { return {search:params.term}; }'),
'results' => new JsExpression('function(data,page) {return { results:data.results }; }'),
],
],
]);
?>