CakePHP: working with Elements

An element (like it is named) is a part of a web page which can be display into multiple pages (a sort of template if you want). Here are some elements’ examples:

  • A header: with your banner, your brand logo
  • A menu: with your categories, links
  • A footer: company name, copyright

    An element (like it is named) is a part of a web page which can be display into multiple pages (a sort of template if you want). Here are some elements’ examples:

    • A header: with your banner, your brand logo
    • A menu: with your categories, links
    • A footer: company name, copyright

    In CakePHP, Elements are located in the app/views/elements/ directory (or if you are using a custom theme you can create specific elements and put them in the /app/views/themed/your_theme_folder/elements/ directory).

    So let’s get started. We will create a basic element which will display ‘Hello World!’:

    Hello World

    You can save this Element: app/view/elements/helloworld.ctp
    The last step is to include the element in our pages, to do so you just have to request it like that:

    /*For instance I want to display Hello Word on my app/views/posts/index.ctp page:*/
    echo $this->element('helloworld');

    Elements using Controller with requestAction

    Displaying basic information is great, but it would be much more better if we could access to our data and request something like the five latest comments or posts added. This is indeed possible through the requestAction method.

    First of all, we have to add a method in our controller which will allow us to retrieve the data we want to render.

    /* For instance I want to display the 5 latest posts on my index page. */
    public function lastposts($limit=5)
    {
    /* We retrieve only the required fields, and configure the query. */
    $posts = $this->Post->find('all', array('fields'=>array('Post.id', 'Post.name', 'Post.created'),
       'recursive'=>0,
       'order'=>array('Post.created desc'),
       'limit'=>$limit));
    if(isset($this->params['requested']))
    {
    return $posts;
    }
    $this->set('lastposts', $posts);
    }

    Second of all, we create our element. This step is exactly the same as what we have done before, create a page called lastposts.ctp in your app/views/elements/ directory but this time there will be more code’s lines.

    The first thing to do in your element is to get our data, to do that you will have to use the requestAction method, now you are ready to display your latest posts:

Leave a Reply

Your email address will not be published. Required fields are marked *