Load virtual attribute into model?

I’m very new to PHP frameworks, so this might be a simple question.

I have a [font="Courier New"]User[/font] model class which has a [font="Courier New"]password2[/font] virtual attribute so that [font="Courier New"]password[/font] can be verified against [font="Courier New"]password2[/font].


class Usager extends \yii\db\ActiveRecord

{

	public $password2;

}

When I call [font="Courier New"]$model->load()[/font], it does not populate the [font="Courier New"]password2[/font] attribute. It is in [font="Courier New"]$request->post()[/font]. The only way I found was to do it manually like this, but I feel this is not the best solution.


$model->load($request->post());

$model->password2 = $request->post($model->formName())['password2'];

I also have the same situation in a [font="Courier New"]UserSearch[/font] model class where I have a [font="Courier New"]keyword[/font] attribute that searches in [font="Courier New"]firstName[/font] and [font="Courier New"]lastName[/font] columns in the database.

What is the proper way to do this?

This is maybe because the attribute password2 is not "safe" (security).

You have to include it into the rules fo the model :




public function rules()

{

  return [

    ...

    ['password2', 'safe'],

  ];

}



If the attribute is not safe, it will not be populated for security reason.

You can use the validator "compare" in your case : http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html#compare

That worked, thanks! I read a little bit more in the manual about safe rules and it all makes sense now.