0
votes

I've created an ActiveRecord Model where a user enters their email and gets added to a database in Yii2. When they're added to the database, I want to update one of my properties based on which view they entered the information from. I know Yii2 lets you set a default value in your model, like

public function rules()
{
    return [
        [['view'], 'default', 'value' => a]
    ]
}

But I'm not sure how to set a different default value based on each view. In my view where I have the form->field($model, 'email') and submit for user input, I tried setAttribute and setAttributes and creating my own set method, but they all fail to set the property (I'm guessing they'd work if I say queried my db and performed them on an already existing instance of my Model).

I'm sure I'm overlooking something really simple

1
Maybe you are looking for something like this: \Yii::$app->controller->action->id? you can put it in the rules function instead of a - Ziki
Add a hidden field to your form in the view, indicating the view. In your controller, evaluate the field's value and set the model's property accordingly. - Patrick
Ziki, That might have worked but all views are handled by actionIndex so they'd have the same id I'm guessing @Patrick That worked great for me. I didn't even evaluate it in the controller, I just set the model's property directly with the hidden field. Thanks! - user3505195

1 Answers

0
votes

You shouldn't define default value based on current view, because models (in general) can be used not from views, but form console applications or other places in your code not related to specific view.

As @Patrick said you can add hidden field in each view like:

<?= $form->field($model, 'view')->hiddenInput(['value'=> $this->id /* view id or whatever */])->label(false);