简体   繁体   中英

yii2 select2 by kartik-v set default value

I've a question about yii2 kartik-v widget select 2.

the widget is attached to a field in my view

<?=
$form->field($model, 'address')->widget(Select2::className(), [
    'options' => ['placeholder' => 'Inserta an address '],
    'pluginOptions' => [
        'allowClear' => true,
        'minimumInputLength' => 3,
        'ajax' => [
            'url' => Url::to(['register/addresses']),
            'dataType' => 'json',
            'data' => new JsExpression('function(params) { return {q:params.term}; }')
        ],
        'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
        'templateResult' => new JsExpression('function(address) { return address.name; }'),
        'templateSelection' => new JsExpression('function (address) { return address.name; }'),
    ],
    'pluginEvents' => [
        "select2:select" => "function(e) {
                      // some function

                }",
    ],
]);
?>

if in my controller i want to set to this field a value

like: $model->address = "Some Value"; on the view the field remain blank

what can i do?

UPDATE!

As the documentation say i can use the option: 'initValueText' if i use the ajax version of this plugin. So i've tried to set 'initValueText' => $model->address, but the result is the same

The problem was this:

  'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
  'templateResult' => new JsExpression('function(address) { return address.name; }'),
  'templateSelection' => new JsExpression('function (address) { return address.name; }'),

It seems that this plugin want a specific return for the keys 'templateResult' and 'templateSelection'.

I've modified the JsExpression return value with address.text (instead of adress.name) as the guide examples : Link .

And then i've modified also the PHP method that return the results:

public function actionAddresses($q = NULL, $id = NULL)
{

    Yii::$app->response->format = Response::FORMAT_JSON;

    $results = array();
    if (!is_null($q)) {

        $geocoder = new GeocodingClient();
        $request = $geocoder->lookup(['address' => $q]);
        $counter = 1;
        foreach ($request['results'] as $key => $value) {
            $results['results'][] = [
                'id' => $counter,
                'text' => $value['formatted_address'], // Instead of 'name'
                'coordinate' => $value['geometry']['location']
            ];
            $counter++;
        }
    }
    return $results;
}

I hope this may help someone with a similar problem.

Its bit late.. but i too had same problem.. i resolved it by assigning value

  <?=
  $form->field($model, 'address')->widget(Select2::className(), [
                          'initValueText' => $model->address,
                           'value' => $model->address,
                           'options' => ['placeholder' => 'Inserta an address '],
                           'pluginOptions' => [
                                    'allowClear' => true,
                                    'minimumInputLength' => 3,
                                'ajax' => [
                                    'url' => Url::to(['register/addresses']),
                                    'dataType' => 'json',
                                    'data' => new JsExpression('function(params) { return {q:params.term}; }')
    ],
    'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
    'templateResult' => new JsExpression('function(address) { return address.name; }'),
    'templateSelection' => new JsExpression('function (address) { return address.name; }'),
],
'pluginEvents' => [
    "select2:select" => "function(e) {
                  // some function

            }",
],
   ]);
 ?>

hey i had the same issue with #ajax neither placeholder nor initValueText were showing what i did was this

<?php
    $product = $model->product_id ? Product::findOne($model->product_id)->name : 'select ....';
    echo $form->field($model, 'product_id')->widget(Select2::classname(), [
        'initValueText' => $product, // set the initial display text
        // 'options' => ['placeholder' => 'select ....'],
        'pluginOptions' => [
            'allowClear' => true,
            'minimumInputLength' => 3,
            'ajax' => [
                'url' => Url::to(['list']),
                'dataType' => 'json',
                'data' => new JsExpression('function(params) { return {q:params.term}; }')
            ],
            'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
            'templateResult' => new JsExpression('function(product_id) { return product_id.name; }'),
            'templateSelection' => new JsExpression('function (product_id) { return product_id.name; }'),
        ],
    ]);?>

if the model is new 'select ....' is shown else the product's name since "options" is not doing much either hope this will be hopeful to someone

you use kartik select2, in controller you have set a value (id/ids) and name values for 'initValueText'

$model->id = 1; // or if arrays [1,3,4,5]
$username = User::find()->select('name')->where('id' => $model->id)->scalar();

and in view kartik select2

$form->field($model, 'username')->widget(Select2::className(), [
'initValueText' => $username;
...

I was facing same problem. Then I tried value key into the options and it worked.

<?php
 echo $form->field($model, 'test')->widget(Select2::classname(), [
                                    //'data' => ['test', 'test2'],
                                    'initValueText'=>['test','test2'],
                                    'options' => ['multiple' => true, 'value'=>['1','2']],
                                    'pluginOptions' => [
                                        'multiple' => true,
                                        'allowClear' => true,
                                        'minimumInputLength' => 1,
                                        'language' => [
                                            'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
                                        ],
                                        'ajax' => [
                                            'url' => '...',
                                            'dataType' => 'json',
                                            'data' => new JsExpression('function(params) { return {q:params.term}; }')
                                        ],
                                        'escapeMarkup' => new JsExpression('function (m) { return m; }') 
                                ?>
                      

Hope It'll be helpful for someone.

I fix this solution by using trigger function. In below method we can set default value in kartik select2 widget.

$('#id').val(11).trigger('change'); //in val() mention the hash value of your select2 list 

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