CakePHP : Change view file from controller

Sat, Aug 9, 2008

CakePHP, PHP

With CakePHP, the controller core automatically detects the file name of the view file which needs to be rendered from a controller action. You might want to reuse an existent view for an action or specify a different file name.

For example, if you have a controller named “Users” and you execute a controller action named “profile”, the view file “users/profile.ctp” will be automatically rendered. But you might want to output a view file named “edit.ctp” in the “users” folder. You can do this with the render method.

$this -> render(‘edit’);

The code above will automatically render the “users/edit.ctp” view file after the controller action/method has been executed. But say for example that your “edit.ctp” file is not within the “users” folder, but rather inside a folder named “accounts”. Then you can change the viewPath and then execute the render method.

$this -> viewPath = ‘accounts’;
$this -> render(‘edit’);

So the code above will output the “accounts/edit.ctp” view file.

, , , , ,
scriptlancebannerpng

This post was written by:

Antonie Potgieter - who has written 46 posts on Lost-In-Code.

I (Antonie Potgieter) am a software engineer/web developer located in South Africa. My full-time work is the management of Tribulant Software and the development of its software packages.

Contact the author

3 Comments For This Post

  1. retomi Says:

    Thanks for your support!

  2. yaqoob Says:

    thanks for pointing out, I was looking for that info

  3. Smart Pad Says:

    Thanks. This is exactly what I am looking for.

Leave a Reply