Yii2: Kartik Select2: Initial Value from Model Att

2019-09-11 19:31发布

问题:

I have a Model who has a column (attribute) that stored a comma separated value of IDs.

For Example, Movie has a column "Genre" that includes more than one genre, e.g.: 40,20,1,3

How can I use Select2 widget to show these values separated when 'multiple' => true

And how can I save them back into comma-separated value as a string. I want a solution that will allow for quick flexibility. I know you can implode and explode the string but seems too much.

Any help appreciated

回答1:

If I remember correctly pass the default option as part of the $options configuration for the widget:

echo $form->field($model, 'model_attribute_name')->widget(Select2::className(), [
    'data'      => $data
    'options'   => [
            'class'       => 'form-control',
            'placeholder' => 'Choose Option...',
            'selected'    => 40 
    ],
    'pluginOptions' => [
        'allowClear' => true,
    ],
])->label('Select2 Form Field');

This is from memory for grain fo salt here. The documentation at http://demos.krajee.com/widget-details/select2 is not very specific about how to do this.



回答2:

I don't believe you can do that. Select2 sends the data in post as an array, so you would still need to use implode before saving. What i would do instead is in your model class:

class MyModel extends \yii\db\ActiveRecord {
    $public myArrayAttribute;

    ...

    public function beforeSave($insert) {
        if (parent::beforeSave($insert)) {
            $this->myAttribute = implode(',', $this->myArrayAttribute);
            return true;
        }
        return false;
    }

    public function afterFind() {
        parent::afterFind();
         $this->myArrayAttribute = explode(',', $this->myAttribute);
    }
}

This way myArrayAttribute will hold the values from the comma separated field as an array. Of course you will need to add validation rules for it and use it instead of your other attribute in create and update forms.