Examples of form usage in Yii

Source: Internet
Author: User
Tags valid email address
This article mainly introduces the form usage in Yii, and summarizes various common forms operation skills in Yii based on the detailed analysis of the instance form, which has some reference value, you can refer to the following example to describe how to use a form in Yii. We will share this with you for your reference. The details are as follows:

To process a form in Yii, follow these steps:

1. create a model class to represent the fields to be collected.
2. create a controller action and submit the response form.
3. create a form related to the controller action in the view script.

I. create a model

Before writing the HTML code required for the form, we should first determine the type of data input from the end user and the rules that the data should comply. The model class can be used to record this information. As defined in the model section, the model is the central location for storing user input and verifying these inputs.

You can create two types of models based on the data input by the user. If user input is collected, used, and discarded, we should create a form model;

If your input is collected and saved to the database, an Active Record should be used. The two types of models share the same basic class CModel, which defines the common interfaces required by the form.

1. define model classes

For example, create a form model:

class LoginForm extends CFormModel{public $username;public $password;public $rememberMe=false;}

LoginForm defines three attributes: $ username, $ password, and $ rememberMe. They are used to save the user name and password entered by the user, and whether the user wants to remember his logon options. Because $ rememberMe has a default value of false, the corresponding options are not checked during initialization.

These member variables are called attributes instead of properties to distinguish them from common properties ). Attribute is an attribute used to store user input or database data ).

2. declare verification rules

Once the user submits his input and the model is filled, we need to ensure that the user input is valid before use. This is achieved by verifying user input and a series of rules. We specify these verification rules in the rules () method. this method should return an array of rule configurations.

Class LoginForm extends CFormModel {public $ username; public $ password; public $ rememberMe = false; private $ _ identity; public function rules () {return array ('username, password ', 'required'), // The username and password are required. array ('rememberme', 'boolean '), // rememberMe should be a Boolean value array ('password', 'authenticate'), // password should be verified (authenticated);} public function authenticate ($ attribute, $ params) {$ this-> _ identi Ty = new UserIdentity ($ this-> username, $ this-> password); if (! $ This-> _ identity-> authenticate () $ this-> addError ('password', 'incorrect user name or password. ');}}

Each rule returned by rules () must be in the following format:

The code is as follows:

Array ('butbutelist', 'validator', 'on' => 'scenariolist',... additional options)


Where:

AttributeList (feature list) is a feature list string that needs to be verified by this rule. each feature name is separated by a comma;
Validator (validators) specifies the type of verification to be performed;
The on parameter is optional. it specifies the list of scenarios that the rule should be applied;

The additional option is an array of name-value pairs used to initialize the attribute values of the corresponding validators.

You can specify Validator in the verification rules in three ways:

First, Validator can be the name of a method in the model class, just like authenticate in the above example. The verification method must be in the following structure:

The code is as follows:

Public function validator name ($ attribute, $ params ){...}


Second, Validator can be the name of a Validator class. when this rule is applied, instances of a Validator class will be created for actual verification. The additional options in the rule are used to initialize the attribute value of the instance. The validators class must inherit from CValidator.

Third, Validator can be an alias for a predefined Validator class. In the preceding example, the required name is the alias of CRequiredValidator, which is used to ensure that the verified feature value is not empty. The following is a complete list of predefined authenticator aliases:

Boolean: the alias of CBooleanValidator to ensure that the feature has a CBooleanValidator: trueva lue or CBooleanValidator: falseva lue value.
Captcha: the alias of CCaptchaValidator to ensure that the feature value is equal to the verification code displayed in CAPTCHA.
Compare: the alias of CCompareva lidator to ensure that the feature is equal to another feature or constant.
Email: the alias of CEmailValidator to ensure that the feature is a valid Email address.
Default: the alias of cdefavaluvalueva lidator, which specifies the default value of the feature.
Exist: the alias of CExistValidator to ensure that the feature value can be found in the column of the specified table.
File: the alias of CFileva lidator to ensure that the feature contains the name of an uploaded file.
Filter: the alias of CFilterValidator. you can use a filter to change this feature.
In: the alias of CRangeva lidator to ensure that the data is within the range of a pre-specified value.
Length: the alias of CStringValidator to ensure that the data length is within a specified range.
Match: the alias of CRegularExpressionValidator to ensure that the data can match a regular expression.
Numerical: the alias of CNumberValidator to ensure that the data is a valid number.
Required: the alias of CRequiredValidator to ensure that the feature is not empty.
Type: the alias of CTypeva lidator to ensure that the feature is of the specified data type.
Unique: The alias of CUniqueva lidator to ensure that the data is unique in the columns of the data table.
Url: the alias of CUrlValidator to ensure that the data is a valid URL.

Below are a few examples of using only these predefined validators:

// The username is required. array ('username', 'required'), // The username must be between 3 and 12 characters in array ('username', 'length ', 'Min' => 3, 'Max '=> 12), // in the registration scenario, the password and password must be consistent with password2. Array ('password', 'Company', 'companyattribute '=> 'password2', 'on' => 'register '), // In The logon scenario, the password must be verified. Array ('password', 'authenticate', 'on' => 'login '),

3. security feature assignment

After a class instance is created, we usually need to fill in its features with the data submitted by the end user. This can be easily implemented through the following massive assignment method:

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

The final expression is called a block assignment (massive assignment). It copies each item in $ _ POST ['loginform'] to the corresponding model features. This is equivalent to the following assignment method:

Foreach ($ _ POST ['loginform'] as $ name => $ value) {if ($ name is a secure feature) $ model-> $ name = $ value ;}

The security of the detection feature is very important. for example, if we think that the primary key of a table is safe and exposed, attackers may be given the opportunity to modify the primary key of the record, in this way, unauthorized content is tampered.

If a feature appears in a verification rule in the corresponding scenario, it is considered safe. For example:

array('username, password', 'required', 'on'=>'login, register'),array('email', 'required', 'on'=>'register'),

As shown above, the username and password features are mandatory in the login scenario. The username, password, and email features are mandatory in the register scenario. Therefore, if we execute block assignment in the login scenario, only username and password will be assigned a block assignment. Because they only appear in the verification rules of login. On the other hand, if the scenario is register, all three features can be assigned a value.

// In the login scenario, $ model = new User ('login'); 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 this policy to check whether the features are secure? The basic principle behind this is: if one feature already has one or more validation rules that can detect validity, what do we worry about?

Remember that verification rules are used to check user input data rather than the data we generate in the code (such as timestamp, automatically generated primary key ). Therefore, do not add verification rules for features that do not accept end user input.

Sometimes, we want to declare that a feature is secure, even if we do not 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 for this purpose:

The code is as follows:

Array ('content', 'Safe ')


There is also an unsafe rule that declares an insecure attribute:

The code is as follows:

Array ('permission', 'unsafe ')


Unsafe rules are not commonly used. they are an exception to the security features we have previously defined.

4. trigger verification

Once the model is filled with data submitted by the user, we can call CModel: validate () to trigger the data verification process. This method returns a value indicating whether the verification is successful. For the CActiveRecord model, verification can also be automatically triggered when we call its CActiveRecord: save () method.

You can set the scene attribute by setting the scenario attribute, so that the verification rules for the corresponding scenario will be applied.

Verification is performed based on scenarios. The scenario attribute specifies the scenario currently used by the model and the currently used verification rule set. For example, in the login scenario, we only want to verify the username and password input in the user model. in the register scenario, we need to verify more input, such as email, address, and so on. The following example demonstrates how to perform verification 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 verification scenario to be triggered. // fill the input value in the model $ model-> attributes = $ _ POST ['user']; // execute the verification if ($ model-> validate () // if the input is valid... else...

The scenario associated with a rule can be specified by the on option in the rule. If the on option is not set, this rule applies to all scenarios. For example:

public function rules(){return array(array('username, password', 'required'),array('password_repeat', 'required', 'on'=>'register'),array('password', 'compare', 'on'=>'register'),);}

The first rule applies to all scenarios, and the second rule applies only to register scenarios.

5. extraction verification error

After verification is completed, any possible errors 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 messages for all model features, and the second method returns only the first error message.

6. feature labels

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 in this form field. Although we can hard encode a tag in the view, it is more flexible and convenient if we specify the tag in the corresponding model.

By default, CModel uses the name of a simple returned feature as its tag. This can be customized by overwriting attributeLabels. As we will see in the following section, specifying tags in the model will allow us to create more powerful forms faster.

2. create actions

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) after judging that the input is correct ); // redirect to the URL of the page that requires authentication} // display the login form $ this-> render ('login', array ('model' => $ model ));}

As shown above, we first create a LoginForm model example. if the request is a POST request (which means the login form has been submitted ), we use the submitted data $ _ POST ['loginform'] to fill in $ model. then we verify this input. if the verification succeeds, redirect the user's browser to the page that requires authentication. If verification fails or this action is accessed for the first time, we will render the login view, which will be described in subsequent sections.

Tip: in the login action, we use Yii: app ()-> user-> returnUrl to obtain the page URL that requires authentication. Component Yii: app ()-> user is a CWebUser (or its subclass) that indicates user session information (such as user name and status ).

Let's pay special attention to the following PHP statements in the login action:

The code is as follows:

$ 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. The attributes 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'] gives us 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: In order for $ _ POST ['loginform'] to pass to us an array rather than a string, we need to comply with a specification when naming form fields. Specifically, it corresponds to the form field of feature a in model class C. we name it C [a]. For example, we can use LoginForm [username] to name the form field corresponding to the username feature.

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

3. create a form

Writing the login view is very simple. we start with a form mark, and its action attribute should be the URL of the login action described earlier. Then we need to insert tags and form fields for the attributes declared in the LoginForm class. Finally, we insert a button that allows users to click to submit this form. All of these can be done with pure HTML code.

Yii provides several helper (helper) classes to simplify view writing. For example, to create a text input field, call CHtml: textField (); to create a drop-down list, call CHtml: dropDownList ().
For example, the following code generates a text input field, which can trigger the form submission action when the user modifies its value.

The code is as follows:

CHtml: textField ($ name, $ value, array ('submit '=> ''));


Next, we use CHtml to create a login form. Assume that the variable $ model is an instance of LoginForm.

The above code generates a more dynamic form, for example, CHtml: activeLabel () to generate a tag related to the features of the specified model. If an input error occurs for this feature, the CSS class of the label changes to error, and the appearance of the label is changed through the CSS style. Similarly, CHtml: activeTextField () generates a text input field for the features 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 provides seamless and consistent verification between the client and the server. With CActiveForm, the above code can be rewritten:

beginWidget('CActiveForm'); ?>errorSummary($model); ?>label($model,'username'); ?>textField($model,'username') ?>label($model,'password'); ?>passwordField($model,'password') ?>checkBox($model,'rememberMe'); ?>label($model,'rememberMe'); ?>endWidget(); ?>

4. collect table input

Sometimes we want to collect user input in batch mode. That is, you can enter information for multiple model instances and submit them at a time. We call this a tabular input, because these input items are usually presented in an HTML table.

To use table input, we first need to create or fill in an array of model instances, depending on whether we want to insert or update data. Then we extract user input data from the $ _ POST variable and assign it to each model. A slightly different from a 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 (Item) is an instance of the 'item' class, // extract the items to be updated in batch 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 projects are valid //... perform some operations here} // display the View collection table input $ this-> render ('batchupdate', array ('items '=> $ items ));}

After this action is ready, we need to continue the batchUpdate view to display the input items in an HTML table.

NamePriceCountDescription$item): ?>

Note: In the above code, we use "[$ I] name" instead of "name" as the second parameter for calling CHtml: activeTextField.

If any verification error occurs, the corresponding input items are automatically highlighted, just like the single model input we described earlier.

I hope this article will help you design PHP programs based on the Yii Framework.

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.