Example of form usage in Yii _php

Source: Internet
Author: User
Tags valid email address
The example in this article describes the form usage in Yii. Share to everyone for your reference, as follows:

When working with forms in Yii, the following steps are usually required:

1. Create a model class to represent the data fields that you want to collect.
2. Create a controller action to respond to the form submission.
3. Create a form in the view script that is related to the controller action.

First, create the model

Before we write the HTML code needed for a form, we should first determine the type of data that comes from the end user and what rules the data should conform to. Model classes can be used to record this information. As defined in the model chapters, the model is the central location for saving user input and validating these inputs.

We can create two types of models, depending on how you use the data entered by the user. If the user input is collected, used and then discarded, we should create a form model;

If the user's input is collected and saved to the database, we should use an active Record. The two types of models share the same base class, CModel, which defines the common interfaces required for the form.

1. Defining Model Classes

For example, create a form model:

Class LoginForm extends Cformmodel{public $username;p ublic $password;p ublic $rememberMe =false;}

Three properties are defined in LoginForm: $username, $password, and $rememberme. They are used to save user-entered user names and passwords, and whether the user wants to remember his login options. Because the $rememberMe has a default value of FALSE, the corresponding option will be unchecked when the initialization is displayed in the login form.

We refer to these member variables as attributes (attributes) rather than attributes (properties) to distinguish them from normal attributes (properties). An attribute (attribute) is a property that is primarily used to store data from user input or database (propertiy).

2. Declaration Validation rules

Once the user submits his input and the model is populated, we need to make sure that the user's input is valid before use. This is done by validating the user's input and a series of rules. We specify these validation rules in the Rules () method, and this method should return a rule configuration array.

Class LoginForm extends Cformmodel{public $username;p ublic $password;p ublic $rememberMe =false;private $_identity; Public Function rules () {return Array (' username, password ', ' required '),//username and password are required for array (' RememberMe ', ' Boolean '),//rememberme should be a Boolean value of array (' Password ', ' Authenticate '),//password should be verified (authenticated));} Public function Authenticate ($attribute, $params) {$this->_identity=new useridentity ($this->username, $this- >password); if (! $this->_identity->authenticate ()) $this->adderror (' password ', ' wrong user name or password. ');}}

Each rule returned by the rules () must be in the following format:
Copy the code as follows: Array (' attributelist ', ' Validator ', ' on ' = ' scenariolist ', ... Additional options)
which

AttributeList (attribute list) is an attribute list string that needs to be validated by this rule, with each attribute name separated by commas;
Validator (Authenticator) specifies the kind of validation to be performed;
The on parameter is optional, which specifies the list of scenes to which this rule should be applied;

An additional option is an array of name values used to initialize the property values of the corresponding validator.

There are three ways to specify Validator in validation rules:

First, Validator can be the name of a method in a model class, just like the authenticate in the example above. The validation method must be the following structure:
Copy the Code Code as follows: Public Function validator Name ($attribute, $params) {...}
Second, validator can be the name of a validator class, and when this rule is applied, an instance of a validator class is created to perform the actual validation. Additional options in the rule are used to initialize the property values of the instance. The validator class must inherit from Cvalidator.

Third, Validator can be an alias for a predefined validator class. In the example above, the required name is the alias of Crequiredvalidator, which is used to ensure that the attribute value being validated is not NULL. The following is a complete list of predefined authenticator aliases:

Boolean:cbooleanvalidator alias, ensure that the attribute has a Cbooleanvalidator::trueva lue or Cbooleanvalidator::falseva lue value.
Captcha:ccaptchavalidator, ensure that the attribute value is equal to the verification code shown in Captcha.
Compare:ccompareva the alias of the Lidator, ensuring that the attribute equals another attribute or constant.
Email:cemailvalidator alias, ensure that the feature is a valid email address.
Default:cdefaultvalueva the alias of the Lidator, specifying the default value for the attribute.
Exist:cexistvalidator, make sure that the attribute values can be found in the columns of the specified table.
File:cfileva Lidator alias to ensure that the feature contains a name for the uploaded file.
The alias of Filter:cfiltervalidator, which changes this feature through a filter.
In:crangeva the alias of the Lidator to ensure that the data is within the range of a pre-specified value.
The alias of the Length:cstringvalidator to ensure that the length of the data is within a specified range.
The alias of the Match:cregularexpressionvalidator to ensure that the data can match a regular expression.
The alias of the Numerical:cnumbervalidator to ensure that the data is a valid number.
The alias of the Required:crequiredvalidator to ensure that the attribute is not empty.
Type:ctypeva the alias of the Lidator, ensuring that the attribute is the specified data type.
Unique:cuniqueva the alias of the Lidator to ensure that the data is unique in the data table column.
The alias of the Url:curlvalidator to ensure that the data is a valid URL.

Here are a few examples of these pre-defined validators:

User name is required array (' username ', ' required '),//username must be between 3 and 12 characters in Array (' username ', ' length ', ' min ' =>3, ' Max ' =>12),//In In the registration scenario, the password password must be consistent with PASSWORD2. Array (' password ', ' compare ', ' compareattribute ' = ' password2 ', ' on ' = ' register '),//In the login scenario, the password must be validated. Array (' Password ', ' Authenticate ', ' on ' = ' login '),

3, the security of the characteristics of the assigned value

After an instance of a class is created, we usually need to populate its attributes with the data submitted by the end user. This can be done easily with the following block assignment (massive assignment):

$model =new loginform;if (isset ($_post[' loginform ')) $model->attributes=$_post[' LoginForm '];

The final expression is called a block assignment (massive assignment), which copies each item in $_post[' LoginForm ' to the corresponding model attribute. This is equivalent to the following assignment method:

foreach ($_post[' LoginForm ') as $name + = $value) {if ($name is a security feature) $model $name = $value;}

It is important to detect the security of an attribute, for example, if we assume that the primary key of a table is safe and expose it, then an attacker could gain an opportunity to modify the record's primary key, thereby tampering with the content that was not authorized to him.

An attribute is considered safe if it appears in a validation rule for the corresponding scenario. For example:

Array (' Username, password ', ' required ', ' on ' = ' login, register '), array (' email ', ' required ', ' on ' = ' register '),

As shown above, the username and password features are required in the login scenario. The username, password, and email features are required in the register scenario. So, if we execute the block assignment in the login scene, only username and password will be assigned to the block. Because only they appear in the validation rules of login. On the other hand, if the scene is a register, these three attributes can all be assigned to a block.

$model=new User (' login ') in the login scenario, if (Isset ($_post[' user ')) $model->attributes=$_post[' user '];//in the registration scenario $model= New User (' register '), if (Isset ($_post[' user ')) $model->attributes=$_post[' user '];

So why do we use such a strategy to detect the security of a feature? The rationale behind this is this: If a feature already has one or more validation rules that can detect validity, what are we worried about?

Keep in mind that validation rules are used to check the data entered by the user, rather than checking the data we generate in the code (such as timestamps, auto-generated primary keys). Therefore, do not add validation rules for attributes that do not accept end-user input.

Sometimes we want to declare that a feature is safe, even if we don't specify any rules for it. For example, the content of an article can accept any input from the user. We can use special safe rules to do this:
Copy the code as follows: Array (' content ', ' safe ')
There is also an unsafe rule that declares a property to be unsafe:
Copy the Code code as follows: Array (' permission ', ' unsafe ')
Unsafe rules are not commonly used and are an exception to the security features we defined earlier.

4. Trigger Verification

Once the model is populated with data submitted by the user, we can call Cmodel::validate () to trigger the data validation process. This method returns a value that indicates whether the validation was successful. For the Cactiverecord model, validation can also be triggered automatically when we call its Cactiverecord::save () method.

We can set the scene properties by setting the scenario property so that the validation rules for the corresponding scene will be applied.

Validation is performed based on the scenario. The Scenario property specifies the scene currently used by the model and the set of validation rules currently in use. For example, in the login scenario, we only want to validate the username and password inputs in the user model, and in the register scenario, we need to verify more input, such as email, address, and so on. The following example shows how to perform validation in the Register scenario:

Create a User model in the registration scenario. Equivalent to://$model =new user;//$model->scenario= ' register '; $model =new User (' register '); Add a parameter to the model class, which is the validation scenario to be triggered//fill the input value into the model $model->attributes=$_post[' User '];//perform validation if ($model->validate ())  / /If the input is valid ... else ...

The scene associated with the rule can be specified by the ON option in the rule. If the on option is not set, the rule is applied to all scenarios. For example:

Public Function rules () {return Array (' username, password ', ' required '), Array (' password_repeat ', ' Required ', ' On ' = = ' register '), Array (' Password ', ' compare ', ' on ' = ' register '),);

The first rule will apply to all scenarios, and the second will only be applied to the register scene.

5. Extraction validation Error

When validation is complete, any errors that may be generated will be stored in the model object. We can extract these error messages by calling Cmodel::geterrors () and Cmodel::geterror (). The difference between the two methods is that the first method returns error information for all model attributes, and the second returns only the first error message.

6. Characteristic label

When designing a form, we usually need to display a label for each form field. The tag tells the user what information he should fill out in this form field. Although we can hardcode a label in the view, it is more flexible and convenient if we specify (label) in the corresponding model.

By default CModel will simply return the name of the attribute as its label. This can be customized by overriding the Attributelabels () method. As we'll see in the next sections, assigning tags in the model will allow us to create more powerful forms faster.

Second, create the action

With the model, we can begin to write the logic for manipulating this model. We put this logic in the action of a controller. For examples of login forms, the corresponding code is:

Public Function Actionlogin () {$model =new loginform;if (isset ($_post[' loginform ')) {//collects data entered by the user $model-> attributes=$_post[' LoginForm '];//validates the user input and redirects to the previous page if the input is correct ($model->validate ()) $this->redirect (Yii::app () ->user->returnurl); Redirect to a page that requires authentication url}//displays the login form $this->render (' login ', array (' model ' = $model));}

As shown above, we first created an example of a loginform model, and if the request is a POST request (which means that the login form was submitted), we populate the $model with the submitted data $_post[' LoginForm '), and then we validate the input, If the validation succeeds, redirect the user's browser to a page that previously required authentication. If the validation fails, or if the action is first accessed, we render the login view, and the contents of this view will be explained in a later section.

Tip: In the login action, we use Yii::app ()->user->returnurl to get the URL of the page that needs authentication before. Component Yii::app ()->user is a cwebuser (or its subclasses) that represents user session information (such as user name, state).

Let's pay special attention to the following PHP statement that appears in the login action:
Copy the Code code as follows: $model->attributes=$_post[' loginform '];
As we said in the Secure attribute assignment, this line of code populates the model with user-submitted data. The Attributes property is defined by Cmodel, which accepts an array of name values and assigns each value to the corresponding model attribute. So if $_post[' loginform ' gives us an array like this, the code above is equivalent to the lengthy paragraph (assuming all the required attributes exist in the array):

$model->username=$_post[' loginform ' [' username ']; $model->password=$_post[' loginform ' [' Password '];$ model->rememberme=$_post[' loginform ' [' rememberme '];

Note: In order for the $_post[' LoginForm ' to pass to us an array rather than a string, we need to follow a specification when naming form fields. Specifically, the form field that corresponds to attribute a in model class C, we name it c[a]. For example, we can use Loginform[username] to name the corresponding form field of the username attribute.

Now the rest of the job is to create the login view, which should contain an HTML form with the required input.

Iii. Creating forms

Writing the login view is simple, and we start with a form tag whose Action property should be the URL of the login action described earlier. Then we need to insert labels and form fields for the attributes declared in the LoginForm class. Finally, we insert a submit button that can be clicked by the user to submit this form. All of this can be done with pure HTML code.

YII provides several helper (helper) classes for simplified view writing. For example, to create a text input field, we can call Chtml::textfield (); To create a drop-down list, call CHtml::d ropdownlist ().
For example, the following code generates a text input field that can touch the post-commit action when the user modifies its value.
Copy the code as follows: Chtml::textfield ($name, $value, Array (' submit ' = ') ');
Below, we use CHtml to create a login form. We assume that the variable $model is an instance of LoginForm.

The code above generates a more dynamic form, for example, Chtml::activelabel () generates a label that is related to the characteristics of the specified model. If this attribute has an input error, the CSS class of this tag becomes error, and the CSS style changes the appearance of the label. Similarly, Chtml::activetextfield () generates a text input field for the properties of the specified model and changes its CSS class when an error occurs.

We can also use a new small object cactiveform to simplify form creation. This small object can provide both client and server-side seamless, consistent validation. With Cactiveform, the above code can be rewritten as:

Beginwidget (' Cactiveform ');? >errorsummary ($model);? >label ($model, ' username ');? >textfield ($model, ' Username ')? >label ($model, ' password ');? >passwordfield ($model, ' password ')? >checkbox ($model, ' rememberme ') );? >label ($model, ' rememberme ');? >endwidget ();?>

Iv. Collection of form inputs

Sometimes we want to collect user input through batch mode. That is, users can enter information for multiple model instances and submit them once. We refer to this as tabular input (tabular input) because these entries are usually rendered as HTML tables.

To use tabular input, we first need to create or populate a model instance array, depending on whether we want to insert or update the data. We then extract the user-entered data from the $_post variable and assign it to each model. One thing that is slightly different from the single model input is that we use $_post[' Modelclass ' [$i] to extract the input data instead of using $_post[' Modelclass '.

Public Function Actionbatchupdate () {//Assume that each item is an instance of the ' Item ' class,//extract items to be updated in bulk mode $items= $this->getitemstoupdate ( if (isset ($_post[' item ')) {$valid =true;foreach ($items as $i + $item) {if (Isset ($_post[' item '] [$i])) $item attributes=$_post[' Item ' [$i]; $valid = $valid && $item->validate ();} if ($valid)//If all items are valid//... Then do some operations here}//Display View Collection table input $this->render (' batchUpdate ', Array (' items ' = $items));}

Ready for this action, we need to continue working with the BatchUpdate view to display the entries in an HTML table.

Namepricecountdescription$item):?>

Note that in the above code we used "[$i]name" instead of "name" as the second parameter when calling Chtml::activetextfield.

If there are any validation errors, the corresponding entries will be highlighted automatically, just like the single model input we explained earlier.

It is hoped that this article is helpful to the PHP program design based on YII framework.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.