Form form usage for YII2

Source: Internet
Author: User
Tags custom name

Working with Forms

This section describes how to create a form page that collects data from users. The page displays a form that contains a name input box and an email input box. When these two pieces of information are collected, the page displays the information entered by the user.

To achieve this goal, you need to create a [model] in addition to creating a [operation] and two [views].

Throughout the section, you will learn:

* Create a [model] (STRUCTURE-MODELS.MD) to represent the data entered by the user through the form
* Declare rules to validate input data
* Generate an HTML form in [view] (STRUCTURE-VIEWS.MD)

Create a model?

The model class ' Entryform ' represents the data requested from the user, and the class is stored in the ' models/entryform.php ' file as shown below. Please refer to the [Class auto-loading] section for more information on class naming conventions.

//This is necessary, personal feel and the previous version of Yii a little bit different, used to yii1 the time did not use this
<?phpnamespace app\models;use yii\base\model;class Entryform extends model{public    $name;    public $email;    Public function rules ()    {        return [[            ' name ', ' email '], ' required ',            [' email ', ' email '],    '}}

This class inherits from the [[Yii\base\model]],yii] provided by a base class, which is typically used to represent data.

> Add: [[[Yii\base\model]] is used for the parent class of the normal model class and is independent of the data table * *. [[Yii\db\activerecord]] is usually the parent class of a normal model class but is associated with a data table (note: [[Yii\db\activerecord]] class is also inherited from [[Yii\base\model]], adding database processing).

The ' Entryform ' class contains ' name ' and ' email ' two public members to store data entered by the user. It also contains a method called ' rules () ' that returns a collection of data validation rules. The validation rules declared above represent:

* ' name ' and ' email ' values are required
* The value of ' mail ' must satisfy the email address verification

If you have a ' entryform ' object that collects data from the user, you can invoke its [[Yii\base\model::validate () |validate ()]] method to trigger data validation. If there is a data validation failure, the [[Yii\base\model::haserrors|haserrors]] property is set to Ture and you want to know what the error is, call [[yii\base\model::geterrors| GetErrors]].

<?php$model = new Entryform (); $model->name = ' Qiang '; $model->email = ' bad '; if ($model->validate ()) {    // Verify success! } else {    //failed!    //Use $model->geterrors () to get error details}
Create an action?

Below you have to create a ' entry ' operation for the new model in the ' site ' controller. The creation and use of the operation has been explained in the [Say hello] (start-hello.md) section.

<?phpnamespace app\controllers;use yii;use yii\web\controller;use app\models\ Entryform;class Sitecontroller extends controller{//...        Other code: Public Function Actionentry () {$model = new Entryform; //Import form Data  if ( $model->load (Yii:: $app->request->post () ) && $mod El->validate ()) {//Verify $model received data//do something meaningful ... return $this->render (' Entry-con        Firm ', [' model ' = $model]);        } else {//either initialize the display or the data validation error return $this->render (' entry ', [' model ' = ' = $model]); }    }}

The operation first creates a ' Entryform ' object. It then attempts to collect user-submitted data from ' $_post ', which is collected by Yii's [[Yii\web\request::p OST ()]] method. If the model is successfully populated with data (that is, the user has submitted an HTML form), the operation calls [[Yii\base\model::validate () |validate ()]] to ensure that the user submits valid data.

> Supplement: Expression ' Yii:: $app ' represents an instance of [apply], which is a globally accessible singleton. At the same time it is also a [service locator], can provide ' request ', ' response ', ' db ' and so on the specific functions of the components. In the code above, the ' request ' component is used to access the ' $_post ' data received by the application instance.

After the user submits the form, the operation will render a view called ' entry-confirm ' to confirm the data entered by the user. If you do not submit a form, or if the data contains errors (translators: If the email format is not correct), the ' entry ' view will render the output, along with the details of the validation errors that are output from a single table.

> Note: In this simple example we just present a confirmation page of valid data. In practice you should consider using [[Yii\web\controller::refresh () |refresh ()]] or [[Yii\web\controller::redirect () |redirect ()]] to avoid [ Form repeat submission question] (Http://en.wikipedia.org/wiki/Post/Redirect/Get).

Create a view?

Finally, create two views of the file ' entry-confirm ' and ' entry '. They will be rendered by the ' entry ' Operation just created.

The ' entry-confirm ' view simply displays the name and email data submitted. The view file is saved in ' views/site/entry-confirm.php '.

<?phpuse yii\helpers\html;? ><p>you has entered the following information:</p><ul>    <li><label>name</ Label>: <?= html::encode ($model->name)?></li>    <li><label>email</label>: <?= Html::encode ($model->email)?></li></ul>

The ' entry ' view displays an HTML form. The view file is saved in ' views/site/entry.php '.

<?phpuse yii\helpers\html;use yii\widgets\activeform;? ><?php $form = Activeform::begin ()?>    <?= $form->field ($model, ' name ')?>    <?= $form Field ($model, ' email ')?>    <div class= "Form-group" >        <?= Html::submitbutton (' Submit ', [' class ' = > ' btn btn-primary '])?>    </div><?php activeform::end ();?>

The view uses a powerful [widget] (structure-widgets.md) [[yii\widgets\activeform| ActiveForm]] to generate an HTML form. Where the ' Begin () ' and ' end ' are used to render the start and close tags of the form, respectively. The [[Yii\widgets\activeform::field () |field ()]] method is used between the two methods to create the input box. The first input box is used for "name", and the second input box is for "email". The Submit button is then generated using the [[Yii\helpers\html::submitbutton ()]] method.

Try it?

Use the browser to access the following URL to see whether it works:

Http://hostname/index.php?r=site/entry

You'll see a page with a form with two input boxes. Each input box is preceded by a label indicating the type of data that should be entered. If you click the Submit button or fill in an incorrect email address, you will see an error message displayed under the corresponding input box.
[Validation of Wrong forms]
After you enter a valid name and email message and submit it, you will see a confirmation page showing the data you submitted.
[Confirmation page of input data]

# # # Effect description?

You might wonder how the HTML form works in the dark, and it looks like it can display text labels for each input box, and when you don't have to enter the correct information, you don't need to refresh the page to give the wrong hint, which may seem magical.

Yes, the data is first validated by the client-side JavaScript script before it is submitted to the server for verification by PHP. [[Yii\widgets\activeform]] smart enough to translate the validation rules you declare in the ' Entryform ' model into client-side JavaScript scripts to perform validation. If the user's browser disables JavaScript, the server will still validate the data again like this in the ' Actionentry () ' method. This ensures that the data submitted by the user is valid under any circumstances.

> Warning: Client-side validation is a means of improving the user experience. Regardless of whether it is enabled properly, server-side validation is mandatory, and do not ignore it.

The text label of the input box is generated by the ' field () ' method, and the content is the property name of the data in the model. For example, the ' name ' property in the model generates a label that is ' name '.

You can customize the label in the view:

<?= $form->field ($model, ' name ')->label (' Custom name ')? ><?= $form->field ($model, ' email ')->label ( ' Custom Email ')?>

> Add: Yii provides quite a few similar widgets to help you generate complex and dynamic views. You'll also learn how easy it is to write widgets in the back. You might turn many of your view code into widgets to improve reuse and speed development.

Summarize

In this section of the guide you are exposed to every part of the MVC design pattern. Learned how to create a model that represents user data and verifies its effectiveness.

You also learned how to get data from the user and display it back to the user in the browser. This would have been a time-consuming task in the development of applications, but Yii provided a powerful widget to make it so simple.

In the next chapter you will learn how to use a database, and almost every application requires a database.

Form form usage for YII2

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.