Yii2:如何使用带有逗号分隔符的属性。 checkboxList() 中的值列表

Yii2: how to use an attribute with comma-sep. list of values in checkboxList()

我有一个数据库值为例如的属性。 cash,creditcard,paypal。在表单上,​​这当然需要呈现为每个选项的复选框,所以我假设我需要这样做:

echo $form->field($model, 'payment_options')
    ->checkboxList(['cash' => 'Cash', 'creditcard' => 'Credit Card', 'paypal' => 'PayPal', 'bitcoin' => 'Bitcoin']);

但是 none 的复选框是默认选中的。我如何指示 Yii 用逗号拆分(分解)值?而且,我想,在插入回数据库之前再次连接(内爆)?

each validator 中,我看到了一些关于 数组属性的信息,但我没有找到关于如何处理这些属性的其他信息...

我发现这是最好的、最有组织的方式。

创建一个 behavior(例如,在 components 文件夹中创建文件 ArrayAttributes.php 并设置 namespace app\components;):

use yii\db\ActiveRecord;
use yii\base\Behavior;

/**
 * For handling array attributes, being a comma-separated list of values in the database
 * Additional feature is handling of JSON strings, eg.: {"gender":"req","birthdate":"hide","addr":"req","zip":"req","city":"req","state":"opt"}
 */

class ArrayAttributesBehavior extends Behavior {

    public $attributes = [];
    public $separator = ',';
    public $jsonAttributes = [];

    public function events() {
        return [
            ActiveRecord::EVENT_AFTER_FIND => 'toArrays',
            ActiveRecord::EVENT_BEFORE_VALIDATE => 'toArrays',
            ActiveRecord::EVENT_BEFORE_INSERT => 'toStrings',
            ActiveRecord::EVENT_BEFORE_UPDATE => 'toStrings',
        ];
    }

    public function toArrays($event) {
        foreach ($this->attributes as $attribute) {
            if ($this->owner->$attribute) {
                $this->owner->$attribute = explode($this->separator, $this->owner->$attribute);
            } else {
                $this->owner->$attribute = [];
            }
        }

        foreach ($this->jsonAttributes as $attribute) {
            if (is_string($this->owner->$attribute)) {
                $this->owner->$attribute = json_decode($this->owner->$attribute, true);
            }
        }
    }

    public function toStrings($event) {
        foreach ($this->attributes as $attribute) {
            if (is_array($this->owner->$attribute)) {
                $this->owner->$attribute = implode($this->separator, $this->owner->$attribute);
            }
        }

        foreach ($this->jsonAttributes as $attribute) {
            if (!is_string($this->owner->$attribute)) {
                $this->owner->$attribute = json_encode($this->owner->$attribute);
            }
        }
    }
}

然后在模型中配置即可:

public function behaviors() {
    return [
        [
            'class' => \your\namespace\ArrayAttributesBehavior::className(),
            'attributes' => ['payment_options'],
        ],
    ];
}

然后请记住,当您制作表单、验证等时,这些属性是数组