How to create a view in Yii?

by aniya.jaskolski , in category: PHP Frameworks , 2 years ago

How to create a view in Yii?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 2 years ago

@aniya.jaskolski 

In Yii, creating a view involves the following steps:

  1. Create a new PHP file in the "views" directory of your application. The name of the file should match the name of the action that will render it.
  2. Write the HTML and PHP code to display the content that you want to show in the view.
  3. Use Yii's built-in widgets and helpers to generate HTML code for common UI elements such as forms, tables, and menus.
  4. Optionally, use Yii's layout system to define a common header, footer, and sidebar for all views.
  5. Pass data from the controller to the view by setting properties of the controller's $view object. For example, to pass a variable named $model to the view, you can write $this->view->params['model'] = $model;.


Here is an example of a simple view in Yii:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!-- views/site/index.php -->

<h1>Welcome to my website!</h1>

<p>This is the homepage of my website.</p>

<?php
use yiihelpersHtml;

echo Html::beginForm(['site/contact'], 'post');
echo Html::input('text', 'name', '', ['placeholder' => 'Enter your name']);
echo Html::submitButton('Submit', ['class' => 'btn btn-primary']);
echo Html::endForm();
?>


In this example, the view displays a header, a paragraph of text, and a simple contact form. The form is generated using Yii's HTML helper class. When the form is submitted, it will send a POST request to the site/contact action of the controller.


To render this view from a controller action, you can use the $this->render() method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// controllers/SiteController.php

namespace appcontrollers;

use yiiwebController;

class SiteController extends Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }
}


In this example, the SiteController class defines an action named actionIndex() that simply renders the index.php view using the $this->render() method. The view file is located in the views/site directory.