未知属性并以Yii2格式以编程方式添加文本字段

时间:2016-05-24 15:38:50

标签: php yii2

我正在添加动态表单字段:

<?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属性?

1 个答案:

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