You can use scripts inside your model for this, but you will need to extend the toArray method so that it works correctly:
public function scenarios() { return array_merge(parent::scenarios(), [ 'simple_info' => [ 'email', 'name', ], 'login' => [ 'id', 'email', 'name', 'auth_token', ], ]); } public function toArray(array $fields = array(), array $expand = array(), $recursive = true) { $scenarios = $this->scenarios(); $scenario = $this->getScenario(); if (!empty($scenarios[$scenario])) { $data = parent::toArray($fields, $expand, $recursive); return array_intersect_key($data, array_flip($scenarios[$scenario])); } return parent::toArray($fields, $expand, $recursive); }
After that, you can simply do something like this:
$model = new LoginForm(); if ($model->load(Yii::$app->request->post(), '') && $model->login()) { $user = $model->getUser(); // Lets change scenario to login in order to get `auth_token` for authorization $user->setScenario('login'); $user->generateAuthKey(); $user->save(FALSE); return $user; } else { return $model; }
source share