Yii2:如何使用comma-sep属性。 checkboxList()中的值列表

时间:2017-07-27 20:19:49

标签: php yii2 checkboxlist

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

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

但默认情况下,没有选中任何复选框。如何指示Yii用逗号分割(爆炸)值?并且,我认为,在插回数据库之前再次连接(implode)?

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

1 个答案:

答案 0 :(得分:0)

我发现这是最好,最有条理的做法。

创建behavior(例如,在ArrayAttributes.php文件夹中创建文件components并设置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'],
        ],
    ];
}

然后请记住,当您进行表单,验证等时,这些属性是数组。