CakePHP - Helper

Helpers, as its names suggest helping the component of other files for showing the same presentational logic of the CakePHP application. These components are shared between view files, elements, or layouts in the CakePHP application. The Html helpers ($this->Html) class defined in Template/Layout/default.ctp. Also, if you want to modify your default style, then you can do it in default.ctp file of the view.

You can access HtmlHelper in Cakephp by this path www\CakePHP3.8\vendor\cakephp\cakephp\src\View\Helper\HtmlHelper. In the Helper folder, there is a file HtmlHelper.php in which we have defined many methods like CSS, Javascript, meta function, etc. in the Html class, but we have defined only four methods in default.ctp file by this syntax in <head> like

 <head>
 <?= $this->Html->charset() ?>  // it define the UTF-8 
 <?= $this->Html->meta('icon') ?> // this contain icon will show in template
    <?= $this->Html->css('base.css') ?> //it contain css file link
    <?= $this->Html->css('style.css') ?>
            <?= $this->Html->script('script') ?> //this used for javascript file link 
</head>

CakePHP includes a number of helpers that help in view creation. They can support in creating well-formed markup language (including forms), formatting text, times and numbers, and can even speed up AJAX functionality. There are Few more helpers included in CakePHP.

  • Breadcrumbs
  • Flash
  • Form
  • Html
  • Number
  • Paginated
  • Url

Breadcrumbs

The breadcrumb class is used in a web application to show the current state of the user. It works as a linker through which we can jump from one controller to another controller by defining their names. It used for showing the menu in CakePHP like Home, then menu, and about us all the steps for displaying the status of the user.

Creation of Breadcrumbs

You can create a crumb to the list using the add () method. It has three arguments:

Title - The string to be displayed as the title of the crumb or record

URL - A string or an array of parameters that will be given to the Url or action which you want to call in your controller's action.

options - An array of attributes for the item and item without link templates.

The given statement will show only a single linker on your browser, and this link will call your controller, which you have defined in Breadcrumbs add() function.

Here is the example of Breadcrumbs

 $this-> Breadcrumbs-> add (
     'Home',
     ['controller' => 'second', 'action' => 'index'] 

If you want to add more breadcrumbs, you must define the other titles in the array with the controller and action names.

 $this-> Breadcrumbs ->add ([
     ['title' => 'Home', 'url' => ['controller' => 'controllerName', 'action' => 'index']],
     ['title' => Contact, 'url' => ['controller' => 'ControllerName', 'action' => 'view']]
 ]); 

Here Render() method is used to display the values of Breadcrumbs, which we have created in add() function. This method accepts two array arguments:

$attributes: It defines the array's attributes that will be applied to the wrapper template. It allows you to add attributes to HTML tags. It accepts unique templateVars keys to allow the insertion of custom template variables into the template.

$separator: An array of features for the separator template. These are some of the qualities:

Separator:  It represents for the particular string which you want to be displayed as a separator

innerAttrs: To provide characteristics in case your separator is divided into two elements

templateVars: It Allows the insertion of custom template variable in the template.

 echo $this-> Breadcrumbs-> render (
     ['class' => 'breadcrumbs-trail'],
     ['separator' => '<i class=" angle-right"></i>']
 ); 

This is your controller’s action file fun2.ctp and here is the path where we have created the file: C:\wamp64\www\CakePHP3.8\src\Template\Layout\fun2.ctp

 <?php
 $this-> Breadcrumbs-> add (
    'Home',
    ['controller' => 'second', 'action' => 'fun2']
 ); 
 $this-> Breadcrumbs->add ([
    ['title' => 'Application', 'url' => ['controller' => 'first', 'action' => 'fun']],
    ['title' => 'Contact', 'url' => ['controller' => 'second', 'action' => 'view']]
 ]);
 $this-> Breadcrumbs-> templates ([ 
    'wrapper' => '<ol class="breadcrumb">{{content}}</ol>',
             'item' => '<li><a href="{{url}}">{{title}}</a></li>',
 ]);
 echo $this-> Breadcrumbs ->render (['separator' => '<i class=" angle-right"></i>']
 );
 ?> 

Output of breadcrumb:

CakePHP - Helper

Url – The UrlHelper makes it easy for you to generate URLs from other helpers. The build is a function in which we generate a URL by passing the controller name, action, and argument; also, we can link to another controller's method.

 echo  $this-> Url-> build ([
     "controller" => "Posts",
     "action" => "search", 
     "?" => ["name" => "amit",”tutorial”=>”javatpoint”]  
]); 

$this-> Url-> css ():– By use this function of url helper, we can pass css file in Template\Layout’s file.

<link href = "<?php echo $this->Url->css(class.css) ?>" rel=”stylesheet”/>

 $this-> Url-> script ():- we can simply pass script file in layout folder.

<script href = ”<?php echo $this->Url->script(plugin.js.) ?>">< /script>

$this-> Url-> image (): – By use this method of url, we can show image on any page.

<img src="<?php  echo $this->Url->image('car.jpeg') ?>"/>

Flash()

FlashComponent provides a way to set a one-time notification message or pop up window to be displayed after submission of form or input the data. CakePHP refers to these messages as "flash messages". FlashComponent displays the flash message to $ _SESSION, which is to be rendered.

Syntax:

 public function showmessage()
 {
 $this-> Flash->set (‘You have successfully registered’, [ ‘element’ = >’success’]); 
}

After creating this method in our controller we have to create a new #.ctp file in CakePHP3.8\src\Template\Second\#.ctp With the given below text in our .ctp file.

 <?= $this->Flash->render() ?>

And we got the output:

CakePHP - Helper 1

And if You want to show an error message then simply write [‘element’ => ‘error’]

 $this->Flash->set (You have successfully registered’, [ ‘element’ => ‘error’]);

Output: -

CakePHP - Helper 2

Custom Helper

You can also create a custom helper in view folder of Helper according to the needs of the application.

These are the steps to create a custom helper in an application.

  • You have to create a custom helper file inside the Helper folder of view likeFirstHelper.php.
  • You have to define the custom function in your Controller file like PostController.php
  • You also have to create a layout file of the function which you have defined in the Controller file.
  • You have to load your custom helper file in the AppView.php file of Helper.

Example:

This is PostsController.php file

 <?php
 namespace App\Controller;
 use App\Controller\AppController;
 class PostsController extends AppController{
  public function index(){
 }
 }
 ?> 

Now we have to create the Firsthelper.php file at the src/view/Helper/Firsthelper.php.

 <?php
 namespace App\View\Helper;
 use Cake\View\Helper;
 class FirstHelper extends Helper{
    public function square($num) // this will square the digits which you have passed
    {
        return $num*$num;
    } 
    public function stringLength($string) // this function will count the length of the string
    {
        return strlen($string);
    }
 }
 ?> 

Now we have to create an index.ctp file for the Posts folder, which is described in src/template/Posts/index.ctp for displaying the data.

 <h2>Learn about Custom Helper in View</h2>
 <?php echo "When you multiply 5 * 5 = "; ?>
 <?php echo $this->First->square(5); ?>
 <br> <br>
 <?php echo "You have Passed this string 'CakePHP is a web Programming Language' for checking the length = "; ?>
 <?php echo $this->First->stringLength("CakePHP is a Web Programming Language"); ?> 

And the last you have to call the Firsthelper file in your AppView.php file inside the View folder.

Like

 public function initialize()
     { 
 $this->loadHelper("First");  // here we have passed the Helper class in AppView.php file
    } 

When you run your code in localhost like localhost/my_app_name/posts, then it will show this Output on your screen.

CakePHP - Helper 3



ADVERTISEMENT
ADVERTISEMENT