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

W

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.

[code]$this->requestAction(‘/users/invite/send/35’);
[/code]

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:

[code]$this->element(‘display_user’, array(‘user’ => $user));
[/code]

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.

About the author

By Jamie

My Books