When to use element() and when to requestAction() When to use element() and when to requestAction()

Several times a week it seems, someone at my office is asking, "Jamie, should I use $this->element() or $this->requestAction()?"

Every time they ask, I ask them back, "What do you need to do?"

There are a few simple ways to determine if using an element is better or a request action is better.

To begin, let's describe the difference. 

A requestAction, performs the entire function in the controller you are calling.  E.g. if you perform database queries and data manipulation, that all gets executed by CakePHP and then it renders the view for that function.

This is different from an element because with an element, CakePHP simply renders the content in the view.

So, with those in my mind, I bet you are already getting a good feel when to use which.  Here are my rules of thumb for when to use requestAction():

  1. Do you require database access?
  2. Do you want to re-use an existing controller function?
  3. Are you doing anything else that should not be in a view?

If you answer yes to any of the above, use a requestAction() on the controller and function.  If you answered no, you most likely want to use an element.

In case you found this article during a search and looking for some examples, here you go.  Below is an example of calling a requestAction and you can definitely extend this to make it even prettier with Organizing data with the jQuery Sortable plugin.


The above statement will call the invite function inside the users controller.  It passes "send" as the first input parameter and 35 as the second.  Basically, the data you pass in is the exact same data you would pass through the URL.

To perform an element request you do the following:

$this->element('display_user', array('user' => $user));

The above statement will load the display_user.ctp file in app/views/elements and will pass in the variable $user to the element.

Until next time.

Published on Mar 16, 2009

Tags: CakePHP Tutorial | Optimization

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.


Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.