Passing AppController variables to elements in Cakephp

0

Is it possible to pass variables originating from the AppController's callbacks through the set method to layout elements in CakePHP?

    
asked by anonymous 12.06.2014 / 15:39

2 answers

1

Searching a little more, I found a way to solve:

The requestAction() function allows views and even elements of cakephp to request information of any controller/action you set, in true MVC style.

Just declare an action on% specific_co_de%:

class PostsController extends AppController {
    // ...
    public function index() {
        $posts = $this->paginate();
        if ($this->request->is('requested')) {   //Se for requisição de outra view/element:
            return $posts;
        } else {  //Senão envia para a view padrão
            $this->set('posts', $posts);
        }
    }
}

Then you call the function inside another view or in this case, an element:

helpbox.ctp

<h2>Últimos posts</h2>
<?php $posts = $this->requestAction('posts/index'); ?> <!--Passa a Action como parâmetro -->
<?php foreach ($posts as $post): ?>
    <ol>
        <li><?php echo $post['Post']['title']; ?></li>
    </ol>
<?php endforeach; ?>

Bonus: Caching the element to decrease requests in the Bank:

When calling Controller within some element or view , use the argument layout :

echo $this->element('helpbox', array(), array('cache' => true));

So I can call any cache declared as action on any public , any controller , without the need to pollute my view .

References: link

    
12.06.2014 / 16:41
0

But I have seen several users commenting that it is not a good practice to use "requestAction", and even it will be discontinued in version 3 of the cake, but if you just want to set a global variable that can be accessed in other areas, could do this:

class AppController extends Controller 
{
    function beforeFilter()
    {
        $visivelElements = ClassRegistry::init('Configuration')->find('all');
        $this->set('visivelElements', $visivelElements);
    }
}

If it were only visible in a certain controller, just do a check, something like:

class AppController extends Controller 
{
    function beforeFilter()
    {
        if ($this->name == 'Home') {
            $visivelElements = ClassRegistry::init('Configuration')->find('all');
            $this->set('visivelElements', $visivelElements);
        }            
    }
}
    
15.08.2014 / 14:01