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:
You load helpers in CakePHP by declaring them in a view class. An class comes with every CakePHP application and is the ideal place to loadhelpers:
To load helpers from plugins use the used elsewhere inCakePHP:
- $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:
- // Loads the FormHelper if it has not already been loaded.
- $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.
You can use the current action name to conditionally load helpers:
- class AppView extends View
- {
- public function initialize(): void
- {
- parent::initialize();
- if ($this->request->getParam('action') === 'index') {
- $this->loadHelper('ListPage');
- }
- }
- }
You can also use your controller’s beforeRender
method to load helpers:
- class ArticlesController extends AppController
- {
- public function beforeRender(EventInterface $event)
- {
- parent::beforeRender($event);
- $this->viewBuilder()->helpers(['MyHelper']);
- }
- }
Configuration options
You can pass configuration options to helpers. These options can be used to setattribute values or modify the behavior of a helper:
- namespace App\View\Helper;
- use Cake\View\Helper;
- use Cake\View\View;
- class AwesomeHelper extends Helper
- {
- public function initialize(array $config): void
- {
- debug($config);
- }
- }
Options can be specified when declaring helpers in controller as shown:
- namespace App\View\Helper;
- use Cake\View\StringTemplateTrait;
- class AwesomeHelper extends Helper
- {
- use StringTemplateTrait;
- protected $_defaultConfig = [
- 'errorClass' => 'error',
- 'templates' => [
- 'label' => '<label for="{{for}}">{{content}}</label>',
- ],
- ];
- }
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 getConfig()
method to read runtime configuration:
- // Read the errorClass config option.
- $class = $this->Awesome->getConfig('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:
- class PostsController extends AppController
- {
- public function beforeRender(EventInterface $event)
- {
- parent::beforeRender($event);
- $builder = $this->viewBuilder();
- $builder->helpers([
- 'CustomStuff' => $this->_getCustomStuffConfig(),
- ]);
- }
- }
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:
- // src/View/AppView.php
- class AppView extends View
- {
- public function initialize(): void
- {
- $this->loadHelper('Html', [
- 'className' => 'MyHtml'
- ]);
- }
- }
- // src/View/Helper/MyHtmlHelper.php
- namespace App\View\Helper;
- use Cake\View\Helper\HtmlHelper;
- class MyHtmlHelper extends HtmlHelper
- {
- // Add your code to override the core HtmlHelper
- }
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.
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:
- echo $this->Html->css('styles');
The above would call the css()
method on the HtmlHelper. You canaccess any loaded helper using $this->{$helperName}
.
There may be situations where you need to dynamically load a helper from insidea view. You can use the view’s todo this:
Helpers feature several callbacks that allow you to augment the view renderingprocess. See the Helper Class and the documentation for more information.
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:
- /* src/View/Helper/LinkHelper.php */
- namespace App\View\Helper;
- use Cake\View\Helper;
- class LinkHelper extends Helper
- {
- public function makeEdit($title, $url)
- // Logic to create specially formatted link goes here...
- }
- }
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:
- /* src/View/Helper/LinkHelper.php (using other helpers) */
- namespace App\View\Helper;
- use Cake\View\Helper;
- class LinkHelper extends Helper
- {
- public $helpers = ['Html'];
- public function makeEdit($title, $url)
- {
- // Use the HTML helper to output
- // Formatted data:
- $link = $this->Html->link($title, $url, ['class' => 'edit']);
- return '<div class="editOuter">' . $link . '</div>';
- }
- }
Using Your Helper
Once you’ve created your helper and placed it in src/View/Helper/, you canload it in your views:
- class AppView extends View
- {
- public function initialize(): void
- {
- parent::initialize();
- $this->loadHelper('Link');
- }
- }
Once your helper has been loaded, you can use it in your views by accessing thematching view property:
- <!-- make a link using the new helper -->
- <?= $this->Link->makeEdit('Change this Recipe', '/recipes/edit/5') ?>
Note
The HelperRegistry
will attempt to lazy load any helpers notspecifically identified in your Controller
.
If you would like to access a View variable inside a helper, you can use$this->_View->get()
like:
- class AwesomeHelper extends Helper
- {
- public $helpers = ['Html'];
- public function someMethod()
- {
- // set meta description
- echo $this->Html->meta(
- 'description', $this->_View->get('metaDescription'), ['block' => 'meta']
- );
- }
- }
Rendering A View Element Inside Your Helper
- 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 in your callbacks, as the base Helper classdoes not implement any of the callback methods.
Helper::
beforeRenderFile
(EventInterface $event, $viewFile)- Is called before each view file is rendered. This includes elements,views, parent views and layouts.
Helper::
afterRenderFile
(EventInterface $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
(EventInterface $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
(EventInterface $event, $viewFile)- Is called after the view has been rendered but before layout rendering hasstarted.
Helper::
beforeLayout
(EventInterface $event, $layoutFile)- Is called before layout rendering starts. Receives the layout filename as anargument.