Yii2:Kartik Select2:来自模型属性的初始值 [英] Yii2: Kartik Select2: Initial Value from Model Attribute

查看:441
本文介绍了Yii2:Kartik Select2:来自模型属性的初始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如, 电影的流派"列中包含一种以上流派,例如:40,20,1,3

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

当'multiple'=> true时,如何使用Select2小部件显示这些值分开

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.

任何帮助表示赞赏

推荐答案

我不相信您可以这样做. Select2将数组中的数据作为数组发送,因此在保存之前,您仍然需要使用implode.我要做的是在您的模型课中:

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

这样,myArrayAttribute会将逗号分隔字段中的值作为数组保存.当然,您将需要为其添加验证规则,并在创建和更新表单中使用它代替您的其他属性.

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.

这篇关于Yii2:Kartik Select2:来自模型属性的初始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆