This example describes the use of forms in Yii. Share to everyone for your reference, specific as follows:
When working with forms in Yii, you typically need the following steps:
1. Create a model class to represent the data fields that you want to collect.
2. Create a controller action to respond to form submission.
3. Create a form related to the Controller action in the view script.
First, create the model
Before writing the HTML code needed for a form, we should first determine the type of data that is entered by the end user and what rules the data should conform to. The model class can be used to record this information. As defined in the Model section, the model is the central location for saving user input and validating these inputs.
Depending on how the data entered by the user is used, we can create two types of models. If user input is collected, used, and discarded, we should create a form model;
If the user's input is collected to be 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 by the form.
1. Define Model class
For example, to create a form model:
Class LoginForm extends Cformmodel
{public
$username;
public $password;
Public $rememberMe =false;
}
Three attributes are defined in the LoginForm: $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 login options. Because the $rememberMe has a default value of FALSE, the corresponding option is not checked when the initialization appears in the login form.
We refer to these member variables as attributes (attributes) rather than attributes (properties) to distinguish them from normal properties. attribute is a property that is primarily used to store data from user input or database (propertiy).
2. Declaring validation rules
Once the user submits his input and the model is populated, we need to ensure 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;
public $password;
Public $rememberMe =false;
Private $_identity;
Public function rules ()
{return
array (
' username, password ', ' required '),//username and password is a must-fill
array (' RememberMe ', ' Boolean '),//rememberme should be a Boolean
array (' Password ', ' Authenticate '),//password should be validated (authenticated)
);
}
The Public function authenticate ($attribute, $params)
{
$this->_identity=new useridentity ($this-> Username, $this->password);
if (! $this->_identity->authenticate ())
$this->adderror (' Password ', ' incorrect username or password. ');
}
}
Each rule returned by rules () must be in the following format:
Copy Code code as follows:
Array (' AttributeList ', ' Validator ', ' on ' => ' scenariolist ', ...) Additional options)
which
AttributeList (attribute list) is a list of attributes that need to be validated by this rule, with each attribute name separated by commas;
Validator (Validator) specifies the kind of validation to perform;
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 that is 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 the model class, just like the authenticate in the example above. The authentication method must be the following structure:
Copy 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 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 above example, the required name is an alias for Crequiredvalidator, which is used to ensure that the value of the attribute being validated is not NULL. The following is a complete list of predefined validator aliases:
Boolean:cbooleanvalidator alias to ensure that the attribute has a Cbooleanvalidator::trueva lue or Cbooleanvalidator::falseva lue value.
Captcha:ccaptchavalidator alias to ensure that the attribute value equals the validation code shown in Captcha.
Compare:ccompareva Lidator alias to ensure that the attribute equals another attribute or constant.
Email:cemailvalidator alias to ensure that the feature is a valid email address.
Default:cdefaultvalueva Lidator alias that specifies the default value for the attribute.
Exist:cexistvalidator alias to ensure that the attribute value can be found in the columns of the specified table.
File:cfileva Lidator alias to ensure that the attribute contains an uploaded file name.
Filter:cfiltervalidator alias, which changes this attribute through a filter.
In:crangeva Lidator alias to ensure that the data is within the range of a predetermined value.
Length:cstringvalidator alias to ensure that the length of the data is within a specified range.
Match:cregularexpressionvalidator alias to ensure that the data can match a regular expression.
Numerical:cnumbervalidator alias to ensure that the data is a valid number.
Required:crequiredvalidator alias to ensure that the attribute is not empty.
Type:ctypeva Lidator alias to ensure that the attribute is the specified data type.
Unique:cuniqueva Lidator alias to ensure that the data is unique in the column in the datasheet.
Url:curlvalidator alias to ensure that the data is a valid URL.
Below we list several examples that use only these predefined validators:
User name is required
Array (' username ', ' required '),
//username must be between 3 and 12 characters
Array (' username ', ' length ', ' min ' =>3, ' Max ' =>12),
//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 assignment
After an instance of a class is created, we usually need to populate its attributes with data submitted by the end user. This can be easily achieved by using 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 ' into the corresponding model attribute. This is equivalent to the following assignment method:
foreach ($_post[' LoginForm '] as $name => $value)
{
if ($name is a security attribute)
$model-> $name = $value;
}
It is important to detect the security of a feature, for example, if we expose a table's primary key as safe, then an attacker might gain an opportunity to modify the primary key of the record to tamper with what is not authorized to him.
Attributes are considered safe if they appear in a validation rule for the corresponding scene. For example:
Array (' Username, password ', ' required ', ' on ' => ' login, register '),
array (' emails ', ' required ', ' on ' => ') Register '),
As shown above, the username and password attributes are required in the login scenario. The username, password and email features are required in the register scenario. So, if we perform block assignment in the login scenario, only username and password will be assigned a value by the block. Because only they appear in the validation rules for login. On the other hand, if the scene is a register, these three attributes can be assigned a value by the block.
$model =new User (' login ') in the login scene;
if (Isset ($_post[' user '))
$model->attributes=$_post[' user '];
$model =new User (' register ') in the registration scene;
if (Isset ($_post[' user '))
$model->attributes=$_post[' user '];
So why do we use such a strategy to detect the security of an attribute? 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 data entered by the user instead of checking the data that we generate in code (such as timestamps, automatically generated primary keys). Therefore, do not add validation rules for attributes that do not accept end user input.
Sometimes we want to declare a feature to be 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 for this purpose:
Copy Code code as follows:
Array (' content ', ' safe ')
There is also a unsafe rule that declares an attribute to be unsafe:
Copy Code code as follows:
Array (' permission ', ' unsafe ')
Unsafe rules are not commonly used, which is an exception to the security features we defined previously.
4. Trigger Verification
Once the model is populated with data submitted by the user, we can invoke 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 are applied.
Validation is performed based on the scenario. The Scenario property specifies the scenario currently used by the model and the set of validation rules currently in use. For example, in the login scenario, we just want to validate the username and password input in the user model, and in the register scenario, we need to validate more input, such as email, address, etc. The following example shows how to perform validation in a register scenario:
Create a User model in the registration scenario. Equivalent to:
//$model =new User;
$model->scenario= ' register ';
$model =new User (' register '); Add parameters to the model class, which is the validation scenario to trigger
//fill the input value into the model
$model->attributes=$_post[' User '];
Perform validation if
($model->validate ()) //If 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 scenes. For example:
Public function rules ()
{return
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 will apply only to the register scene.
5, extraction validation error
When the validation is complete, any errors that may occur 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 an error message 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 label tells the user what information he or she should fill out in this form field. Although we can hard-code a label in the view, it is more flexible and convenient if we specify (label) in the appropriate model.
By default, Cmodel the name of the simple return attribute as its label. This can be customized by overriding the Attributelabels () method. As we'll see in the next section, specifying tags in the model allows 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 the example of a login form, the corresponding code is:
Public Function Actionlogin ()
{
$model =new loginform;
if (Isset ($_post[' loginform '))
{
//collect user input data
$model->attributes=$_post[' loginform '];
Validates user input and redirects to the previous page
if ($model->validate ()) $this->redirect () after the correct input (
Yii::app ()->user-> ReturnUrl); Redirect to previously authenticated page URL
}
//Display login Form
$this->render (' login ', array (' model ' => $model)
}
As shown above, we first created an example of a loginform model; If the request is a POST request (meaning that the login form was submitted), we use the submitted data $_post[' LoginForm ' to populate the $model; and then we validate this input, If the validation succeeds, redirect the user's browser to the page that requires authentication before. If the validation fails, or if the action is first accessed, we render the login view, and the contents of this view are explained in subsequent chapters.
Tip: In the login action, we use Yii::app ()->user->returnurl to get the URL of the page that requires authentication before. Component Yii::app ()->user is a cwebuser (or its subclass) that represents user session information (such as user name, state).
Let's pay special attention to the following PHP statements that appear in the login action:
Copy Code code as follows:
$model->attributes=$_post[' LoginForm '];
As we said in the security attribute assignment, this line of code populates the model with data submitted by the user. The Attributes property is defined by the 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 above code is equivalent to the lengthy paragraph below (assuming that 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 $_post[' loginform ' to pass us an array instead of a string, we need to follow a specification when naming form fields. Specifically, the form field corresponding to the feature a in model class C is named C[a]. For example, we can use Loginform[username to name the corresponding form field for the username attribute.
Now the rest of the work is to create the login view, which should contain an HTML form with the entry you want.
Third, create a form
Writing the login view is simple, we start with a form tag, and its action attribute 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 the form. All of this can be done with pure HTML code.
YII provides several helper classes for simplifying view writing. For example, to create a text entry field, we can call Chtml::textfield (), and to create a drop-down list, call CHtml::d ropdownlist ().
For example, the following code will generate a text input field that can touch the publication submit action when the user modifies its value.
Copy Code code as follows:
Chtml::textfield ($name, $value, Array (' Submit ' => '));
Below, we create a login form using CHtml. We assume that the variable $model is an instance of LoginForm.
The above code generates a more dynamic form, for example, Chtml::activelabel () generates a label related to the attributes of the specified model. If this attribute has an input error, the CSS class for this label becomes error and changes the appearance of the label through CSS styles. Similarly, Chtml::activetextfield () generates a text input field for the attributes of the specified model and changes its CSS class when the error occurs.
We can also use a new small object cactiveform to simplify form creation. This small object provides seamless, consistent validation both on the client and on the server side. Using 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.. Collect form Input
Sometimes we want to collect user input through batch mode. That is, users can enter information for multiple model instances and submit them at once. We refer to this as form input (tabular input) because these entries are usually rendered as HTML tables.
To use form 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 data entered by the user from the $_post variable and assign it to each model. A slightly different thing from a single model input is that we use the $_post[' Modelclass ' [$i] to extract the input data instead of using $_post[' Modelclass '.
The Public Function actionbatchupdate ()
{
//assumes that each item is an instance of an ' item ' class,
//extracts the item to be updated through the 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 items are valid
//... Do some action here
//Show view collection form input
$this->render (' batchUpdate ', Array (' Items ' => $items));
}
Ready for this action, we need to continue working on the BatchUpdate view to display the entries in an HTML table.
Namepricecount
Description
$item):?>
Note that in the above code we used "[$i]name" instead of "name" as the second argument 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.
I hope this article will help you with the PHP program design based on the YII framework.