How to run an action of controller file from .ctp file?
I want to call an action al开发者_StackOverflow社区ong with its .ctp file of a controller file from another .ctp file. for e.g.
users_controller.php has an action called list_category() and I want to call it from /app/views/pages/index.ctp file. Not just call list_category but also want to show its html output(I mean also list_category.ctp should be rendered).
Thanks.
Create an element, for instance list_category.ctp
.
In the element use requestAction
to get the data:
<?php
$categories = $this->requestAction('/users/list_categories');
?>
<?php foreach($categories as $category): ?>
<?php // Your display code goes here ?>
<?php endforeach; ?>
In your controller make sure you return
the data you want.
<?php
function list_categories() {
return $this->User->Category->find('all');
}
?>
You can reuse the code for your list_category.ctp
view.
There is an overhead when using requestAction
but it is often less than people believe.
Can you do that with routing? I'm not sure of the syntax off the top of my head but I think you can specify that method that the controller runs when you land on that page
It seems wrong, what is it that you're trying to accomplish? How about elements?
How about calling the controller from your main controller, then pass its results to your layout. Finally use an element to render the output there and also use the element to render the output on that other controller too. That way you don't have duplicate layouts. Just one element used by two controllers.
This is very similar to the way Rails creates its layouts when you 'bake' them. It creates an equivalent of a element to use in the add and edit layouts.
This can be done with requestAction, but be aware, that it's expensive and you should be careful with it.
精彩评论