kartik-v / yii2-widgets

Collection of useful widgets for Yii Framework 2.0
http://demos.krajee.com/widgets
Other
558 stars 175 forks source link

initValueText: if json result has element!=text it is not working as expected #340

Open tsdogs opened 7 years ago

tsdogs commented 7 years ago

If the JSON data is using some different structure (as using an ActiveQuery to query data), and JSON result contains something like: {"results":[{"id":"ID1","description":"DESCRIPTION 1"},{"id":"ID2","description":"DESCRIPTION 2"}, ...

I would be using something like this:

echo $form->field($model, 'field')->widget(Select2::classname(), [
    'initValueText' => $initialValue,
    'options' => ['placeholder' => 'Field ...','class'=>'asset','id'=>'xxx_field'],
    'pluginOptions' => [
        'allowClear' => true,
        'minimumInputLength' => 2,
        'ajax' => [
            'url' => $url,
            'dataType' => 'json',
            'data' => new JsExpression('function(params) { return {q:params.term}; }')
        ],
        'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
        'templateResult' => new JsExpression('function(model) { return model.description; }'),
        'templateSelection' => new JsExpression('function (model) { return model.description; }'),
    ],
]);

The result is that initialValueText "is not correctly used" and an empty string is assigned (when the value assigned to the attribute is selected an "undefined" is returned).

That's because on initial settings the "templateSelection" model has a "text" value initialized and not a "description" initialized. using this solves the problem:

        'templateSelection' => new JsExpression('function (model) { if (model.description!=undefined) return model.description; else return model.text; }'),

It would be nice to have some setting which would simply rename the "text" and also the "id" value used for the Select2 (something like displayValue ...)

hope it's clear enough :-)

--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/44952018-initvaluetext-if-json-result-has-element-text-it-is-not-working-as-expected?utm_campaign=plugin&utm_content=tracker%2F530581&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F530581&utm_medium=issues&utm_source=github).