YII2 Series Tutorial II: Mvc,forms and layouts

Source: Internet
Author: User
Tags yii

In the previous article we simply implemented the Yii2 framework installation and Hello World , in this article, we will be curious to explore a few important elements in the Yii2 composition: MVC , Forms and Layouts .

The goal of this article is to create a small form application, is to achieve a simple similar to the microblogging function, but I do not want to get involved in the database that piece, because in fact, the database and table in the YII2 framework in fact there is still a lot of things to talk about in the next article will be detailed.

Mvc

The model (Model) for my own simple understanding is a collection of concepts, which contains a collection of the concept of a variety of data, such as a User name, gender and many other attributes, this concept set is usually a table for the database (if there is no corresponding data table, Can be thought of as a property of a collection), and each specific instance concept corresponds to a data record. For example, in this article we will create a Status model that represents the state (from life: a state), which has two important attributes, text and that is the permissions text State itself, which permissions is the permission of the state.

The view (Views) requests data from the controller to the model and presents the data to the user in a specific layout.

The controller (Controller) can Model send different instructions to and from the Views model, typically fetching the data from the figure and then reading the view file to render the output data.

In YII2 applications, this is typically the case when a URL points to a specific controller action , and then the Controller is responsible for fetching the data to a particular model and then assigning the data to the view render output.

Here to say my personal views, I think in fact, perhaps the most things should be, and it is to cater to, MVC Model Controller and Views is relatively light, Controller responsible for coordination Model and, views are Views responsible for the display of data.

In the YII2 project, we placed the models file under the /models/ directory, so we created it under this folder Status.php :

<?phpNamespaceApp\ModelsUseYii\Base\Model;ClassStatusExtendsmodel{Const PERMISSIONS_PRIVATE =10;Const PERMISSIONS_PUBLIC =20;Public$text;Public$permissions;PublicfunctionRules() {return [[[' Text ',' Permissions '],' Required '),]; }PublicfunctionGetPermissions () {return array (self::P ermissions_private=> ' PRIVATE ',  Self::P ermissions_public=>public function getpermissionslabel ( $permissions) {if ( $permissions ==self::P ermissions_ Public) {return else {return  ' Private ';}}}   

It is important to note that rules() this method will trigger the form validation rules that yii comes with, such as this and both of text permissions these form input boxes cannot be empty, as getPermissions() This method is dropdown used when using the input box.

StatusOnce the model is created, we can then create the corresponding controller and method. In the normal development of my habit is to create a corresponding controller for each model, which usually contains several of the most common methods:,,, index create , and store so update on delete . Here I create a StatusController.php , this file should be located in the /controllers/ folder, and we want to implement a publishing state function, we must need an create action method, such as our purpose is: When the user access http://localhost:8999/status/create , We can show a page that creates a state to the user.

<?phpNamespaceApp\ControllersUseYii;UseYii\Web\Controller;UseApp\Models\Status;ClassStatuscontrollerExtendscontroller{PublicfunctionActioncreate () { $model = new Status; if ( $model->load (yii:: $app- Request->post ()) &&  $model->validate ()) {//$ Model has post data directly showing return  $this->render (" view ", [" model ' =  $model]);} else {//when there is no data, directly render create VIEW return  $this->render ( ' create ', [ ' model ' = >  $model]); } }} 

First, based on the rules of the URL, we create a actionCreate() method in which we determine the display of a particular view by conditional judgment.

After creating the controller and method, we can go to the next step: Create a view. In Yii2, the location of the view file is closely related to the name of the controller, such as the one we created above StatusController , we now need to views/ create a status/ folder, and then create the various associated view files in this folder, StatusController such as the above actionCreate() In return $this->render() two views: view.php andcreate.php

Forms

First, we need a Create view to show Status the form we created (create.php) :

<?phpUseYii\Helpers\Html;UseYii\Widgets\ActiveForm;UseApp\Models\Status;?><?php$form = Activeform::begin ();?><?=$form->field ($model,' Text ')->textarea ([' Rows ' + =' 4 '])->label (' Status Update ');?><?=$form->field ( $model,  ' permissions ')->dropdownlist ( $model->getpermissions (), [ ' prompt ' => -Choose Your Permissions-']) ?> < div class= "Form-group" > <?= Html::submitbutton ( ' Submit ', [ ' class ' =  ' btn Btn-primary ']) </div> <?php activeform::end (); ?>             

In our usual development of Web applications, forms are almost always present at all times, as long as the form is needed where information is collected. And Yii2 in the form of support this is very good, as you can see, the above Yii2 ActiveForm is Yii2 built to help us to build the form of the small component, it is important to note that dropDownList this input box how to implement, it directly used getPermissions() , This method just returns an array of what we need.

http://localhost:8999/status/createat this time visit: You can see the form created above:

As for why the automatic layout, do not need us to write CSS, it is because Yii2 default will give us to load the bootstrap CSS file, so we use the right to specify the class name is OK. And obviously, we can see that once the input box loses focus, if nothing is entered in it, each input box will have a corresponding error message, and the user experience is very good. This is actually due to the method we declare in the status model rules() , YII2 will give the corresponding validation by JS at the front end according to the specified rules.

Then we try to fill in some content, and you'll see the change in the input box:

Click the Submit button, the form will be submitted to StatusController the actionCreate() method, once the post data is transmitted, the view will be rendered view.php :

Here, we actually walk through the whole MVC process, and in the process, we incidentally say a bit about the knowledge of forms.

Layouts

Why do you say layouts? Because layouts in Yii can actually be viewed as a frequently repeated part of the view, such as an HTML file header , navigation bar and so on footer , these are almost in every view file will be used, So Yii took a once and for all approach to managing these shared parts: the layouts was born. This way you don't have to repeat unnecessary code in every file, and it's view especially good to manage.

Yii allows you to create multiple layouts, but I do not seem to have encountered the use of the scene, so still can not give an empirical statement, anyway, a layouts is basically enough.

Finally, we take a look at the layouts of the East wind to see how we can modify the default navigation bar for YII2: Add a new navigation.

In the previous section I mentioned views\layouts\main.php this file, the concrete structure inside you can directly open to see, we change here is Nav::widget this part:

  Echo Nav::widget ([' Options ' = [' Class ' =' Navbar-nav navbar-right '],' Items ' = [[' Label ' =' Home ',' URL ' = ['/site/index '], [' Label ' =' Status ',' Items ' = [[' Label ' =' Create ',' URL ' = ['/status/create '],],], [' Label ' =' About ',' URL ' = [ ' label ' =  Contact ',  ' url ' = = [ '/site/contact ']], Yii:: $app->user->isguest? [ ' label ' = =  ' Login ',  ' url ' = [  '/site/login '] : [ ' label ' =  ' Logout ('. Yii:: $app->user->identity->username.  ' url ' = = [ ' linkoptions ' = [ ' data-method ' = =  ' post ']], [],]);            

We added the following on the original basis:

 [    ‘label‘ => ‘Status‘,    ‘items‘ => [        [‘label‘ => ‘Create‘, ‘url‘ => [‘/status/create‘]], ],],

After that, refresh the page and you'll see the changes in our navigation. And it's amazing: there's also dropdown menu the functionality that is implemented here, which is actually used Bootstrap dropdown menu .

Well, this article seems to be about the same, at least I don't know what else to say, the next article I will try to talk about YII2 database related content, first sleep.

The source will be placed in Github:https://github.com/jellybool/helloyii

YII2 Series Tutorial II: Mvc,forms and layouts

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.