1

我有一个模型,它有一列(属性)存储了一个逗号分隔的 ID 值。

例如,电影有一列“流派”,其中包含多个流派,例如:40,20,1,3

当“多个”=> true 时,如何使用 Select2 小部件显示这些值?

以及如何将它们作为字符串保存回逗号分隔值。我想要一个能够快速灵活的解决方案。我知道你可以内爆和爆炸字符串,但似乎太多了。

任何帮助表示赞赏

4

3 回答 3

0

如果您正在显示一个包含已填充字段的表单,也许您想更新一个已经存在的对象,并且您想显示 Select2 字段的已保存值,请使用 'data' => [ 1 => 'Some value' ],其中 1 是与表单中显示的值相关联的值。您可以事先从数据库中检索要放入数据的内容。

来源:https ://github.com/kartik-v/yii2-widget-select2/issues/37

于 2021-07-10T00:40:33.433 回答
0

如果我记得正确地将默认选项作为小部件的 $options 配置的一部分传递:

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');

这是记忆中的盐粒。http://demos.krajee.com/widget-details/select2上的文档对如何执行此操作不是很具体。

于 2017-02-21T14:00:07.750 回答
0

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.

于 2017-02-21T16:59:50.327 回答