With the model, we can start to write the logic for operating the model. We place this logic in the action of a controller. For the example of a logon form, the corresponding code is: publicfunctionactionLogin (){...
With the model, we can start to write the logic for operating the model. We place this logic in the action of a controller. For the example of a logon form, the corresponding code is:
Public function actionLogin () {$ model = new LoginForm; if (isset ($ _ POST ['loginform']) {// collect user input data $ model-> attributes = $ _ POST ['loginform']; // verify user input, and redirect to the previous page if ($ model-> validate () $ this-> redirect (Yii: app () -> user-> returnUrl);} // display the login form $ this-> render ('login', array ('model' => $ model ));}
As shown above, we first createLoginFormModel example; if the request is a POST request (meaning the login form has been submitted), we use the submitted data$_POST['LoginForm']Fill$modelThen we verify this input. if the verification succeeds, redirect the user's browser to the page that previously needed authentication. If verification fails or this action is accessed for the first time, we renderloginView. the content of this view is described in the next section.
Tip:InloginAction, we useYii::app()->user->returnUrlObtain the URL of the page that requires authentication. ComponentsYii::app()->userIs a CWebUser (or its subclass) that represents user session information (such as user name and status ). For more details, refer to verification and authorization.
Let's take a special note.loginThe following PHP statement appears in the action:
$model->attributes=$_POST['LoginForm'];
As we mentioned in the security feature assignment, this line of code uses the data submitted by the user to fill the model.attributesThe attribute is defined by CModel. it accepts a name-value pair array and assigns each value to the corresponding model feature. Therefore, if$_POST['LoginForm']Given an array like this, the code above is equivalent to the lengthy section below (assuming that the array contains all the required features ):
$model->username=$_POST['LoginForm']['username'];$model->password=$_POST['LoginForm']['password'];$model->rememberMe=$_POST['LoginForm']['rememberMe'];
Note:To enable$_POST['LoginForm']What is passed to us is an array rather than a string. we need to follow a standard when naming form fields. Specific, corresponding to model classCFeatures inaForm field, we name itC[a]. For example, we can useLoginForm[username]NameusernameForm field corresponding to the feature.
The rest is to createloginView. it should contain an HTML form with the required input.
The above is the Yii Framework official guide series 18-use form: Create action content. For more information, see PHP Chinese website (www.php1.cn )!