Quick tip: Get element content within the controller in CakePHP

Bookmark and Share

This is an easy quick tip to able able to get an element’s content from within a controller in CakePHP 1.2 or 1.3. The trick is simple you just need an instance from View class to be able to use its element function within the controller. To do this use the following code inside your action:

$view = new View($this, false);
$content = $view->element('my-element', $params);

$params is an optional parameters array which is sent to the element to be used as variables. You can also use $view->set() just as you use $this->set() in your controller.

Now as you know it, how you intend to use? or what was the situation where you needed to use something like this?

3 comments on “Quick tip: Get element content within the controller in CakePHP

  1. Hi there!
    Thanks for the nice tip!
    To answer your question, I have to create some kind of newsletter system. Instead of my controller sending the email to multiple recipients, I want it to save the content of the email in the database. A cron job will take care of the actual sending of the email later.
    I could have created the content of the email directly inside the controller, but that would have completely broken the MVC pattern, and I just don’t like it :)


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>