Yii2:如何使用带有逗号的属性. 复选框列表()中的值列表



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

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

但默认情况下不会选中任何复选框。如何指示 Yii 用逗号拆分(分解(值?而且,我认为,在插入回数据库之前再次连接(内爆(?

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

我发现这是最好和最有条理的方法。

创建一个行为(例如,在文件夹中创建文件ArrayAttributes.phpcomponents并设置namespace appcomponents;(:

use yiidbActiveRecord;
use yiibaseBehavior;
/**
* 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' => yournamespaceArrayAttributesBehavior::className(),
'attributes' => ['payment_options'],
],
];
}

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

最新更新