Using Element in cakePHP

Element is really necessary if we want to use a code more than once in the view or layout. Instead we have rewritten many times in the view with a similar source segment, we just write once in the elements and use them repeatedly. Creating an element used repeatedly in cakephp will be very easy when we use requestAction function. Here I will guide you to use the element that used to be in the cakephp 1.1 and 1.2.



First, we will create Post controller follows:

<?php
class PostsController extends AppController {
 var $name = 'Posts';
 function index() {
  $posts = $this->Post->findAll(); 
  //check function requestAction have been call or not
  if(isset($this->params['requested'])) {
   return $posts;
  }
  $this->set('posts', $posts);
 }
}
?>

In Index function, we will check that it has been called by requestAciton function or not. If so, the function returns an array $ posts. Now we'll create an element post.ctp (or post.thml in cakephp 1.1) has the following path: /app/elements/posts.ctp.

<?php
 $posts = $this->requestAction('posts/index'); 
 foreach($posts as $post):
 echo $post['Post']['title'];
 endforeach; 
?>

To use that element, we only add a paragraph code to views or layouts:


<?php echo $this->renderElement('posts');?>