Once we have a model, we can start to write logic that is needed to manipulate the model. We place this logic inside a controller action. For the login form example, the following code is needed:
public function actionLogin()
{
$form=new LoginForm;
if(isset($_POST['LoginForm']))
{
// collects user input data
$form->attributes=$_POST['LoginForm'];
// validates user input and redirect to previous page if validated
if($form->validate())
$this->redirect(Yii::app()->user->returnUrl);
}
// displays the login form
$this->render('login',array('user'=>$form));
}
In the above, we first create a LoginForm
instance; if the request is a
POST request (meaning the login form is submitted), we populate $form
with the submitted data $_POST['LoginForm']
; we then validate the input
and if successful, redirect the user browser to the page that previously
needed authentication. If the validation fails, or if the action is
initially accessed, we render the login
view whose content is to be
described in the next subsection.
Tip: In the
login
action, we useYii::app()->user->returnUrl
to get the URL of the page that previously needed authentication. The componentYii::app()->user
is of type CWebUser (or its child class) which represents user session information (e.g. username, status). For more details, see Authentication and Authorization.
Let's pay special attention to the following PHP statement that appears in
the login
action:
$form->attributes=$_POST['LoginForm'];
As we described in Securing Attribute Assignments,
this line of code populates the model with the user submitted data.
The attributes
property is defined by CModel which
expects 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 would be equivalent to the following lengthy
one (assuming every needed attribute is present in the array):
$form->username=$_POST['LoginForm']['username'];
$form->password=$_POST['LoginForm']['password'];
$form->rememberMe=$_POST['LoginForm']['rememberMe'];
Note: In order to let
$_POST['LoginForm']
to give us an array instead of a string, we stick to a convention when naming input fields in the view. In particular, for an input field corresponding to attributea
of model classC
, we name it asC[a]
. For example, we would useLoginForm[username]
to name the input field corresponding to theusername
attribute.
The remaining task now is to create the login
view which should contain
an HTML form with the needed input fields.
Signup or Login in order to comment.