mirror of
https://github.com/yiisoft/yii2.git
synced 2025-08-26 14:26:54 +08:00
Added Controller::populate().
This commit is contained in:
@ -1,9 +1,9 @@
|
||||
<?php
|
||||
|
||||
use yii\web\Controller;
|
||||
use app\models\LoginForm;
|
||||
use app\models\User;
|
||||
|
||||
class SiteController extends \yii\web\Controller
|
||||
class SiteController extends Controller
|
||||
{
|
||||
public function actionIndex()
|
||||
{
|
||||
@ -13,15 +13,13 @@ class SiteController extends \yii\web\Controller
|
||||
public function actionLogin()
|
||||
{
|
||||
$model = new LoginForm();
|
||||
if (isset($_POST[$model->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()
|
||||
|
@ -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;
|
||||
|
@ -302,6 +302,34 @@ class Controller extends Component
|
||||
return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
|
Reference in New Issue
Block a user