• Translate

7/13/2017

Getting Started tutorial Web Application Development with Yii2 (Part 3): View

Tutorial PHP | Tutorial Web Design |

Advertisement

Getting Started tutorial Web Application Development with Yii2 (Part 3): View
View is a core part of a web framework that is responsible for storing HTML code and various manipulations to display data tailored to system specifications. By relying on views you can display a data derived from a database query result or display a contents of the webserver log you are using. With the view also users will use their account to login through the login form and access the various pages that have been allowed to the user. View is not only in HTML format, there is also a display format JSON, XML, Text, and others.

Now let's see how to create a view in Yii2.

Using View

To make us feel better, let's create a controller with the class name HelloViewController. Let's create the HelloViewController.php file first in the controllers folder. Now create the following code in the HelloViewController.php file: 

<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;

class HelloViewController extends Controller
{
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionIndex()
    {
        return $this->render('index');
    }
}
Not only stop here, we must create a view file that will be displayed when the hello-view/index action is accessed by the user. In Yii2, by default a view folder must be grouped with the name of the existing controller. For example when we will display the view index in HelloViewController, then we must create a folder in the views folder with the name hello-view. Then we create the file* with the name index.php to be accessible from HelloViewController.

Now please create a folder named hello-view inside the views folder and create a file with the name index.php in views/hello-view. Then create the following code inside the index.php file: 
h1>Demo View</h1>
<p>Halo dari demo-view/index.php ...</p>
Now you can view it via URL http://localhost/hello-yii/web/index.php?r=hello-view/ in web browser as in the following picture: 
Using View

Using View Saved in Folder

In addition to saving views in the hello-view folder, you can also create more folders that may store various grouped views. Call it there is a demo folder that stores a view file named sample.php. Then you can use the view by using $ this-> render ('demo / sample'). Let's create a demo folder inside the hello-view folder and then create a file named sample.php and create the following code in the file:
<h1>Demo View</h1>
<p>Halo dari demo-view/demo/sample.php...</p>
Then add a demo action in HelloViewController:
<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;

class HelloViewController extends Controller
{
    ....

    public function actionDemo()
    {
        return $this->render('demo/sample');
    }
}
Now let's look at the result via URL  http://localhost/hello-yii/web/index.php?r=hello-view/demo in the web browser: 
Using View Saved in Folder

Skipping Variables to View

You can also pass various variables into a view to display in the view. The set of variables is packaged using PHP arrays. Now let's create a file with the name greeting.php inside the views/hello-view folder. Now let's make the following source code inside greeting.php file:
<?php
$this->title = 'Hello View - Greeting';
?>
<h1>Welcome</h1>
<p>Halo <?= $salutation?>. <?= $name ?> dari <?= $address ?></p>
Then let's add the following action in the controller HelloViewController:
<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;

class HelloViewController extends Controller
{
    ....

    public function actionGreeting($name="Bon Xi Lai", $salutation="Mr", $address='Kao Shiung, Taiwan')
    {
        return $this->render('greeting', [
                    'name' => $name,
                    'salutation' => $salutation,
                    'address' => $address
                ]);
    }
}
In the above action, there is a default value that will be filled when no query string is included in the URL. As you can see, the second parameter is an array that packs the various variables and passes them to the greeting.php view. And in that view we can use it one by one to extract its value. Here is a screenshot when the action is executed from the URL http://localhost/hello-yii/web/index.php?r=hello-view/greeting
Skipping Variables to View

Skipping Variables to View

Creating Simple Widgets

You may also need a reusable component eg wanting to create a football scoreboard that can be displayed on any page without copying its HTML structure in another view. Yii2 has a feature called widgets. You can create an HTML component written using a PHP class. The class will write an HTML structure tailored to the parameters you specify. For example, now we will create a widget "Hello World". First please create a folder called components under the hello-yii folder. Then please create a file named HelloWidget.php under the hello-yii/components folder.

Then please create the following code in the file:
<?php

namespace app\components;

use yii\base\Widget;
use yii\helpers\Html;

class HelloWidget extends Widget
{
    public $message;

    public function init()
    {
        parent::init();
        if ($this->message === null) {
            $this->message = 'Hello World';
        }
    }

    public function run()
    {
        return Html::encode($this->message);
    }
}
To create a widget, you need to drop a class from Widgets. Then you can override the two main methods of init() and run(). The init() method is a method that will be executed before any other action is executed. While method run() function to output the output of course the structure of HTML code or regular string.

Now let's create a view file in the views/demo folder with the name widget.php. Then create the following code in the file: 
<?php
$this->title = 'Hello View - Demo Widget';
?>
<h1>Demo View</h1>
<p>Halo dari demo-view/demo/widget.php...</p>
<?= $hello_widget ?>
And finally let's create an action in HelloWorldController that will try the widget:
<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use app\components\HelloWidget;

class HelloViewController extends Controller
{
    ....

    public function actionWidget()
    {
        $hello = HelloWidget::widget(['message' => 'Hai, pesan ini dirender oleh HelloWidget dari components/HelloWidget.php']);
        return $this->render('demo/widget', [
                    'hello_widget' => $hello
                ]);
    }
}
In the above code, you call the class HelloWidget by way of use the app\components\HelloWidget. Then you can start using widgets by calling the HelloWidget class and passing message parameters via static method widget(). The message parameter we have defined in HelloWidget class is when we write public $message; In the class. The output results are saved into the $hello variable and we miss to view the demo/widget with the hello_widget variable name.

Here is a screenshot of a page that uses the HelloWidget widget accessed via URL http://localhost/hello-yii/web/index.php?r=hello-view/widget
Creating Simple Widgets

Setting Title and Meta Tags

Can be spelled out if this is a feature that is also important for the sake of tidiness web page that we will show. Yii2 has a feature that can set the title and meta tags of a page. So you do not have to bother making your own code to manipulate title and meta tags for a page. Now let's create a file with the name metatags.php inside the views/demo folder. Then create the following code inside the file:
<?php

$this->title = 'Hello View - Demo Meta Tags';
$this->registerMetaTag(['name' => 'keywords', 'content' => 'yii, framework, php']);
$this->registerMetaTag(['name' => 'description', 'content' => 'Belajar yii framework. Dipersembahkan oleh Codepolitan.'], 'description');

?>

<h1>Demo Meta Tags</h1>

<p>Lorem ipsum sit dolor amet...</p>
Now let's create a new action in the HelloViewController class: 
<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use app\components\HelloWidget;

class HelloViewController extends Controller
{
    ....

    public function actionDemoMetaTags()
    {
        return $this->render('demo/metatags');
    }
}
Now we access the URL http://localhost/hello-yii/web/index.php?r=hello-view/demo-meta-tags , and see the following screenshot: 
Setting Title and Meta Tags

Setting Title and Meta Tags

Creating Simple Layouts

One other important part is to create a layout. Yii2 has a number of functions that can help you to create a layout. Basically a layout is a primary container that will display a page section of the view. Thus you can reduce the frequency of copying a section that often appears on web pages, eg sidebar, footer, and header. Quite a piece of content that changes on every page. To create a layout we now create a file named demo.php in the views/layouts folder:
<?php
/* @var $this \yii\web\View */
/* @var $content string */

use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use app\assets\AppAsset;
use yii\helpers\Url;

AppAsset::register($this);
?>

<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
    <head>
        <meta charset="<?= Yii::$app->charset ?>">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <?= Html::csrfMetaTags() ?>

        <title><?= Html::encode($this->title) ?></title>

        <?php $this->head() ?>
    </head>
    <body>

        <?php $this->beginBody() ?>

        <div class="wrap">
            <?php
            NavBar::begin([
                'brandLabel' => 'Perusahaanku',
                'brandUrl' => Url::toRoute(['hello-view/index']),
                'options' => [
                    'class' => 'navbar-inverse navbar-fixed-top',
                ],
            ]);
            echo Nav::widget([
                'options' => ['class' => 'navbar-nav navbar-right'],
                'items' => [
                    ['label' => 'Salam', 'url' => ['/hello-view/greeting']],
                    ['label' => 'Widget', 'url' => ['/hello-view/widget']],
                    ['label' => 'Demo Folder', 'url' => ['/hello-view/demo']],
                ],
            ]);
            NavBar::end();
            ?>

            <div class="container">
                <?php if (isset($this->blocks['block1'])): ?>
                    <?= $this->blocks['block1'] ?>
                <?php endif; ?>

                <?= $content ?>

                <?php if (isset($this->blocks['block2'])): ?>
                    <?= $this->blocks['block2'] ?>
                <?php endif; ?>
            </div>
        </div>

        <footer class="footer">
            <div class="container">
                <p class="pull-left">&copy; Perusahaanku <?= date('Y') ?></p>
            </div>
        </footer>

        <?php $this->endBody() ?>

    </body>
</html>
<?php $this->endPage() ?>
The above layout code actually does not vary much with the layout that has been created Yii2 in file layouts/main.php. Here we just change the Nav widget that displays various URLs consisting of actions we have created earlier. Then inside the container we create an blocks that will be used to display the HTML page in that special place. Blocks are used to display an HTML structure separate from the main content. Now for more details, let's change the view hello-view/index.php to something like this: 
<h1>Demo View</h1>
<p>Halo dari demo-view/index.php ...</p>
<?php $this->beginBlock('block1'); ?>
<p>...content of block1...</p>
<?php $this->endBlock(); ?>
<?php $this->beginBlock('block2'); ?>
<p>...content of block2...</p>
<?php $this->endBlock(); ?>
In the above code, however you position the block in the code above. Suppose the second block is stored above, the first block is stored last. The output will still be displayed according to the block layout in the demo.php layout. Now let's use the demo.php layout inside the HelloWidgetController class as follows: 
<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use app\components\HelloWidget;

class HelloViewController extends Controller
{
    public $layout = 'demo';
    ... ...
}
Yes, you can simply create an attribute named $layout and be public then fill it with the layout name we will use. It could be that one day, you missed the admin layout of the attribute. Now let's look at the results as in the following URL:
Creating Simple Layouts

Closing

The view handling problem in Yii2 is very complete. You can create customized layouts with web templates you've purchased or created by a team of web designers. You can also pass various variables into a view to display into a table or into a slide gallery. You've also tried to create a reusable widget for other actions.

In the next tutorial, you will try to use the built-in widget provided for Yii2. These widgets are the components of Twitter Bootstrap and jQuery UI. You will try to display it in view so the HTML page becomes more interesting and richer of course with Yii2 way.

Cooperation with (codepolitan / arslan / yiiframework)

Disqus
Blogger
Comment
How to style text in Disqus comments Top Disqus Commentators
  • To write a bold letter please use <strong></strong> or <b></b>.
  • To write a italic letter please use <em></em> or <i></i>.
  • To write a underline letter please use <u></u>.
  • To write a strikethrought letter please use <strike></strike>.
  • To write HTML code, please use <code></code> or <pre></pre> or <pre><code></code></pre>, and please parse the code in the parser box below.
Show Parser Box

No comments Add Comment

Comments not appropriate topic will sign SPAM.