php - How to run an action of controller file from .ctp file?


I want to call an action along 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).





Create an element, for instancelist_category.ctp.

In the element userequestAction to get the data:

    $categories = $this->requestAction('/users/list_categories');

<?php foreach($categories as $category): ?>

    <?php // Your display code goes here ?>

<?php endforeach; ?>

In your controller make sure youreturn the data you want.

    function list_categories() {

        return $this->User->Category->find('all');


You can reuse the code for yourlist_category.ctp view.

There is an overhead when usingrequestAction 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.

People are also looking for solutions to the problem: php - Detect water/sea between two lat longs


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.