Side menu element which uses data from table

Hi everybody,

I would like to ask somebody kindly to help me with following issue with my CakePHP 4.2.4 app.

I created a simple web app - a register of subjects authorised to perform some activities. My app is based on several tables, like e.g. Subjects, People, Certificates, Workplaces, Menus …

I would like to make an element that would serve as side menu. This side menu shoud be generated automaticaly using the table Menus, which contains these data:
Menus (id,link name, controller, action, date of creation, date of change)

I baked simple actions like add, view edit links and everything works as it should. I modified /myapp/Menus/index.php into file sidemenu.php (and added corresponding action into MenusController.php) that show a list of working links.

public function sidemenu()
{
    $menus = $this->paginate($this->Menus);

    $this->set(compact('menus'));
}

When I copy sidemenu.php into file into /myapp/templates/element folder, and then incorporate element sidemenu.php into layout file default.php ($this->element(‘helpbox’)), it stops working.

The problem is that variable $menus is empty. Is there a way how to load table content into variable $menus in my element automatically?

Thank you very much!

You should take a look at cells, instead of using elements.

When to use Cells

Cells are ideal for building reusable page components that require interaction with models, view logic, and rendering logic. A simple example would be the cart in an online store, or a data-driven navigation menu in a CMS.

https://book.cakephp.org/4/en/views/cells.html

1 Like

dirk, thank you very much for help. Thanks to you and cookbook, my menu is working now. Here is what I did:

  1. Using console, I created file \myapp\src\View\Cell\MenuCell.php (bin/cake bake cell Menu). I needed to use paginator, so I added “use Cake\Datasource\Paginator;” and created public function display(). Result is below:

  1. Then I edited file display.php created also using cake console in the first step. The file was created in folder \myapp\templates\cell\Menu\display.php. Content of the file is below:

  1. Finally I included cell in default.php layout file locate in \myapp\templates\layout folder, respective section of the code is bellow:

3