1

I am adding dynamic form field:

<?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 } ?>

I've declared it safe in the rules():

$channels = Channel::find()->all();

foreach ( $channels as $channel ) {
    $rules[] = [['channel_' . $channel->name], 'safe'];
}

return $rules;

However I'm getting an error:

Getting unknown property: app\models\MyModel::channel_facebook

How do I dynamically declare the 'channel_' . $channel->name properties in Yii2?

1 Answer 1

1

You could simply override attributes(), e.g. :

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.