Yiiframework getting started tutorial
Http://vmee.org/yiiframework%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%E5%8D%81%E4%B8%80%E4%B9%8B%E4%BD%BF%E7%94%A8%E8%A1%A8%E5%8D%95
11. When using a form to process a form in yii, follow these steps: 1. Create a model class to represent the fields of the data 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 by 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. 1. define a model class. 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 (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-> _ ide Ntity = 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: array ('butbutelist', 'validator', 'on' => 'scenariolist ',... additional options) 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 (validator) specifies the type of verification to be performed; the on parameter is optional. It specifies the list of scenarios to which this rule applies. 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: /*** @ Param string name of the feature to be verified * @ Param array option specified in the verification Rule */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 pre-defined authenticator aliases: Boolean: cbooleanvalidator. Make sure 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. Here are a few examples of using only these predefined validators: // The username is a required item array ('username', 'required '), // The username must be an array of 3 to 12 characters ('username', 'length', 'Min' => 3, 'max '=> 12 ), // In the registration scenario, the 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 features are assigned 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 using the following block assignment (massive assignment): $ model = new loginform; If (isset ($ _ post ['loginform']) $ model-> attributes = $ _ post ['loginform']; The final expression is called 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 to achieve this purpose: array ('content', 'safe ') and an unsafe rule for declaring an attribute as unsafe: array ('permission ', 'unsafe ') unsafe rules are not commonly used. They are an exception to the security features we have previously defined. 4. 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. After verification error extraction 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. After creating an action model, we can start to write the logic used to operate 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. The content of this view will be explained in the next section. 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: $ 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 follow a standard 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. Creating a form to write a login view is very simple. We start with a form mark, and its action attribute should be the URL of the previously described login action. 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. Chtml: textfield ($ name, $ value, array ('submit '=> ''); below, 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. Namepricecount description $ 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.