This article mainly introduces the use of the yii Framework form model and the example of submitting form data in the form of arrays. For more information, see the description in the Yii document, the general process of Yii processing forms is:
Create a model class corresponding to the form and set field verification rules
Create an action for form submission to process submitted content
Create a form in the view
In a small project just now, I want to use ajax to submit form information and verify and save the information, and do not want to use hidden iframe for refreshing new submissions. In addition, the action can be used to validate model classes, let's think of the form array submission method. for example:
Form code:
The code is as follows:
After submission, you can directly use $ _ POST ['arr'] to obtain the submitted data. $ _ POST ['arr'] is:
The code is as follows:
Array
(
[0] =>
[1] => B
[2] => c
)
Similarly, if you use the following form to submit:
The code is as follows:
$ _ POST ['arr:
Array
(
[3] =>
[6] => B
[8] => c
)
Of course, two-dimensional arrays can also be submitted:
The code is as follows:
$ _ POST ['arr:
Array
(
[0] => Array
(
[Name1] =>
)
[1] => Array
(
[Name2] => B
)
[2] => Array
(
[Name3] => c
)
)
If the key of the first sub-array is not set, each value is added to arr when an array is generated. if you want to save the information in an array, add a key value as follows:
The code is as follows:
$ _ POST ['arr:
Array
(
[A] => Array
(
[Name1] => a1
[Value1] => a2
)
[B] => Array
(
[Name2] => b1
[Value2] => b2
)
)
The following is an example of submitting a form using ajax and verifying the form using the yii form model. The first part is the model class. there is only the simplest verification method:
The code is as follows:
Class LandingForm extends CFormModel
{
Public $ landing_title;
Public $ landing_content;
Public $ landing_position;
Public function rules ()
{
Return array (
Array ('logging _ title, landing_content ', 'required '),
Array ('logging _ position', 'default', 'value' => ''),
);
}
}
It is interesting to find that when the model class sets the parameter verification method, it needs to set rules for each public parameter. if there are parameters with no rules set, after the form value in $ _ POST is assigned a value to the model, the parameter value without the rule is null.
Obtain the parameters submitted by the form in the action and verify the parameters:
The code is as follows:
$ Model = new LandingForm;
$ Model-> attributes = $ _ POST ['form'];
If ($ model-> validate ()){
$ Info = $ model-> attributes;
...
}
Finally, the code for the front-end form submission, using jquery:
The code is as follows:
Var info = new Object ();
Info = {'form [landing_title] ': landing_title,
'Form [landing_content] ': landing_content,
'Form [landing_position] ': landing_position,
};
Var url = "...";
$. Post (url, info, function (rst ){
...
});