Development - Views


General Info

A view is a (visual) representation of its model. It would ordinarily highlight certain attributes of the model and suppress others. In such way it's acting as a filter of presentation. A view is attached to its model (or model part) and gets the data necessary for the presentation from the model by asking questions. It may also update the model by sending appropriate messages and queries. Generally all view files are placed in protected/views/{controller-lowercase-name}/ directory. There is only one exclusion for view files, that related to script components and they must be placed in directory protected/views/components/.

Remeber, that view file name must be in lowercase! Example: views/posts/edit.php

Call View from the Action

The typical way to create a view in is to use method render of embedded view property of the Action.
Example of an action that calles view file:
<?php
class AccountController extends CController
{
    public function indexAction()
    {
        ...
        
        // Call the view file
        $this->_view->render('accounts/index');

        // Or call another view file
        $this->_view->render('accounts/members/index');
    }
}    

Rendering Data - passing data to the View (template engine)

When generating the HTML code of the resulting web page, the view (template engine) processes the data received from the action. Data should be passed to the template engine using the following syntax:
/* create new variable "title" */
$this->_view->title = 'some text here...';
/* create new variable "text" */
$this->_view->text = 'other text here...';
/* change value of variable "title" */
$title = 'changed title value';
$this->_view->title = $title;

/* sample 1-3 - call of views from controllers */
/* sample 1 - full syntax */
$this->_view->render('controller/view');
/* sample 2 - short syntax, missing controller means use current controller name */
$this->_view->render('view'); 
/* sample 3 - call of another view */
$this->_view->render('errors/404');

/* sample 4 - call of view from components */
A::app()->view->renderContent('leftmenu');

/* sample 5 - call of another view from current controller */
$data = array();
$data['user_id'] = 2;
$data['type'] = 'global';
$this->_view->renderView('statistics', $data);
/* sample 6 - call of one view from another view */
$this->_view->renderView('tabs/emails');
Now all variables that were created with $this->_view may be used in our view file with simple using of PHP echo command.
Here the example:
<?php echo $actionMessage; ?>

<div class="title">
    echo $title;
</legend>

<div class="content">
    echo $text;
</legend>