Initialising related models with blank values

Hi all,

I’ve got a given model User that has HAS_ONE relation with the UserProfile entity.

I’m building a new ActiveForm and would like to initialize objects as follows:




$user=new User();

$user->scenario='create';

$user->userProfile=new UserProfile();

$user->useProfile->scenario('create');


return $this->render('form,array('user'=>$user));



Yii2 would issue an exception

This is to avoid passing numerous variables to the view, I was thinking about passing the primary model, with all the relations established.

Any ideas on how to overcome this issue?

Solution #1

to inherit ActiveRecord and introduce the following overridden method:


 public  function hasOne($class,$link)

    {


        if($this->isNewRecord)

        {

            // this is a new record, no class yet return empty instance


            return new $class;

        }

        parent::hasOne($class,$link);





    }