Yii 1.1: Putting Function To Be Called In View


Sometimes we need some complicated view to be displayed (such as generating complicated table). Most people suggest that in MVC the View must be as simple as possible (don't have too much loops, etc). So what we have to do is to hide away the complex code by putting it at somewhere else. The following are few places options to keep the function:

  1. We can add the function in the Model, so in the view file we just can call the model's method. The drawback of this method is model is not supposed to be put some viewing function. So it's not advisable to put the function related viewing or output result to the screen in there.
//File in the models/mymodel.php
class MyModel extends CActiveRecord{
    public function myFunction(){
        //do something...
//File in the views/view.php
<?php MyModel::model()->myFunction(); ?>
  1. Use widget. We can create a class extends CWidget. In the View then we just need to call the widget function. Widget is more suitable when there is more than one view needed to display it.
//in the protected/components/mywidget
class MyWidget extends CWidget{
    public function init(){
        //do initializing...
    public function run(){
        //render or echoing something...
//in the view.php
<?php $this->widget('application.components.mywidget.MyWidget'); ?>
  1. Put the function to the controller. If the function only used in one view. Then it is better to putt into the Controller.

  2. Use the view file. Because the CController's render() and renderPartial() methods can return value instead displaying it, using view as the function is possible. That's mean we can put the function into certain view file (preferably in one folder with the caller if the caller only one). To make the render return value we must specified the third parameter to be 'true'.

//in the _view_function.php
<?php //echo something ?>
// in the view.php
<?php $this->renderPartial('_view_function', null, true); ?>

Total 2 comments

#11622 report it
Mathew Gor at 2013/01/23 06:55am
Calling a controller method from a view

It's a bad practice to call controller methods from view files. The goal is to decouple controllers and views and by doing it you're creating an unnecessary coupling.

#2418 report it
Maurizio Domba Cerin at 2010/12/28 02:31am

If the view code/function will be used in more than one view... then creating a widget is the best way, but if the function is to be used only by that view/controller than you can put the function in the controller (better than in the model)...

class DocumentController extends Controller
   public function testXY()
      return "complex display";

and from the view you call it like

<?php echo $this->testXY(); ?>

Leave a comment

Please to leave your comment.