0

I am creating a simple website in cakephp.

I have kept header and footer in "element" but my problem is that menu of header is coming from database and it will not be available until I call a function.

I want as soon as controller is called function of menu should be called by own.

2 Answers 2

3

In your AppController add this:

function beforeFilter(){
    $this->set('menu', $this->YourModel->findById('Id of your menu data row in database'));
}

Then, in the view, the menu will be accessible by calling echo $menu['yourModel']['menu'];

0
1

TLDR:

Instead of calling the function every time the entire controller (or all controllers) is loaded, it's better practice to just call the function when the element itself is loaded. This allows you much more flexibility moving forward. Eg, maybe the log-in screen doesn't need the menu - or maybe you eventually add an admin tool that has a different menu...etc etc.

CakePHP makes this VERY easy using requestAction() - read more here: http://book.cakephp.org/2.0/en/views.html#passing-variables-into-an-element

Side Note: It's also ideal (MVC pattern and many other reasons) to keep ALL queries in a model, instead of calling them directly from a controller.

Example Code:

/**
 * MenusController (or any other controller you want)
 */
public function get_menu_main() {
    $this->set('menu', $this->Menu->getMenuMain());
}
public function get_menu_footer() {
    $this->set('menu', $this->Menu->getMenuFooter());
}

/**
 * Menu model
 */
public function getMenuMain() {
    return $this->findById('12345');
}
public function getMenuFooter() {
    return $this->findById('67891');
}

Then, in your element, just use a requestAction to retrieve the data you need for that specific element:

/**
* MainMenu element
*/
$menu = $this->requestAction('menus/get_menu_main/');

/**
* FooterMenu element
*/
$menu = $this->requestAction('menus/get_menu_footer/');

Side note: to be a little more proper, you can use $this->Html->url() instead of hard-coding the URLs to the actions.

Side note: Some of this code might seem like adding extra code when you don't "need" it, but by breaking things up into their correct MVC spot, your code will be much cleaner, more flexible/upgradable...etc etc etc. Getting into a habit of doing things like this will make your life MUCH easier when things start to get even slightly more complicated. (And in all reality, the code above adds a few lines, but as far as complexity is concerned, I think it's easier to understand than having a query in the AppController that loads variables for an element(s). /endrant

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.