Helpers

Helpers are the component-like classes for the presentation layer of yourapplication. They contain presentational logic that is shared between manyviews, elements, or layouts. This chapter will show you how to configurehelpers. How to load helpers and use those helpers, and outline the simple stepsfor creating your own custom helpers.

CakePHP includes a number of helpers that aid in view creation. They assist increating well-formed markup (including forms), aid in formatting text, times andnumbers, and can even speed up AJAX functionality. For more information on thehelpers included in CakePHP, check out the chapter for each helper:

Configuring Helpers

You load helpers in CakePHP by declaring them in a view class. An AppViewclass comes with every CakePHP application and is the ideal place to loadhelpers:

  1. class AppView extends View
  2. {
  3. public function initialize()
  4. {
  5. parent::initialize();
  6. $this->loadHelper('Html');
  7. $this->loadHelper('Form');
  8. $this->loadHelper('Flash');
  9. }
  10. }

To load helpers from plugins use the plugin syntax used elsewhere inCakePHP:

  1. $this->loadHelper('Blog.Comment');

You don’t have to explicitly load Helpers that come from CakePHP or yourapplication. These helpers can be lazily loaded upon first use. For example:

  1. // Loads the FormHelper if it has not already been loaded.
  2. $this->Form->create($article);

From within a plugin’s views, plugin helpers can also be lazily loaded. Forexample, view templates in the ‘Blog’ plugin, can lazily load helpers from thesame plugin.

Conditionally Loading Helpers

You can use the current action name to conditionally load helpers:

  1. class AppView extends View
  2. {
  3. public function initialize()
  4. {
  5. parent::initialize();
  6. if ($this->request->getParam('action') === 'index') {
  7. $this->loadHelper('ListPage');
  8. }
  9. }
  10. }

You can also use your controller’s beforeRender method to load helpers:

  1. class ArticlesController extends AppController
  2. {
  3. public function beforeRender(Event $event)
  4. {
  5. parent::beforeRender($event);
  6. $this->viewBuilder()->helpers(['MyHelper']);
  7. }
  8. }

Configuration options

You can pass configuration options to helpers. These options can be used to setattribute values or modify the behavior of a helper:

  1. namespace App\View\Helper;
  2.  
  3. use Cake\View\Helper;
  4. use Cake\View\View;
  5.  
  6. class AwesomeHelper extends Helper
  7. {
  8.  
  9. // initialize() hook is available since 3.2. For prior versions you can
  10. // override the constructor if required.
  11. public function initialize(array $config)
  12. {
  13. debug($config);
  14. }
  15. }

Options can be specified when declaring helpers in controller as shown:

  1. namespace App\Controller;
  2.  
  3. use App\Controller\AppController;
  4.  
  5. class AwesomeController extends AppController
  6. {
  7. public $helpers = ['Awesome' => ['option1' => 'value1']];
  8. }

By default all configuration options will be merged with the $_defaultConfigproperty. This property should define the default values of any configurationyour helper requires. For example:

  1. namespace App\View\Helper;
  2.  
  3. use Cake\View\Helper;
  4. use Cake\View\StringTemplateTrait;
  5.  
  6. class AwesomeHelper extends Helper
  7. {
  8.  
  9. use StringTemplateTrait;
  10.  
  11. protected $_defaultConfig = [
  12. 'errorClass' => 'error',
  13. 'templates' => [
  14. 'label' => '<label for="{{for}}">{{content}}</label>',
  15. ],
  16. ];
  17. }

Any configuration provided to your helper’s constructor will be merged with thedefault values during construction and the merged data will be set to_config. You can use the config() method to read runtime configuration:

  1. // Read the errorClass config option.
  2. $class = $this->Awesome->config('errorClass');

Using helper configuration allows you to declaratively configure your helpers andkeep configuration logic out of your controller actions. If you haveconfiguration options that cannot be included as part of a class declaration,you can set those in your controller’s beforeRender callback:

  1. class PostsController extends AppController
  2. {
  3. public function beforeRender(Event $event)
  4. {
  5. parent::beforeRender($event);
  6. $builder = $this->viewBuilder();
  7. $builder->helpers([
  8. 'CustomStuff' => $this->_getCustomStuffConfig(),
  9. ]);
  10. }
  11. }

Aliasing Helpers

One common setting to use is the className option, which allows you tocreate aliased helpers in your views. This feature is useful when you want toreplace $this->Html or another common Helper reference with a customimplementation:

  1. // src/View/AppView.php
  2. class AppView extends View
  3. {
  4. public function initialize()
  5. {
  6. $this->loadHelper('Html', [
  7. 'className' => 'MyHtml'
  8. ]);
  9. }
  10. }
  11.  
  12. // src/View/Helper/MyHtmlHelper.php
  13. namespace App\View\Helper;
  14.  
  15. use Cake\View\Helper\HtmlHelper;
  16.  
  17. class MyHtmlHelper extends HtmlHelper
  18. {
  19. // Add your code to override the core HtmlHelper
  20. }

The above would alias MyHtmlHelper to $this->Html in your views.

Note

Aliasing a helper replaces that instance anywhere that helper is used,including inside other Helpers.

Using Helpers

Once you’ve configured which helpers you want to use in your controller,each helper is exposed as a public property in the view. For example, if youwere using the HtmlHelper you would be able to access it bydoing the following:

  1. echo $this->Html->css('styles');

The above would call the css() method on the HtmlHelper. You canaccess any loaded helper using $this->{$helperName}.

Loading Helpers On The Fly

There may be situations where you need to dynamically load a helper from insidea view. You can use the view’s Cake\View\HelperRegistry todo this:

  1. // Either one works.
  2. $mediaHelper = $this->loadHelper('Media', $mediaConfig);
  3. $mediaHelper = $this->helpers()->load('Media', $mediaConfig);

The HelperRegistry is a registry andsupports the registry API used elsewhere in CakePHP.

Callback Methods

Helpers feature several callbacks that allow you to augment the view renderingprocess. See the Helper Class and theEvents System documentation for more information.

Creating Helpers

You can create custom helper classes for use in your application or plugins.Like most components of CakePHP, helper classes have a few conventions:

  • Helper class files should be put in src/View/Helper. For example:src/View/Helper/LinkHelper.php
  • Helper classes should be suffixed with Helper. For example: LinkHelper.
  • When referencing helper class names you should omit the Helper suffix. Forexample: $this->loadHelper('Link');.
    You’ll also want to extend Helper to ensure things work correctly:
  1. /* src/View/Helper/LinkHelper.php */
  2. namespace App\View\Helper;
  3.  
  4. use Cake\View\Helper;
  5.  
  6. class LinkHelper extends Helper
  7. {
  8. public function makeEdit($title, $url)
  9. {
  10. // Logic to create specially formatted link goes here...
  11. }
  12. }

Including Other Helpers

You may wish to use some functionality already existing in another helper. To doso, you can specify helpers you wish to use with a $helpers array, formattedjust as you would in a controller:

  1. /* src/View/Helper/LinkHelper.php (using other helpers) */
  2.  
  3. namespace App\View\Helper;
  4.  
  5. use Cake\View\Helper;
  6.  
  7. class LinkHelper extends Helper
  8. {
  9. public $helpers = ['Html'];
  10.  
  11. public function makeEdit($title, $url)
  12. {
  13. // Use the HTML helper to output
  14. // Formatted data:
  15.  
  16. $link = $this->Html->link($title, $url, ['class' => 'edit']);
  17.  
  18. return '<div class="editOuter">' . $link . '</div>';
  19. }
  20. }

Using Your Helper

Once you’ve created your helper and placed it in src/View/Helper/, you canload it in your views:

  1. class AppView extends View
  2. {
  3. public function initialize()
  4. {
  5. parent::initialize();
  6. $this->loadHelper('Link');
  7. }
  8. }

Once your helper has been loaded, you can use it in your views by accessing thematching view property:

  1. <!-- make a link using the new helper -->
  2. <?= $this->Link->makeEdit('Change this Recipe', '/recipes/edit/5') ?>

Note

The HelperRegistry will attempt to lazy load any helpers notspecifically identified in your Controller.

Accessing View Variables Inside Your Helper

If you would like to access a View variable inside a helper, you can use$this->_View->get() like:

  1. class AwesomeHelper extends Helper
  2. {
  3.  
  4. public $helpers = ['Html'];
  5.  
  6. public function someMethod()
  7. {
  8. // set meta description
  9. echo $this->Html->meta(
  10. 'description', $this->_View->get('metaDescription'), ['block' => 'meta']
  11. );
  12. }
  13. }

Rendering A View Element Inside Your Helper

If you would like to render an Element inside your Helper you can use$this->_View->element() like:

  1. class AwesomeHelper extends Helper
  2. {
  3. public function someFunction()
  4. {
  5. // output directly in your helper
  6. echo $this->_View->element(
  7. '/path/to/element',
  8. ['foo'=>'bar','bar'=>'foo']
  9. );
  10.  
  11. // or return it to your view
  12. return $this->_View->element(
  13. '/path/to/element',
  14. ['foo'=>'bar','bar'=>'foo']
  15. );
  16. }
  17. }

Helper Class

  • class Helper

Callbacks

By implementing a callback method in a helper, CakePHP will automaticallysubscribe your helper to the relevant event. Unlike previous versions of CakePHPyou should not call parent in your callbacks, as the base Helper classdoes not implement any of the callback methods.

  • Helper::beforeRenderFile(Event $event, $viewFile)
  • Is called before each view file is rendered. This includes elements,views, parent views and layouts.

  • Helper::afterRenderFile(Event $event, $viewFile, $content)

  • Is called after each view file is rendered. This includes elements, views,parent views and layouts. A callback can modify and return $content tochange how the rendered content will be displayed in the browser.

  • Helper::beforeRender(Event $event, $viewFile)

  • The beforeRender method is called after the controller’s beforeRender methodbut before the controller renders view and layout. Receives the file beingrendered as an argument.

  • Helper::afterRender(Event $event, $viewFile)

  • Is called after the view has been rendered but before layout rendering hasstarted.

  • Helper::beforeLayout(Event $event, $layoutFile)

  • Is called before layout rendering starts. Receives the layout filename as anargument.

  • Helper::afterLayout(Event $event, $layoutFile)

  • Is called after layout rendering is complete. Receives the layout filenameas an argument.