using function/widget/behavior to 'include' code

Hi guys

To prevent duplication of code, I have the following function in my controller:


public function renderView($view, $model)

{

         if (Yii::app()->request->isAjaxRequest){

	    echo CJSON::encode(array(

		'form'=>$this->renderPartial(...

        }

        else{

	    $this->render(...

	}




It is used by the index, create, update and view actions in this way:

$this->renderview($view, $model);

Since the renderView function will be identical in 90% of the CRUD controllers, I want to store it in a separate file - to be used like a simple php ‘include’.

I tried helper functions, widgets and behaviors - all with problems. The error I got for behaviors said that behaviours do not have a ‘render’ method.

Should I keep on duplicating the function in the controllers or is there a better way?

If you generated the CRUD with GII, there is Controller.php in the components dir. Just add your renderView to it. You may need to modify your code to also get/send which controller you are calling from (possible $this->getController()->id).

all because of


$this

try


Yii::app()->getController()->render(...

OK thanx guys. Will try.

You can still use behaviors and use $this in a similar manner. You just need to use $this->owner->render() in the behavior code. In the scope of the behavior, $this->owner is the object to which the behavior is attached.

Thanx for the tip SpikyJT. Will check that method as well.