我正在添加动态表单字段:
<?php
$channels = Channel::find()->all();
foreach ( $channels as $channel ) {
$channel_name = 'channel_' . strtolower( $channel->name );
?>
<div class="col-xs-2">
<?= $form->field( $model, $channel_name )->textInput()->label( $channel->name ) ?>
</div>
<?php } ?>
我在rules()
:
$channels = Channel::find()->all();
foreach ( $channels as $channel ) {
$rules[] = [['channel_' . $channel->name], 'safe'];
}
return $rules;
但是我收到了错误:
获取未知属性:app \ models \ MyModel :: channel_facebook
如何在Yii2中动态声明'channel_' . $channel->name
属性?
答案 0 :(得分:1)
您可以简单地覆盖attributes()
,例如:
public function attributes()
{
// just an example, not really efficient but it will work
$attributes = [];
$channels = Channel::find()->all();
foreach ($channels as $channel) {
$attributes[] = 'channel_' . strtolower($channel->name);
}
return array_merge(parent::attributes(), $attributes);
}