Andrew Tat
Andrew Tat

Reputation: 463

Cakephp Navigation Bar: Populate in an Element with Data from a Model

I'm trying to create a navigation bar for my website that will grab information from Model's database table. The navigation bar currently is implemented in an Element and has hard-coded links. Here's what I have so far:

In the Photo controller I have this:

public function get_all() {
    return $this -> Photo -> find("all");
}

In the header.ctp Element I have this:

<ul>
    <?php
        $photos = $this -> Photo -> get_all();
        foreach($photos as $photo) {
            ?>
            <li><?= $this -> Html -> link($photo["Photo"]["title"], array("action" => "view", $photos["Photo"]["id"])) ?></li>
            <?php
        }
    ?>
</ul>

I'm still new to Cakephp; what should I do/change to access database tables from an Element?

Upvotes: 2

Views: 589

Answers (1)

Reactgular
Reactgular

Reputation: 54771

You want to use a requestAction in the element to ask a controller to provide you with the list from the model.

You were almost there.

 <ul>
     <?php
         $photos = $this->requestAction(array('controller'=>'photos','action'=>'get_all'));
         foreach($photos as $photo) {
             ?>
             <li><?= $this -> Html -> link($photo["Photo"]["title"], array("action" =>      "view", $photos["Photo"]["id"])) ?></li>
             <?php
         }
     ?>
 </ul>

Upvotes: 1

Related Questions