yii2yii-widgets

Yii2, what the model parameter does in widget?


echo Select2::widget([
    'model' => $vendorModel,
    'attribute' => 'id',
    'data' => $vendor,
    'options' => ['placeholder' => 'Select a vendor ...'],
    'pluginOptions' => [
        'allowClear' => true
    ],
]);

The above Select2 widget (and most of widgets are same) require the Model attribute, but I don't know what the model does in Widget, because even if I put the any other model object, it works.

replaced model with $userModel that doesn't relate with vendor model at all and I tried, and it works.

echo Select2::widget([
    'model' => $userModel,
    'attribute' => 'id',
    'data' => $vendor,
    'options' => ['placeholder' => 'Select a vendor ...'],
    'pluginOptions' => [
        'allowClear' => true
    ],
]);

How should I understand the Model?


Solution

  • Select2 widget is an instance of Yii2 Input widget and it renders input for model attribute. It is useful for forms where you create/update your model. So e.g. if it is for actionCreate() you should use your new ActiveRecord model instance for widget 'model' attribute and any attribute name you want to fill for 'attribute'.

    So in your example you are trying to set your model id with some key from $vendor list. All models fit your widget settings just because they all have 'id'.

    I believe you need to provide some other attribute here called e.g. 'vendor_id'. Notice that your $vendor list should have vendor ids as keys and e.g. vendor names as values.