With the model in hand, we can start writing the logic for operating this model. We put this logic in a controller action. For the login form example, the corresponding code is:
public function actionLogin() { $model=new LoginForm; if(isset($_POST['LoginForm'])) { // 收集用户输入的数据 $model->attributes=$_POST['LoginForm']; // 验证用户输入,并在判断输入正确后重定向到前一页 if($model->validate()) $this->redirect(Yii::app()->user->returnUrl); } // 显示登录表单 $this->render('login',array('model'=>$model)); }
As shown above, we first created a LoginForm
Model example; If the request is a POST request (meaning that the login form was submitted), we use the submitted data $_POST['LoginForm']
to fill in $model
; We then validate this input and, if the validation is successful, redirect the user's browser to the page that previously required authentication. If the verification fails, or this action is accessed for the first time, we render the login
view. We will explain the content of this view in the next section.
Tips: In the
login
action, we useYii::app()->user->returnUrl
Get the URL of the page that previously required authentication. ComponentYii::app()->user
is a CWebUser (or its subclass) that represents user session information (e.g. username, status). For more details, please refer to Authentication and Authorization.
Let us pay special attention to the following PHP statement that appears in the login
action:
$model->attributes=$_POST['LoginForm'];
As we discussed in Safe Property Assignment , this line of code populates the model with user-submitted data. attributes
Attributes are defined by CModel, which accepts an array of name-value pairs and assigns each value to the corresponding model attribute. So if $_POST['LoginForm']
gives us such an array, the above code is equivalent to the following lengthy paragraph (assuming all the required properties are present in the array):
$model->username=$_POST['LoginForm']['username']; $model->password=$_POST['LoginForm']['password']; $model->rememberMe=$_POST['LoginForm']['rememberMe'];
loginNote: In order to use
All that's left now is to create the$_POST['LoginForm']
What is passed to us is an array instead of a string. We need to follow a convention when naming form fields. Specifically, we name the form field corresponding to the featurea
in the model classC
. For example, we can useLoginForm[username]
to name the form field corresponding to theusername
attribute.
view, which should contain an HTML form with the required inputs. The above is the Yii Framework Official Guide Series 18 - Using Forms: Creating Actions. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!