From 06fa0259b55173b6c6ed142aeed874f9f04defbd Mon Sep 17 00:00:00 2001 From: Qiang Xue Date: Mon, 29 Apr 2013 23:13:10 -0400 Subject: [PATCH] Added Controller::populate(). --- app/protected/controllers/SiteController.php | 18 ++++++++---------- app/protected/models/LoginForm.php | 2 +- framework/base/Controller.php | 28 ++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 11 deletions(-) diff --git a/app/protected/controllers/SiteController.php b/app/protected/controllers/SiteController.php index 6130c5b..39e9c1f 100644 --- a/app/protected/controllers/SiteController.php +++ b/app/protected/controllers/SiteController.php @@ -1,9 +1,9 @@ formName()])) { - $model->attributes = $_POST[$model->formName()]; - if ($model->login()) { - Yii::$app->getResponse()->redirect(array('site/index')); - } + if ($this->populate($_POST, $model) && $model->login()) { + Yii::$app->getResponse()->redirect(array('site/index')); + } else { + echo $this->render('login', array( + 'model' => $model, + )); } - echo $this->render('login', array( - 'model' => $model, - )); } public function actionLogout() diff --git a/app/protected/models/LoginForm.php b/app/protected/models/LoginForm.php index d77aa5d..b68e146 100644 --- a/app/protected/models/LoginForm.php +++ b/app/protected/models/LoginForm.php @@ -42,7 +42,7 @@ class LoginForm extends Model { if ($this->validate()) { $user = User::findByUsername($this->username); - Yii::$app->getUser()->login($user); + Yii::$app->getUser()->login($user, $this->rememberMe ? 3600*24*30 : 0); return true; } else { return false; diff --git a/framework/base/Controller.php b/framework/base/Controller.php index 0d46235..583de60 100644 --- a/framework/base/Controller.php +++ b/framework/base/Controller.php @@ -303,6 +303,34 @@ class Controller extends Component } /** + * Populates one or multiple models from the given data array. + * @param array $data the data array. This is usually `$_POST` or `$_GET`, but can also be any valid array. + * @param Model $model the model to be populated. If there are more than one model to be populated, + * you may supply them as additional parameters. + * @return boolean whether at least one model is successfully populated with the data. + */ + public function populate($data, $model) + { + $success = false; + if (!empty($data) && is_array($data)) { + $models = func_get_args(); + array_shift($models); + foreach ($models as $model) { + /** @var Model $model */ + $scope = $model->formName(); + if ($scope == '') { + $model->attributes = $data; + $success = true; + } elseif (isset($data[$scope])) { + $model->attributes = $data[$scope]; + $success = true; + } + } + } + return $success; + } + + /** * Renders a view and applies layout if available. * * The view to be rendered can be specified in one of the following formats: