Yii Framework official guide series 17-use forms: Create models

Source: Internet
Author: User
Tags valid email address
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 chapter ,...



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 user input is collected and saved to the database, we should use an Active Record. The two types of models share the same basic class CModel, which defines the common interfaces required by the form.

Note:In this example, we mainly use the form model. However, the same operation can also be applied to the Active Record model.

1. define model classes

Below we createLoginFormThe model class is used to collect user input on a logon page. Because the login information is only used to verify the user and does not need to be saved, we willLoginFormCreate a form model.


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

LoginFormThree attributes are defined:$username,$passwordAnd$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$rememberMeThere is a default valuefalse, The corresponding options are not checked in the login form during initialization.

Information:We call these member variablesAttributes)Instead of properties, it is different 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. Inrules()Specifies the verification rules in the 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'), array ('memberme', 'boolean'), array ('password', 'authenticate'),);} public function authenticate ($ attribute, $ params) {$ this-> _ identity = new UserIdentity ($ this-> username, $ this-> password); if (! $ This-> _ identity-> authenticate () $ this-> addError ('password', 'incorrect user name or password. ');}}

The code above specifies:usernameAndpasswordIs required,passwordAuthenticated ),rememberMeIt should be a Boolean value.

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


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

WhereAttributeList (feature list)Is a list of feature strings that need to be verified by this rule. each feature name is separated by a comma;Validator)Specifies the type of verification to be performed;onThe parameter is optional, which specifies the list of scenarios that the rule should be applied to. the additional option is an array of name-value pairs used to initialize the attribute values of the corresponding validators.

You can specify three methods in the verification rules.Validator.

First,ValidatorIt can be the name of a method in the model class, just as in the above exampleauthenticate. The verification method must be in the following structure:


/*** @ Param string name of the feature to be verified * @ param array the option specified in the verification rule */public function ValidatorName ($ attribute, $ params ){...}

Second,ValidatorIt can be the name of a validator class. when this rule is applied, an instance of the 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,ValidatorIt can be an alias of a predefined validator class. In the preceding example,requiredThe 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: trueValue or CBooleanValidator: falseValue 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 CCompareValidator 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 cdefavaluvaluevalidator, 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 CFileValidator to ensure that the feature contains the name of an uploaded file.

  • filter: The alias of CFilterValidator, which is changed through a filter.

  • in: The alias of CRangeValidator 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 CTypeValidator to ensure that the feature is of the specified data type.

  • unique: The alias of CUniqueValidator to ensure that the data is unique in the column 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 calledBlock assignment(Massive assignment), It will$_POST['LoginForm']Copy each item in 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.

The security policies for detection features are different in versions 1.0 and 1.1. we will explain them separately below:

1.1 Security features

In version 1.1, features are considered safe if they appear in a verification rule in the corresponding scenario. For example:


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

As shown above,usernameAndpasswordFeature inloginThis is mandatory in scenarios. Whileusername,passwordAndemailFeature inregisterThis is mandatory in scenarios. Therefore, if weloginIn the scenario, onlyusernameAndpasswordIt is assigned a value to the block. Because they only appear inlogin. On the other hand, if the scenario isregisterAll three features can be assigned values by blocks.


// 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,NoAdd 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 specialsafeRules:


array('content', 'safe')

For the sake of completion, there is also an attribute that is declared as insecureunsafeRules:


array('permission', 'unsafe')

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

1.0 security features

In version 1.0, determine whether a data item is secure.safeAttributesThe scenario where the return values and data items of the method are specified. by default, this method returns all public member variables as the security feature of CFormModel, and it also returns the security feature of all field names in the table as CActiveRecord except the primary key. we can rewrite this method based on the scenario to limit the security features. for example, a user model can contain many features,loginScenario, we can only useusernameAndpasswordFeature. we can specify this restriction as follows:


public function safeAttributes(){    return array(        parent::safeAttributes(),        'login' => 'username, password',    );}

safeAttributesThe returned values of a method are structured as follows:


array(   // these attributes can be massively assigned in any scenario   // that is not explicitly specified below   'attr1, attr2, ...',     *   // these attributes can be massively assigned only in scenario 1   'scenario1' => 'attr2, attr3, ...',     *   // these attributes can be massively assigned only in scenario 2   'scenario2' => 'attr1, attr3, ...',)

If the model is not scene sensitive (for example, it is only used in one scenario, or all scenarios share the same set of security features), the return value can be a simple string as follows.


'attr1, attr2, ...'

For insecure data items, we need to use independent value assignment statements to assign them to corresponding features as follows:


$model->permission='admin';$model->id=1;

4. trigger verification

Once the model is filled with data submitted by the user, we can call CModel: validate () to start 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.

We can use scenario to set the scenario attributes, 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 exampleloginIn this scenario, we only want to verifyusernameAndpasswordInput.registerIn scenarios, we need to verify more input, suchemail,address. The following example demonstrates howregisterPerform verification in the scenario:


// Create a User model in the registration scenario. Equivalent to: // $ model = new User; // $ model-> scenario = 'register '; $ model = new User ('register '); // fill the input value in the model $ model-> attributes = $ _ POST ['user']; // execute the verification if ($ model-> validate ()) // if the inputs are valid... else...

You can useonOption. IfonIf this 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 onlyregisterScenario.

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 returnsAllError message of model features, while the second will only returnFirstError 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.

The above is the Yii Framework official guide series 17-use form: create model content. For more information, see PHP Chinese website (www.php1.cn )!

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.