Views. CakePHP 3.5
विज्ञापन
विज्ञापन
CHAPTER 11
Views
class Cake\View\View
Views are the V in MVC. Views are responsible for generating the specific output required for the request. Often this is in the form of HTML, XML, or JSON, but streaming files and creating PDF’s that users can download are also responsibilities of the View Layer.
CakePHP comes with a few built-in View classes for handling the most common rendering scenarios:
• To create XML or JSON webservices you can use the
JSON and XML views
• To serve protected files, or dynamically generated files, you can use
Sending Files
• To create multiple themed views, you can use
Themes
The App View
AppView is your application’s default View class. AppView itself extends the Cake\View\View class included in CakePHP and is defined in src/View/AppView.php as follows:
<?php
namespace
App\View;
use
Cake\View\View;
class AppView extends
View
{
}
You can use your AppView to load helpers that will be used for every view rendered in your application. CakePHP provides an initialize() method that is invoked at the end of a View’s constructor for this kind of use:
<?php
namespace
App\View;
use
Cake\View\View;
class AppView extends
View
{
259
CakePHP Cookbook Documentation, Release 3.5
}
public function
initialize ()
{
// Always enable the MyUtils Helper
$this -> loadHelper ( 'MyUtils' );
}
View Templates
The view layer of CakePHP is how you speak to your users.
Most of the time your views will be rendering
HTML/XHTML documents to browsers, but you might also need to reply to a remote application via JSON, or output a CSV file for a user.
CakePHP template files have a default extension of .ctp (CakePHP Template) and utilize the alternative PHP syntax
112 for control structures and output. These files contain the logic necessary to prepare the data received from the controller into a presentation format that is ready for your audience.
Alternative Echos
Echo, or print a variable in your template:
<?
php
echo
$variable ; ?>
Using Short Tag support:
<?= $variable ?>
Alternative Control Structures
Control structures, like if, for, foreach, switch, and while can be written in a simplified format. Notice that there are no braces. Instead, the end brace for the foreach is replaced with endforeach. Each of the control structures listed below has a similar closing syntax: endif, endfor, endforeach, and endwhile. Also notice that instead of using a semicolon after each structure (except the last one), there is a colon.
The following is an example using foreach:
<ul>
<?php foreach ( $todo
as
$item ) : ?>
<li> <?
= $item ?> </li>
<?php endforeach ; ?>
</ul>
Another example, using if/elseif/else. Notice the colons:
<?php if ( $username === 'sally' ) : ?>
<h3>Hi Sally</h3>
<?php elseif ( $username === 'joe' ) : ?>
<h3>Hi Joe</h3>
<?php else : ?>
112 http://php.net/manual/en/control-structures.alternative-syntax.php
260 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
<h3>Hi unknown user</h3>
<?php endif ; ?>
If you’d prefer using a templating language like Twig
113
, a subclass of View will bridge your templating language and
CakePHP.
Template files are stored in src/Template/, in a folder named after the controller that uses the files, and named after the action it corresponds to. For example, the view file for the Products controller’s “view()” action, would normally be found in src/Template/Products/view.ctp.
The view layer in CakePHP can be made up of a number of different parts. Each part has different uses, and will be covered in this chapter:
• views: Templates are the part of the page that is unique to the action being run. They form the meat of your application’s response.
• elements: small, reusable bits of view code. Elements are usually rendered inside views.
• layouts: template files that contain presentational code that wraps many interfaces in your application. Most views are rendered inside a layout.
• helpers: these classes encapsulate view logic that is needed in many places in the view layer. Among other things, helpers in CakePHP can help you build forms, build AJAX functionality, paginate model data, or serve
RSS feeds.
• cells: these classes provide miniature controller-like features for creating self contained UI components. See the
View Cells
documentation for more information.
View Variables
Any variables you set in your controller with set() will be available in both the view and the layout your action renders. In addition, any set variables will also be available in any element. If you need to pass additional variables from the view to the layout you can either call set() in the view template, or use a
Using View Blocks
You should remember to always escape any user data before outputting it as CakePHP does not automatically escape output. You can escape user content with the h() function:
<?= h( $user -> bio ); ?>
Setting View Variables
Cake\View\View::set( string $var , mixed $value)
Views have a set() method that is analogous to the set() found in Controller objects. Using set() from your view file will add the variables to the layout and elements that will be rendered later. See
Setting View Variables
for more information on using set().
In your view file you can do:
$this -> set ( 'activeMenuButton' , 'posts' );
Then, in your layout, the $activeMenuButton variable will be available and contain the value ‘posts’.
113 http://twig.sensiolabs.org
View Templates 261
CakePHP Cookbook Documentation, Release 3.5
Extending Views
View extending allows you to wrap one view in another. Combining this with
view blocks
gives you a powerful way to keep your views
DRY
. For example, your application has a sidebar that needs to change depending on the specific
view being rendered. By extending a common view file, you can avoid repeating the common markup for your sidebar, and only define the parts that change:
<!-- src/Template/Common/view.ctp -->
<h1> <?
= $this -> fetch ( 'title' ) ?> </h1>
<?
= $this -> fetch ( 'content' ) ?>
<div class="actions">
<h3>Related actions</h3>
<ul>
<?
= $this -> fetch ( 'sidebar' ) ?>
</ul>
</div>
The above view file could be used as a parent view. It expects that the view extending it will define the sidebar and title blocks. The content block is a special block that CakePHP creates. It will contain all the uncaptured content from the extending view. Assuming our view file has a $post variable with the data about our post, the view could look like:
<!-- src/Template/Posts/view.ctp -->
<?php
$this -> extend ( '/Common/view' );
$this -> assign ( 'title' , $post );
$this -> start ( 'sidebar' );
?>
<li>
<?php
echo
$this -> Html -> link ( 'edit' , [
'action' => 'edit' ,
$post -> id
]); ?>
</li>
<?php
$this -> end (); ?>
// The remaining content will be available as the 'content' block
// In the parent view.
<?
= h( $post -> body ) ?>
The post view above shows how you can extend a view, and populate a set of blocks. Any content not already in a defined block will be captured and put into a special block named content. When a view contains a call to extend()
, execution continues to the bottom of the current view file. Once it is complete, the extended view will be rendered. Calling extend() more than once in a view file will override the parent view that will be processed next:
$this -> extend ( '/Common/view' );
$this -> extend ( '/Common/index' );
The above will result in /Common/index.ctp being rendered as the parent view to the current view.
You can nest extended views as many times as necessary. Each view can extend another view if desired. Each parent view will get the previous view’s content as the content block.
262 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Note: You should avoid using content as a block name in your application. CakePHP uses this for uncaptured content in extended views.
You can get the list of all populated blocks using the blocks() method:
$list = $this -> blocks ();
Using View Blocks
View blocks provide a flexible API that allows you to define slots or blocks in your views/layouts that will be defined elsewhere. For example, blocks are ideal for implementing things such as sidebars, or regions to load assets at the bottom/top of the layout. Blocks can be defined in two ways: either as a capturing block, or by direct assignment.
The start(), append(), prepend(), assign(), fetch(), and end() methods allow you to work with capturing blocks:
// Create the sidebar block.
$this -> start ( 'sidebar' );
echo
$this -> element ( 'sidebar/recent_topics' );
echo
$this -> element ( 'sidebar/recent_comments' );
$this -> end ();
// Append into the sidebar later on.
$this -> start ( 'sidebar' );
echo
$this -> fetch ( 'sidebar' );
echo
$this -> element ( 'sidebar/popular_topics' );
$this -> end ();
You can also append into a block using append():
$this -> append ( 'sidebar' );
echo
$this -> element ( 'sidebar/popular_topics' );
$this -> end ();
// The same as the above.
$this -> append ( 'sidebar' , $this -> element ( 'sidebar/popular_topics' ));
If you need to clear or overwrite a block there are a couple of alternatives. The reset() method will clear or overwrite a block at any time. The assign() method with an empty content string can also be used to clear the specified block.:
// Clear the previous content from the sidebar block.
$this -> reset ( 'sidebar' );
// Assigning an empty string will also clear the sidebar block.
$this -> assign ( 'sidebar' , '' );
New in version 3.2: View::reset() was added in 3.2
Assigning a block’s content is often useful when you want to convert a view variable into a block. For example, you may want to use a block for the page title, and sometimes assign the title as a view variable in the controller:
// In view file or layout above $this->fetch('title')
$this -> assign ( 'title' , $title );
Using View Blocks 263
CakePHP Cookbook Documentation, Release 3.5
The prepend() method allows you to prepend content to an existing block:
// Prepend to sidebar
$this -> prepend ( 'sidebar' , 'this content goes on top of sidebar' );
Note: You should avoid using content as a block name. This is used by CakePHP internally for extended views, and view content in the layout.
Displaying Blocks
You can display blocks using the fetch() method. fetch() will output a block, returning ‘’ if a block does not exist:
<?= $this -> fetch ( 'sidebar' ) ?>
You can also use fetch to conditionally show content that should surround a block should it exist. This is helpful in layouts, or extended views where you want to conditionally show headings or other markup:
// In src/Template/Layout/default.ctp
<?php if ( $this -> fetch ( 'menu' )) : ?>
<div class="menu">
<h3>Menu options</h3>
<?
= $this -> fetch ( 'menu' ) ?>
</div>
<?php endif ; ?>
You can also provide a default value for a block if it does not exist. This allows you to add placeholder content when a block does not exist. You can provide a default value using the second argument:
<div class="shopping-cart">
<h3>Your Cart</h3>
<?
= $this -> fetch ( 'cart' , 'Your cart is empty' ) ?>
</div>
Using Blocks for Script and CSS Files
The HtmlHelper ties into view blocks, and its script(), css(), and meta() methods each update a block with the same name when used with the block = true option:
<?php
// In your view file
$this -> Html -> script ( 'carousel' , [ 'block' =>
true
]);
$this -> Html -> css ( 'carousel' , [ 'block' =>
true
]);
?>
// In your layout file.
<!DOCTYPE html>
<html lang="en">
<head>
<title> <?
= $this -> fetch ( 'title' ) ?> </title>
<?
= $this -> fetch ( 'script' ) ?>
<?
= $this -> fetch ( 'css' ) ?>
264 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
</head>
// Rest of the layout follows
The
Cake\View\Helper\HtmlHelper
also allows you to control which block the scripts and CSS go to:
// In your view
$this -> Html -> script ( 'carousel' , [ 'block' => 'scriptBottom' ]);
// In your layout
<?= $this -> fetch ( 'scriptBottom' ) ?>
Layouts
A layout contains presentation code that wraps around a view. Anything you want to see in all of your views should be placed in a layout.
CakePHP’s default layout is located at src/Template/Layout/default.ctp. If you want to change the overall look of your application, then this is the right place to start, because controller-rendered view code is placed inside of the default layout when the page is rendered.
Other layout files should be placed in src/Template/Layout.
When you create a layout, you need to tell
CakePHP where to place the output of your views.
To do so, make sure your layout includes a place for
$this->fetch('content')
Here’s an example of what a default layout might look like:
<!DOCTYPE html>
<html lang="en">
<head>
<title> <?
= h( $this -> fetch ( 'title' )) ?> </title>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<!-- Include external files and scripts here (See HTML helper for more info.) -->
<?php
echo
$this -> fetch ( 'meta' );
echo
$this -> fetch ( 'css' );
echo
$this -> fetch ( 'script' );
?>
</head>
<body>
<!-- If you'd like some sort of menu to show up on all of your views, include it here -->
<div id="header">
<div id="menu">...</div>
</div>
<!-- Here's where I want my views to be displayed -->
<?
= $this -> fetch ( 'content' ) ?>
<!-- Add a footer to each displayed page -->
<div id="footer">...</div>
</body>
</html>
The script, css and meta blocks contain any content defined in the views using the built-in HTML helper. Useful for including JavaScript and CSS files from views.
Layouts 265
CakePHP Cookbook Documentation, Release 3.5
Note: When using HtmlHelper::css() or HtmlHelper::script() in template files, specify 'block'
=> true to place the HTML source in a block with the same name. (See API for more details on usage).
The content block contains the contents of the rendered view.
You can set the title block content from inside your view file:
$this -> assign ( 'title' , 'View Active Users' );
You can create as many layouts as you wish: just place them in the src/Template/Layout directory, and switch between them inside of your controller actions using the controller or view’s $layout property:
// From a controller
public function
view ()
{
// Set the layout.
$this -> viewBuilder () -> setLayout ( 'admin' );
// Before 3.4
$this -> viewBuilder () -> layout ( 'admin' );
// Before 3.1
$this -> layout = 'admin' ;
}
// From a view file
$this -> layout = 'loggedin' ;
For example, if a section of my site included a smaller ad banner space, I might create a new layout with the smaller advertising space and specify it as the layout for all controllers’ actions using something like:
namespace
App\Controller;
class UsersController extends
AppController
{
public function
viewActive ()
{
$this -> set ( 'title' , 'View Active Users' );
$this -> viewBuilder () -> setLayout ( 'default_small_ad' );
}
public function
viewImage ()
{
$this -> viewBuilder () -> setLayout ( 'image' );
// Output user image
}
// or the following before 3.4
$this -> viewBuilder () -> layout ( 'default_small_ad' );
// or the following before 3.1
$this -> layout = 'default_small_ad' ;
}
Besides a default layout CakePHP’s official skeleton app also has an ‘ajax’ layout. The Ajax layout is handy for crafting AJAX responses - it’s an empty layout. (Most AJAX calls only require a bit of markup in return, rather than a
266 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
fully-rendered interface.)
The skeleton app also has a default layout to help generate RSS.
Using Layouts from Plugins
If you want to use a layout that exists in a plugin, you can use
plugin syntax
. For example, to use the contact layout
from the Contacts plugin:
namespace
App\Controller;
class UsersController extends
AppController
{
public function
view_active ()
{
$this -> viewBuilder () -> layout ( 'Contacts.contact' );
// or the following before 3.1
$this -> layout = 'Contacts.contact' ;
}
}
Elements
Cake\View\View::element( string $elementPath , array $data, array $options = [])
Many applications have small blocks of presentation code that need to be repeated from page to page, sometimes in different places in the layout. CakePHP can help you repeat parts of your website that need to be reused. These reusable parts are called Elements. Ads, help boxes, navigational controls, extra menus, login forms, and callouts are often implemented in CakePHP as elements. An element is basically a mini-view that can be included in other views, in layouts, and even within other elements. Elements can be used to make a view more readable, placing the rendering of repeating elements in its own file. They can also help you re-use content fragments in your application.
Elements live in the src/Template/Element/ folder, and have the .ctp filename extension. They are output using the element method of the view:
echo
$this -> element ( 'helpbox' );
Passing Variables into an Element
You can pass data to an element through the element’s second argument:
echo
$this -> element ( 'helpbox' , [
"helptext" => "Oh, this text is very helpful."
]);
Inside the element file, all the passed variables are available as members of the parameter array (in the same way that Controller::set() in the controller works with template files).
In the above example, the src/Template/Element/helpbox.ctp file can use the $helptext variable:
// Inside src/Template/Element/helpbox.ctp
echo
$helptext ; // Outputs "Oh, this text is very helpful."
Elements 267
CakePHP Cookbook Documentation, Release 3.5
The View::element() method also supports options for the element. The options supported are ‘cache’ and
‘callbacks’. An example:
echo
$this -> element ( 'helpbox' , [
"helptext" => "This is passed to the element as $helptext " ,
"foobar" => "This is passed to the element as $foobar " ,
],
[
// uses the "long_view" cache configuration
"cache" => "long_view" ,
// set to true to have before/afterRender called for the element
"callbacks" =>
true
]
);
Element caching is facilitated through the Cache class. You can configure elements to be stored in any Cache configuration you’ve set up. This gives you a great amount of flexibility to decide where and for how long elements are stored. To cache different versions of the same element in an application, provide a unique cache key value using the following format:
$this -> element ( 'helpbox' , [], [
"cache" => [ 'config' => 'short' , 'key' => 'unique value' ]
]
);
If you need more logic in your element, such as dynamic data from a datasource, consider using a View Cell instead of an element. Find out more
about View Cells
Caching Elements
You can take advantage of CakePHP view caching if you supply a cache parameter. If set to true, it will cache the element in the ‘default’ Cache configuration. Otherwise, you can set which cache configuration should be used. See
Caching
for more information on configuring Cache. A simple example of caching an element would be:
echo
$this -> element ( 'helpbox' , [], [ 'cache' =>
true
]);
If you render the same element more than once in a view and have caching enabled, be sure to set the ‘key’ parameter to a different name each time. This will prevent each successive call from overwriting the previous element() call’s cached result. For example:
echo
$this -> element (
'helpbox' ,
[ 'var' => $var ],
[ 'cache' => [ 'key' => 'first_use' , 'config' => 'view_long' ]]
);
echo
$this -> element (
'helpbox' ,
[ 'var' => $differenVar ],
[ 'cache' => [ 'key' => 'second_use' , 'config' => 'view_long' ]]
);
The above will ensure that both element results are cached separately. If you want all element caching to use the same cache configuration, you can avoid some repetition by setting View::$elementCache to the cache configuration you want to use. CakePHP will use this configuration when none is given.
268 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Requesting Elements from a Plugin
If you are using a plugin and wish to use elements from within the plugin, just use the familiar
plugin syntax
view is being rendered for a plugin controller/action, the plugin name will automatically be prefixed onto all elements used, unless another plugin name is present. If the element doesn’t exist in the plugin, it will look in the main APP folder:
echo
$this -> element ( 'Contacts.helpbox' );
If your view is a part of a plugin, you can omit the plugin name.
For example, if you are in the
ContactsController of the Contacts plugin, the following:
echo
$this -> element ( 'helpbox' );
// and
echo
$this -> element ( 'Contacts.helpbox' ); are equivalent and will result in the same element being rendered.
For elements inside subfolder of a plugin (e.g., plugins/Contacts/Template/Element/sidebar/helpbox.ctp), use the following:
echo
$this -> element ( 'Contacts.sidebar/helpbox' );
Requesting Elements from the App
If you are within a plugin’s template file and want to render an element residing in your main application rather than this or another plugin, use the following:
echo
$this -> element ( 'some_global_element' , [], [ 'plugin' =>
false
]);
// or...
echo
$this -> element ( 'some_global_element' , [ 'localVar' => $someData ], [ 'plugin' =>
˓→
false
]);
Routing prefix and Elements
New in version 3.0.1.
If you have a Routing prefix configured, the Element path resolution can switch to a prefix location, as Layouts and action View do. Assuming you have a prefix “Admin” configured and you call:
echo
$this -> element ( 'my_element' );
The element first be looked for in src/Template/Admin/Element/. If such a file does not exist, it will be looked for in the default location.
Caching Sections of Your View
Cake\View\View::cache( callable $block , array $options = [])
Sometimes generating a section of your view output can be expensive because of rendered
View Cells
or expensive helper operations. To help make your application run faster CakePHP provides a way to cache view sections:
Elements 269
CakePHP Cookbook Documentation, Release 3.5
// Assuming some local variables
echo
$this -> cache (
function
()
use
( $user , $article ) {
echo
$this -> cell ( 'UserProfile' , [ $user ]);
echo
$this -> cell ( 'ArticleFull' , [ $article ]);
}, [ 'key' => 'my_view_key' ]);
By default cached view content will go into the View::$elementCache cache config, but you can use the config option to change this.
View Events
Like Controller, view trigger several events/callbacks that you can use to insert logic around the rendering life-cycle:
Event List
• View.beforeRender
• View.beforeRenderFile
• View.afterRenderFile
• View.afterRender
• View.beforeLayout
• View.afterLayout
You can attach application
event listeners
to these events or use
Helper Callbacks
Creating Your Own View Classes
You may need to create custom view classes to enable new types of data views, or add additional custom viewrendering logic to your application. Like most components of CakePHP, view classes have a few conventions:
• View class files should be put in src/View. For example: src/View/PdfView.php
• View classes should be suffixed with View. For example: PdfView.
• When referencing view class names you should omit the
View suffix.
$this->viewBuilder()->className('Pdf');
.
You’ll also want to extend View to ensure things work correctly:
For example:
// In src/View/PdfView.php
namespace
App\View;
use
Cake\View\View;
class PdfView extends
View
{
public function
render ( $view =
null
, $layout =
null
)
{
// Custom logic here.
}
}
270 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Replacing the render method lets you take full control over how your content is rendered.
More About Views
View Cells
View cells are small mini-controllers that can invoke view logic and render out templates. The idea of cells is borrowed from cells in Ruby
114
, where they fulfill a similar role and purpose.
When to use Cells
Cells are ideal for building reusable page components that require interaction with models, view logic, and rendering logic. A simple example would be the cart in an online store, or a data-driven navigation menu in a CMS.
Creating a Cell
To create a cell, define a class in src/View/Cell and a template in src/Template/Cell/. In this example, we’ll be making a cell to display the number of messages in a user’s notification inbox. First, create the class file. Its contents should look like:
namespace
App\View\Cell;
use
Cake\View\Cell;
class InboxCell extends
Cell
{
public function
display ()
{
}
}
Save this file into src/View/Cell/InboxCell.php. As you can see, like other classes in CakePHP, Cells have a few conventions:
• Cells live in the App\View\Cell namespace. If you are making a cell in a plugin, the namespace would be
PluginName\View\Cell .
• Class names should end in Cell.
• Classes should inherit from Cake\View\Cell.
We added an empty display() method to our cell; this is the conventional default method when rendering a cell.
We’ll cover how to use other methods later in the docs. Now, create the file src/Template/Cell/Inbox/display.ctp.
This will be our template for our new cell.
You can generate this stub code quickly using bake: bin / cake bake cell Inbox
Would generate the code we typed out.
114 https://github.com/apotonick/cells
More About Views 271
CakePHP Cookbook Documentation, Release 3.5
Implementing the Cell
Assume that we are working on an application that allows users to send messages to each other. We have a Messages model, and we want to show the count of unread messages without having to pollute AppController. This is a perfect use case for a cell. In the class we just made, add the following:
namespace
App\View\Cell;
use
Cake\View\Cell;
class InboxCell extends
Cell
{
public function
display ()
{
$this -> loadModel ( 'Messages' );
$unread = $this -> Messages -> find ( 'unread' );
$this -> set ( 'unread_count' , $unread -> count ());
}
}
Because Cells use the ModelAwareTrait and ViewVarsTrait, they behave very much like a controller would.
We can use the loadModel() and set() methods just like we would in a controller. In our template file, add the following:
<!-src / Template / Cell / Inbox / display .
ctp -->
< div class = "notification-icon" >
You have <?= $unread_count ?> unread messages.
</div>
Note: Cell templates have an isolated scope that does not share the same View instance as the one used to render template and layout for the current controller action or other cells. Hence they are unaware of any helper calls made or blocks set in the action’s template / layout and vice versa.
Loading Cells
Cells can be loaded from views using the cell() method and works the same in both contexts:
// Load an application cell
$cell = $this -> cell ( 'Inbox' );
// Load a plugin cell
$cell = $this -> cell ( 'Messaging.Inbox' );
The above will load the named cell class and execute the display() method. You can execute other methods using the following:
// Run the expanded() method on the Inbox cell
$cell = $this -> cell ( 'Inbox::expanded' );
If you need controller logic to decide which cells to load in a request, you can use the CellTrait in your controller to enable the cell() method there:
272 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
namespace
App\Controller;
use
App\Controller\AppController;
use
Cake\View\CellTrait;
class DashboardsController extends
AppController
{
use
CellTrait;
// More code.
}
Passing Arguments to a Cell
You will often want to parameterize cell methods to make cells more flexible. By using the second and third arguments of cell(), you can pass action parameters and additional options to your cell classes, as an indexed array:
$cell = $this -> cell ( 'Inbox::recent' , [ '-3 days' ]);
The above would match the following function signature:
public function
recent ( $since )
{
}
Rendering a Cell
Once a cell has been loaded and executed, you’ll probably want to render it. The easiest way to render a cell is to echo it:
<?= $cell ?>
This will render the template matching the lowercased and underscored version of our action name, e.g. display.ctp.
Because cells use View to render templates, you can load additional cells within a cell template if required.
Note: Echoing a cell uses the PHP __toString() magic method which prevents PHP from showing the filename and line number for any fatal errors raised. To obtain a meanful error message, it is recommended to use the
Cell::render() method, for example <?= $cell->render() ?>.
Rendering Alternate Templates
By convention cells render templates that match the action they are executing. If you need to render a different view template, you can specify the template to use when rendering the cell:
// Calling render() explicitly
echo
$this -> cell ( 'Inbox::recent' , [ '-3 days' ]) -> render ( 'messages' );
// Set template before echoing the cell.
$cell = $this -> cell ( 'Inbox' );
More About Views 273
CakePHP Cookbook Documentation, Release 3.5
$cell -> template = 'messages' ;
echo
$cell ;
Caching Cell Output
When rendering a cell you may want to cache the rendered output if the contents don’t change often or to help improve performance of your application. You can define the cache option when creating a cell to enable & configure caching:
// Cache using the default config and a generated key
$cell = $this -> cell ( 'Inbox' , [], [ 'cache' =>
true
]);
// Cache to a specific cache config and a generated key
$cell = $this -> cell ( 'Inbox' , [], [ 'cache' => [ 'config' => 'cell_cache' ]]);
// Specify the key and config to use.
$cell = $this -> cell ( 'Inbox' , [], [
'cache' => [ 'config' => 'cell_cache' , 'key' => 'inbox_' .
$user -> id ]
]);
If a key is generated the underscored version of the cell class and template name will be used.
Note: A new View instance is used to render each cell and these new objects do not share context with the main template / layout. Each cell is self-contained and only has access to variables passed as arguments to the View::cell() call.
Paginating Data inside a Cell
Creating a cell that renders a paginated result set can be done by leveraging the Paginator class of the ORM. An example of paginating a user’s favorite messages could look like:
namespace
App\View\Cell;
use
Cake\View\Cell;
use
Cake\Datasource\Paginator;
class FavoritesCell extends
Cell
{
public function
display ( $user )
{
$this -> loadModel ( 'Messages' );
// Create a paginator
$paginator =
new
Paginator();
// Paginate the model
$results = $paginator -> paginate (
$this -> Messages ,
$this -> request -> getQueryParams (),
[
// Use a parameterized custom finder.
'finder' => [ 'favorites' => [ $user ]],
// Use scoped query string parameters.
274 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
'scope' => 'favorites' ,
]
);
$this -> set ( 'favorites' , $results );
}
}
The above cell would paginate the Messages model using
scoped pagination parameters
New in version 3.5.0: Cake\Datasource\Paginator was added in 3.5.0.
Themes
You can take advantage of themes, making it easy to switch the look and feel of your page quickly. Themes in
CakePHP are simply plugins that focus on providing template files. In addition to template files, they can also provide helpers and cells if your theming requires that. When using cells and helpers from your theme, you will need to continue using the
plugin syntax
To use themes, set the theme name in your controller’s action or beforeRender() callback:
class ExamplesController extends
AppController
{
// For CakePHP before 3.1
public
$theme = 'Modern' ;
public function
beforeRender (\Cake\Event\Event $event )
{
$this -> viewBuilder () -> theme ( 'Modern' );
}
}
Theme template files need to be within a plugin with the same name. For example, the above theme would be found in plugins/Modern/src/Template. It’s important to remember that CakePHP expects CamelCase plugin/theme names. Beyond that, the folder structure within the plugins/Modern/src/Template folder is exactly the same as src/Template/.
For example, the view file for an edit action of a Posts controller would reside at plugins/Modern/src/Template/Posts/edit.ctp. Layout files would reside in plugins/Modern/src/Template/Layout/. You can provide customized templates for plugins with a theme as well. If you had a plugin named ‘Cms’, that contained a TagsController, the Modern theme could provide plugins/Modern/src/Template/Plugin/Cms/Tags/edit.ctp to replace the edit template in the plugin.
If a view file can’t be found in the theme, CakePHP will try to locate the view file in the src/Template/ folder. This way, you can create master template files and simply override them on a case-by-case basis within your theme folder.
Theme Assets
Because themes are standard CakePHP plugins, they can include any necessary assets in their webroot directory. This allows for easy packaging and distribution of themes. Whilst in development, requests for theme assets will be handled by Cake\Routing\Dispatcher. To improve performance for production environments, it’s recommended that you
Improve Your Application’s Performance
All of CakePHP’s built-in helpers are aware of themes and will create the correct paths automatically. Like template files, if a file isn’t in the theme folder, it will default to the main webroot folder:
More About Views 275
CakePHP Cookbook Documentation, Release 3.5
// When in a theme with the name of 'purple_cupcake'
$this -> Html -> css ( 'main.css' );
// creates a path like
/ purple_cupcake / css / main .
css
// and links to plugins / PurpleCupcake / webroot / css / main .
css
JSON and XML views
The JsonView and XmlView let you create JSON and XML responses, and integrate with the
Cake\Controller\Component\RequestHandlerComponent
.
By enabling RequestHandlerComponent in your application, and enabling support for the json and or xml extensions, you can automatically leverage the new view classes. JsonView and XmlView will be referred to as data views for the rest of this page.
There are two ways you can generate data views. The first is by using the _serialize key, and the second is by creating normal template files.
Enabling Data Views in Your Application
Before you can use the data view classes, you’ll first need to load the
Cake\Controller\Component\RequestHandlerComponent in your controller:
public function
initialize ()
{
...
$this -> loadComponent ( 'RequestHandler' );
}
This can be done in your AppController and will enable automatic view class switching on content types. You can also set the component up with the viewClassMap setting, to map types to your custom classes and/or map other data types.
You can optionally enable the json and or xml extensions with
Routing File Extensions
. This will allow you to access
the JSON, XML or any other special format views by using a custom URL ending with the name of the response type as a file extension such as http://example.com/articles.json.
By default, when not enabling
Routing File Extensions
, the request the Accept header is used for selecting which
type of format should be rendered to the user. An example Accept format that is used to render JSON responses is application/json
.
Using Data Views with the Serialize Key
The _serialize key is a special view variable that indicates which other view variable(s) should be serialized when using a data view. This lets you skip defining template files for your controller actions if you don’t need to do any custom formatting before your data is converted into json/xml.
If you need to do any formatting or manipulation of your view variables before generating the response, you should use template files. The value of _serialize can be either a string or an array of view variables to serialize:
276 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
namespace
App\Controller;
class ArticlesController extends
AppController
{
public function
initialize ()
{
parent
:: initialize ();
$this -> loadComponent ( 'RequestHandler' );
}
public function
index ()
{
// Set the view vars that have to be serialized.
$this -> set ( 'articles' , $this -> paginate ());
// Specify which view vars JsonView should serialize.
$this -> set ( '_serialize' , [ 'articles' ]);
}
}
You can also define _serialize as an array of view variables to combine:
namespace
App\Controller;
class ArticlesController extends
AppController
{
public function
initialize ()
{
parent
:: initialize ();
$this -> loadComponent ( 'RequestHandler' );
}
public function
index ()
{
// Some code that created $articles and $comments
// Set the view vars that have to be serialized.
$this -> set ( compact ( 'articles' , 'comments' ));
// Specify which view vars JsonView should serialize.
$this -> set ( '_serialize' , [ 'articles' , 'comments' ]);
}
}
Defining _serialize as an array has the added benefit of automatically appending a top-level <response> element when using
XmlView
. If you use a string value for _serialize and XmlView, make sure that your view
variable has a single top-level element. Without a single top-level element the Xml will fail to generate.
New in version 3.1.0: In this version, the variable _serialize is automaticaly set to true to serialize all view variables instead of explicitly specifying them.
Using a Data View with Template Files
You should use template files if you need to do some manipulation of your view content before creating the final output. For example if we had articles, that had a field containing generated HTML, we would probably want to omit that from a JSON response. This is a situation where a view file would be useful:
More About Views 277
CakePHP Cookbook Documentation, Release 3.5
// Controller code
class ArticlesController extends
AppController
{
public function
index ()
{
$articles = $this -> paginate ( 'Articles' );
$this -> set ( compact ( 'articles' ));
}
}
// View code - src/Template/Articles/json/index.ctp
foreach
( $articles
as
& $article ) { unset ( $article -> generated_html );
}
echo
json_encode ( compact ( 'articles' ));
You can do more complex manipulations, or use helpers to do formatting as well. The data view classes don’t support layouts. They assume that the view file will output the serialized content.
Note: As of 3.1.0 AppController, in the application skeleton automatically adds '_serialize' => true to all
XML/JSON requests. You will need to remove this code from the beforeRender callback or set '_serialize' => false in your controller’s action if you want to use view files.
Creating XML Views
class XmlView
By default when using _serialize the XmlView will wrap your serialized view variables with a <response> node. You can set a custom name for this node using the _rootNode view variable.
The XmlView class supports the _xmlOptions variable that allows you to customize the options used to generate
XML, e.g. tags vs attributes.
Creating JSON Views
class JsonView
The JsonView class supports the _jsonOptions variable that allows you to customize the bit-mask used to generate
JSON. See the json_encode
115 documentation for the valid values of this option.
For example, to serialize validation error output of CakePHP entities in a consistent form of JSON do:
// In your controller's action when saving failed
$this -> set ( 'errors' , $articles -> errors ());
$this -> set ( '_jsonOptions' , JSON_FORCE_OBJECT);
$this -> set ( '_serialize' , [ 'errors' ]);
JSONP Responses
When using JsonView you can use the special view variable _jsonp to enable returning a JSONP response. Setting it to true makes the view class check if query string parameter named “callback” is set and if so wrap the json
115 http://php.net/json_encode
278 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
response in the function name provided. If you want to use a custom query string parameter name instead of “callback” set _jsonp to required name instead of true.
Example Usage
While the
RequestHandlerComponent
can automatically set the view based on the request content-type or extension, you could also handle view mappings in your controller:
// src/Controller/VideosController.php
namespace
App\Controller;
use
App\Controller\AppController;
use
Cake\Network\Exception\NotFoundException;
class VideosController extends
AppController
{
public function
export ( $format = '' )
{
$format = strtolower ( $format );
// Format to view mapping
$formats = [
];
'xml' => 'Xml' ,
'json' => 'Json' ,
// Error on unknown type
if
( !
isset ( $formats [ $format ])) {
throw new
NotFoundException(__( 'Unknown format.' ));
}
// Set Out Format View
$this -> viewBuilder () -> className ( $formats [ $format ]);
// Set Force Download
$this -> response -> download ( 'report-' .
date ( 'YmdHis' ) .
'.' .
$format );
// Get data
$videos = $this -> Videos -> find ( 'latest' );
// Set Data View
$this -> set ( compact ( 'videos' ));
$this -> set ( '_serialize' , [ 'videos' ]);
}
}
Helpers
Helpers are the component-like classes for the presentation layer of your application. They contain presentational logic that is shared between many views, elements, or layouts. This chapter will show you how to configure helpers.
How to load helpers and use those helpers, and outline the simple steps for creating your own custom helpers.
CakePHP includes a number of helpers that aid in view creation. They assist in creating well-formed markup (including forms), aid in formatting text, times and numbers, and can even speed up AJAX functionality. For more information on the helpers included in CakePHP, check out the chapter for each helper:
More About Views 279
CakePHP Cookbook Documentation, Release 3.5
Breadcrumbs
class Cake\View\Helper\BreadcrumbsHelper(View $view, array $config = [])
New in version 3.3.6.
BreadcrumbsHelper provides a way to easily deal with the creation and rendering of a breadcrumbs trail for your app.
Creating a Breadcrumbs Trail
You can add a crumb to the list using the add() method. It takes three arguments:
• title The string to be displayed as a the title of the crumb
• url A string or an array of parameters that will be given to the
Url
• options An array of attributes for the item and itemWithoutLink templates. See the section about
defining attributes for the item
for more informations.
In addition to adding to the end of the trail, you can do a variety of operations:
// Add at the end of the trail
$this -> Breadcrumbs -> add (
'Products' ,
[ 'controller' => 'products' , 'action' => 'index' ]
);
// Add multiple crumbs at the end of the trail
$this -> Breadcrumbs -> add ([
[ 'title' => 'Products' , 'url' => [ 'controller' => 'products' , 'action' => 'index
˓→
' ]],
[ 'title' => 'Product name' , 'url' => [ 'controller' => 'products' , 'action' =>
˓→
'view' , 1234 ]]
]);
// Prepended crumbs will be put at the top of the list
$this -> Breadcrumbs -> prepend (
'Products' ,
[ 'controller' => 'products' , 'action' => 'index' ]
);
// Prepend multiple crumbs at the top of the trail, in the order given
$this -> Breadcrumbs -> prepend ([
[ 'title' => 'Products' , 'url' => [ 'controller' => 'products' , 'action' => 'index
˓→
' ]],
[ 'title' => 'Product name' , 'url' => [ 'controller' => 'products' , 'action' =>
˓→
'view' , 1234 ]]
]);
// Insert in a specific slot. If the slot is out of
// bounds, an exception will be raised.
$this -> Breadcrumbs -> insertAt (
2 ,
'Products' ,
[ 'controller' => 'products' , 'action' => 'index' ]
);
// Insert before another crumb, based on the title.
// If the named crumb title cannot be found,
280 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
// an exception will be raised.
$this -> Breadcrumbs -> insertBefore (
'A product name' , // the title of the crumb to insert before
'Products' ,
[ 'controller' => 'products' , 'action' => 'index' ]
);
// Insert after another crumb, based on the title.
// If the named crumb title cannot be found,
// an exception will be raised.
$this -> Breadcrumbs -> insertAfter (
'A product name' , // the title of the crumb to insert after
'Products' ,
[ 'controller' => 'products' , 'action' => 'index' ]
);
Using these methods gives you the ability to work with CakePHP’s 2-step rendering process. Since templates and layouts are rendered from the inside out (meaning, included elements are rendered first), this allows you to define precisely where you want to add a breadcrumb.
Rendering the Breadcrumbs Trail
After adding crumbs to the trail, you can easily render it using the render() method. This method accepts two array arguments:
• $attributes : An array of attributes that will applied to the wrapper template. This gives you the ability to add attributes to the HTML tag. It accepts the special templateVars key to allow the insertion of custom template variables in the template.
• $separator : An array of attributes for the separator template. Possible properties are:
– separator The string to be displayed as a separator
– innerAttrs To provide attributes in case your separator is divided in two elements
– templateVars Allows the insertion of custom template variable in the template
All other properties will be converted as HTML attributes and will replace the attrs key in the template. If you use the default for this option (empty), it will not render a separator.
Here is an example of how to render a trail:
echo
$this -> Breadcrumbs -> render (
[ 'class' => 'breadcrumbs-trail' ],
[ 'separator' => '<i class="fa fa-angle-right"></i>' ]
);
Customizing the Output
The BreadcrumbsHelper internally uses the StringTemplateTrait, which gives the ability to easily customize output of various HTML strings. It includes four templates, with the following default declaration:
[
'wrapper' => '<ul{{attrs}}>{{content}}</ul>' ,
'item' => '<li{{attrs}}><a href="{{url}}"{{innerAttrs}}>{{title}}</a></li>{
˓→
{separator}}' ,
'itemWithoutLink' => '<li{{attrs}}><span{{innerAttrs}}>{{title}}</span></li>{
˓→
{separator}}' ,
More About Views 281
CakePHP Cookbook Documentation, Release 3.5
'separator' => '<li{{attrs}}><span{{innerAttrs}}>{{custom}}{{separator}}</span></
]
˓→ li>'
You can easily customize them using the templates() method from the StringTemplateTrait:
$this -> Breadcrumbs -> templates ([
'wrapper' => '<nav class="breadcrumbs"><ul{{attrs}}>{{content}}</ul></nav>' ,
]);
Since your templates will be rendered, the templateVars option allows you to add your own template variables in the various templates:
$this -> Breadcrumbs -> templates ([
'item' => '<li{{attrs}}>{{icon}}<a href="{{url}}"{{innerAttrs}}>{{title}}</a></li>
˓→
{{separator}}'
]);
And to define the {{icon}} parameter, just specify it when adding the crumb to the trail:
$this -> Breadcrumbs -> add (
'Products' ,
[ 'controller' => 'products' , 'action' => 'index' ],
[
'templateVars' => [
'icon' => '<i class="fa fa-money"></i>'
]
]
);
Defining Attributes for the Item
If you want to apply specific HTML attributes to both the item and its sub-item , you can leverage the innerAttrs key, which the $options argument provides. Everything except innerAttrs and templateVars will be rendered as HTML attributes:
$this -> Breadcrumbs -> add (
'Products' ,
[ 'controller' => 'products' , 'action' => 'index' ],
[
'class' => 'products-crumb' ,
'data-foo' => 'bar' ,
'innerAttrs' => [
'class' => 'inner-products-crumb' ,
'id' => 'the-products-crumb'
]
]
);
// Based on the default template, this will render the following HTML :
< li class = "products-crumb" data foo = "bar" >
< a href = "/products/index" class = "inner-products-crumb" id = "the-products-crumb" >
˓→
Products </ a >
</ li >
282 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Clearing the Breadcrumbs
You can clear the bread crumbs using the reset() method. This can be useful when you want to transform the crumbs and overwrite the list:
$crumbs = $this -> Breadcrumbs -> getCrumbs ();
$crumbs = collection( $crumbs ) -> map (
function
( $crumb ) {
$crumb [ 'options' ][ 'class' ] = 'breadcrumb-item' ;
return
$crumb ;
}) -> toArray ();
$this -> Breadcrumbs -> reset () -> add ( $crumbs );
New in version 3.4.0: The reset() method was added in 3.4.0
Flash
class Cake\View\Helper\FlashHelper(View $view, array $config = [])
FlashHelper provides a way to render flash messages that were set in $_SESSION by
FlashComponent
Flash-
Component
and FlashHelper primarily use elements to render flash messages. Flash elements are found under the src/Template/Element/Flash directory. You’ll notice that CakePHP’s App template comes with three flash elements: success.ctp, default.ctp, and error.ctp.
Rendering Flash Messages
To render a flash message, you can simply use FlashHelper’s render() method:
<?= $this -> Flash -> render () ?>
By default, CakePHP uses a “flash” key for flash messages in a session. But, if you’ve specified a key when setting the flash message in
FlashComponent
, you can specify which flash key to render:
<?= $this -> Flash -> render ( 'other' ) ?>
You can also override any of the options that were set in FlashComponent:
// In your Controller
$this -> Flash -> set ( 'The user has been saved.' , [
'element' => 'success'
]);
// In your View: Will use great_success.ctp instead of succcess.ctp
<?= $this -> Flash -> render ( 'flash' , [
'element' => 'great_success'
]);
Note: When building custom flash message templates, be sure to properly HTML encode any user data. CakePHP won’t escape flash message parameters for you.
New in version 3.1: The
FlashComponent
now stacks messages. If you set multiple flash messages, when you call render()
, each message will be rendered in its own elements, in the order they were set.
For more information about the available array options, please refer to the
FlashComponent
section.
More About Views 283
CakePHP Cookbook Documentation, Release 3.5
Routing Prefix and Flash Messages
New in version 3.0.1.
If you have a Routing prefix configured, you can now have your Flash elements stored in src/Template/{Prefix}/Element/Flash.
This way, you can have specific messages layouts for each part of your application. For instance, using different layouts for your front-end and admin section.
Flash Messages and Themes
The FlashHelper uses normal elements to render the messages and will therefore obey any theme you might have specified. So when your theme has a src/Template/Element/Flash/error.ctp file it will be used, just as with any
Elements and Views.
Form
class Cake\View\Helper\FormHelper(View $view, array $config = [])
The FormHelper does most of the heavy lifting in form creation. The FormHelper focuses on creating forms quickly, in a way that will streamline validation, re-population and layout. The FormHelper is also flexible - it will do almost everything for you using conventions, or you can use specific methods to get only what you need.
Starting a Form
Cake\View\Helper\FormHelper::create( mixed $context = null
, array $options = [])
• $context - The context for which the form is being defined. Can be an ORM entity, ORM resultset, array of metadata or false/null (to make a model-less form).
• $options - An array of options and/or HTML attributes.
The first method you’ll need to use in order to take advantage of the FormHelper is create(). This method outputs an opening form tag.
All parameters are optional. If create() is called with no parameters supplied, it assumes you are building a form that submits to the current controller, via the current URL. The default method for form submission is POST. If you were to call create() inside the view for UsersController::add(), you would see something like the following output in the rendered view:
<
form
method = "post" action = "/users/add" >
The $context argument is used as the form’s ‘context’. There are several built-in form contexts and you can add your own, which we’ll cover below, in a following section. The built-in providers map to the following values of
$context
:
• An Entity instance or an iterator will map to EntityContext
116
; this context class allows FormHelper to work
with results from the built-in ORM.
• An array containing the 'schema' key, will map to ArrayContext
117 structures to build forms against.
which allows you to create simple data
• null and false will map to NullContext
118
; this context class simply satisfies the interface FormHelper
requires. This context is useful if you want to build a short form that doesn’t require ORM persistence.
116
117
118 https://api.cakephp.org/3.x/class-Cake.View.Form.EntityContext.html
https://api.cakephp.org/3.x/class-Cake.View.Form.ArrayContext.html
https://api.cakephp.org/3.x/class-Cake.View.Form.NullContext.html
284 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
All context classes also have access to the request data, making it simpler to build forms.
Once a form has been created with a context, all controls you create will use the active context. In the case of an ORM backed form, FormHelper can access associated data, validation errors and schema metadata. You can close the active context using the end() method, or by calling create() again.
To create a form for an entity, do the following:
// If you are on /articles/add
// $article should be an empty Article entity.
echo
$this -> Form -> create ( $article );
Output:
<
form
method = "post" action = "/articles/add" >
This will POST the form data to the add() action of ArticlesController. However, you can also use the same logic to create an edit form. The FormHelper uses the Entity object to automatically detect whether to create an add or edit form. If the provided entity is not ‘new’, the form will be created as an edit form.
For example, if we browse to http://example.org/articles/edit/5, we could do the following:
// src/Controller/ArticlesController.php:
public function
edit ( $id =
null
)
{
if
(
empty
( $id )) {
throw new
NotFoundException;
}
$article = $this -> Articles -> get ( $id );
// Save logic goes here
$this -> set ( 'article' , $article );
}
// View/Articles/edit.ctp:
// Since $article->isNew() is false, we will get an edit form
<?= $this -> Form -> create ( $article ) ?>
Output:
<
form
method = "post" action = "/articles/edit/5" >
<
input
type = "hidden" name = "_method" value = "PUT" />
Note: Since this is an edit form, a hidden input field is generated to override the default HTTP method.
Options for Form Creation
The $options array is where most of the form configuration happens. This special array can contain a number of different key-value pairs that affect the way the form tag is generated. Valid values:
• 'type' - Allows you to choose the type of form to create. If no type is provided then it will be autodetected based on the form context. Valid values:
– 'get' - Will set the form method to HTTP GET.
– 'file' - Will set the form method to POST and the 'enctype' to “multipart/form-data”.
– 'post' - Will set the method to POST.
More About Views 285
CakePHP Cookbook Documentation, Release 3.5
– 'put','delete','patch' - Will override the HTTP method with PUT, DELETE or PATCH respectively, when the form is submitted.
• 'method' - Valid values are the same as above. Allows you to explicitly override the form’s method.
• 'url' - Specify the URL the form will submit to. Can be a string or a URL array.
• 'encoding' Sets the accept-charset encoding for the form.
Configure::read('App.encoding')
.
Defaults to
• 'enctype' - Allows you to set the form encoding explicitly.
• 'templates' - The templates you want to use for this form. Any templates provided will be merged on top of the already loaded templates. Can be either a filename (without extension) from /config or an array of templates to use.
• 'context' - Additional options for the form context class. (For example the EntityContext accepts a
'table' option that allows you to set the specific Table class the form should be based on.)
• 'idPrefix' - Prefix for generated ID attributes.
• 'templateVars' - Allows you to provide template variables for the formStart template.
Tip: Besides the above options you can provide, in the $options argument, any valid HTML attributes that you want to pass to the created form element.
Getting form values from the query string
New in version 3.4.0.
A FormHelper’s values sources define where its rendered elements, such as input-tags, receive their values from.
By default FormHelper draws its values from the ‘context’. The default contexts, such as EntityContext, will fetch data from the current entity, or from $request->getData().
If however, you are building a form that needs to read from the query string, you can use valueSource() to change where FormHelper reads data input data from:
// Prioritize query string over context:
echo
$this -> Form -> create ( $article , [
'valueSources' => [ 'query' , 'context' ]
]);
// Same effect:
echo
$this -> Form
-> setValueSources ([ 'query' , 'context' ])
-> create ( $articles );
// Only read data from the query string
echo
$this -> Form -> create ( $article );
$this -> Form -> setValueSources ( 'query' );
// Same effect:
echo
$this -> Form -> create ( $article , [ 'valueSources' => 'query' ]);
The supported sources are context, data and query. You can use one or more sources. Any widgets generated by FormHelper will gather their values from the sources, in the order you setup.
The value sources will be reset to the default (['context']) when end() is called.
286 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Changing the HTTP Method for a Form
By using the type option you can change the HTTP method a form will use:
echo
$this -> Form -> create ( $article , [ 'type' => 'get' ]);
Output:
<
form
method = "get" action = "/articles/edit/5" >
Specifying a 'file' value for type, changes the form submission method to ‘post’, and includes an enctype of
“multipart/form-data” on the form tag. This is to be used if there are any file elements inside the form. The absence of the proper enctype attribute will cause the file uploads not to function.
E.g.
echo
$this -> Form -> create ( $article , [ 'type' => 'file' ]);
Output:
<
form
enctype = "multipart/form-data" method = "post" action = "/articles/add" >
When using 'put', 'patch' or 'delete' as 'type' values, your form will be functionally equivalent to a
‘post’ form, but when submitted, the HTTP request method will be overridden with ‘PUT’, ‘PATCH’ or ‘DELETE’, respectively. This allows CakePHP to emulate proper REST support in web browsers.
Setting a URL for the Form
Using the 'url' option allows you to point the form to a specific action in your current controller or another controller in your application.
For example, if you’d like to point the form to the login() action of the current controller, you would supply an
$options array, like the following:
echo
$this -> Form -> create ( $article , [ 'url' => [ 'action' => 'login' ]]);
Output:
<
form
method = "post" action = "/users/login" >
If the desired form action isn’t in the current controller, you can specify a complete URL for the form action. The supplied URL can be relative to your CakePHP application:
echo
$this -> Form -> create (
null
, [
'url' => [ 'controller' => 'Articles' , 'action' => 'publish' ]
]);
Output:
<
form
method = "post" action = "/articles/publish" >
Or you can point to an external domain:
echo
$this -> Form -> create (
null
, [
'url' => 'http://www.google.com/search' ,
'type' => 'get'
]);
More About Views 287
CakePHP Cookbook Documentation, Release 3.5
Output:
<
form
method = "get" action = "http://www.google.com/search" >
Use 'url' => false if you don’t want to output a URL as the form action.
Using Custom Validators
Often models will have multiple validation sets, and you will want FormHelper to mark fields required based on a the specific validation rules your controller action is going to apply. For example, your Users table has specific validation rules that only apply when an account is being registered:
echo
$this -> Form -> create ( $user , [
'context' => [ 'validator' => 'register' ]
]);
The above will use the rules defined in the register validator, which are defined by
UsersTable::validationRegister()
, for $user and all related associations.
If you are creating a form for associated entities, you can define validation rules for each association by using an array:
echo
$this -> Form -> create ( $user , [
'context' => [
'validator' => [
'Users' => 'register' ,
'Comments' => 'default'
]
]
]);
The above would use register for the user, and default for the user’s comments.
Creating context classes
While the built-in context classes are intended to cover the basic cases you’ll encounter you may need to build a new context class if you are using a different ORM. In these situations you need to implement the
Cake\View\Form\ContextInterface
119
. Once you have implemented this interface you can wire your new context into the FormHelper. It is often best to do this in a View.beforeRender event listener, or in an application view class:
$this -> Form -> addContextProvider ( 'myprovider' ,
function
( $request , $data ) {
if
( $data [ 'entity' ] instanceof MyOrmClass) {
return new
MyProvider( $request , $data );
}
});
Context factory functions are where you can add logic for checking the form options for the correct type of entity. If matching input data is found you can return an object. If there is no match return null.
Creating Form Controls
Cake\View\Helper\FormHelper::control( string $fieldName , array $options = [])
119 https://api.cakephp.org/3.x/class-Cake.View.Form.ContextInterface.html
288 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
• $fieldName - A field name in the form 'Modelname.fieldname'.
• $options - An optional array that can include both
Options for Control
, and options of the other methods
(which control() employs internally to generate various HTML elements) as well as any valid HTML attributes.
The control() method lets you to generate complete form controls. These controls will include a wrapping div, label
, control widget, and validation error if necessary. By using the metadata in the form context, this method will choose an appropriate control type for each field. Internally control() uses the other methods of FormHelper.
Tip: Please note that while the fields generated by the control() method are called generically “inputs” on this page, technically speaking, the control() method can generate not only all of the HTML input type elements, but also other HTML form elements (e.g. select, button, textarea).
By default the control() method will employ the following widget templates:
'inputContainer' => '<div class="input {{type}}{{required}}">{{content}}</div>'
'input' => '<input type="{{type}}" name="{{name}}"{{attrs}}/>'
In case of validation errors it will also use:
'inputContainerError' => '<div class="input {{type}}{{required}} error">{{content}}{
˓→
{error}}</div>'
The type of control created (when we provide no additional options to specify the generated element type) is inferred via model introspection and depends on the column datatype:
Column Type Resulting Form Field string, uuid (char, varchar, etc.) text boolean, tinyint(1) checkbox decimal number float number integer number text textarea text, with name of password, passwd password text, with name of email email text, with name of tel, telephone, or phone tel date day, month, and year selects datetime, timestamp day, month, year, hour, minute, and meridian selects time hour, minute, and meridian selects binary file
The $options parameter allows you to choose a specific control type if you need to:
echo
$this -> Form -> control ( 'published' , [ 'type' => 'checkbox' ]);
Tip: As a small subtlety, generating specific elements via the control() form method will always also generate the wrapping div, by default. Generating the same type of element via one of the specific form methods (e.g.
More About Views 289
CakePHP Cookbook Documentation, Release 3.5
$this->Form->checkbox('published');
) in most cases won’t generate the wrapping div. Depending on your needs you can use one or another.
The wrapping div will have a required class name appended if the validation rules for the model’s field indicate that it is required and not allowed to be empty. You can disable automatic required flagging using the
'required' option:
echo
$this -> Form -> control ( 'title' , [ 'required' =>
false
]);
To skip browser validation triggering for the whole form you can set option 'formnovalidate' => true for the input button you generate using
View\Helper\FormHelper::submit()
or set 'novalidate' => true in options for
View\Helper\FormHelper::create()
For example, let’s assume that your Users model includes fields for a username (varchar), password (varchar), approved (datetime) and quote (text). You can use the control() method of the FormHelper to create appropriate controls for all of these form fields:
echo
$this -> Form -> create ( $user );
// The following generates a Text input
echo
$this -> Form -> control ( 'username' );
// The following generates a Password input
echo
$this -> Form -> control ( 'password' );
// Assuming 'approved' is a datetime or timestamp field the following
//generates: Day, Month, Year, Hour, Minute
echo
$this -> Form -> control ( 'approved' );
// The following generates a Textarea element
echo
$this -> Form -> control ( 'quote' );
echo
$this -> Form -> button ( 'Add' );
echo
$this -> Form -> end ();
A more extensive example showing some options for a date field:
echo
$this -> Form -> control ( 'birth_dt' , [
'label' => 'Date of birth' ,
'minYear' => date ( 'Y' ) 70 ,
'maxYear' => date ( 'Y' ) 18 ,
]);
Besides the specific
Options for Control
, you also can specify any option accepted by corresponding specific method
for the chosen (or inferred by CakePHP) control type and any HTML attribute (for instance onfocus).
If you want to create a select form field while using a belongsTo (or hasOne) relation, you can add the following to your UsersController (assuming your User belongsTo Group):
$this -> set ( 'groups' , $this -> Users -> Groups -> find ( 'list' ));
Afterwards, add the following to your view template:
echo
$this -> Form -> control ( 'group_id' , [ 'options' => $groups ]);
To make a select box for a belongsToMany Groups association you can add the following to your UsersController:
$this -> set ( 'groups' , $this -> Users -> Groups -> find ( 'list' ));
Afterwards, add the following to your view template:
290 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
echo
$this -> Form -> control ( 'groups._ids' , [ 'options' => $groups ]);
If your model name consists of two or more words (e.g. “UserGroups”), when passing the data using set() you should name your data in a pluralised and lower camelCased
120 format as follows:
$this -> set ( 'userGroups' , $this -> UserGroups -> find ( 'list' ));
Note: You should not use
FormHelper::control() to generate submit buttons.
View\Helper\FormHelper::submit()
instead.
Use
Field Naming Conventions
When creating control widgets you should name your fields after the matching attributes in the form’s entity. For example, if you created a form for an $article entity, you would create fields named after the properties. E.g.
title , body and published.
You can create controls for associated models, or arbitrary models by passing in association.fieldname as the first parameter:
echo
$this -> Form -> control ( 'association.fieldname' );
Any dots in your field names will be converted into nested request data. For example, if you created a field with a name 0.comments.body you would get a name attribute that looks like 0[comments][body]. This convention makes it easy to save data with the ORM. Details for the various association types can be found in the
Creating Inputs for Associated Data
section.
When creating datetime related controls, FormHelper will append a field-suffix. You may notice additional fields named year, month, day, hour, minute, or meridian being added. These fields will be automatically converted into DateTime objects when entities are marshalled.
Options for Control
FormHelper::control() supports a large number of options via its $options argument.
In addition to its own options, control() accepts options for the inferred/chosen generated control types (e.g.
for checkbox or textarea), as well as HTML attributes.
This subsection will cover the options specific to
FormHelper::control()
.
• $options['type'] - A string that specifies the widget type to be generated. In addition to the field types found in the
Creating Form Controls
, you can also create 'file', 'password', and any other type supported
by HTML5. By specifying a 'type' you will force the type of the generated control, overriding model introspection. Defaults to null.
E.g.
echo
$this -> Form -> control ( 'field' , [ 'type' => 'file' ]);
echo
$this -> Form -> control ( 'email' , [ 'type' => 'email' ]);
Output:
120 https://en.wikipedia.org/wiki/Camel_case#Variations_and_synonyms
More About Views 291
CakePHP Cookbook Documentation, Release 3.5
<
div
class = "input file" >
<
label
for = "field" >Field</
label
>
<
input
type = "file" name = "field" value = "" id = "field" />
</
div
>
<
div
class = "input email" >
<
label
for = "email" >Email</
label
>
<
input
type = "email" name = "email" value = "" id = "email" />
</
div
>
• $options['label'] - Either a string caption or an array of
options for the label
the string you would like to be displayed within the label that usually accompanies the input HTML element.
Defaults to null.
E.g.
echo
$this -> Form -> control ( 'name' , [
'label' => 'The User Alias'
]);
Output:
<
div
class = "input" >
<
label
for = "name" >The User Alias</
label
>
<
input
name = "name" type = "text" value = "" id = "name" />
</
div
>
Alternatively, set this key to false to disable the generation of the label element.
E.g.
echo
$this -> Form -> control ( 'name' , [ 'label' =>
false
]);
Output:
<
div
class = "input" >
<
input
name = "name" type = "text" value = "" id = "name" />
</
div
>
Set this to an array to provide additional options for the label element. If you do this, you can use a 'text' key in the array to customize the label text.
E.g.
echo
$this -> Form -> control ( 'name' , [
'label' => [
'class' => 'thingy' ,
'text' => 'The User Alias'
]
]);
Output:
<
div
class = "input" >
<
label
for = "name" class = "thingy" >The User Alias</
label
>
<
input
name = "name" type = "text" value = "" id = "name" />
</
div
>
292 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
• $options['options'] - You can provide in here an array containing the elements to be generated for widgets such as radio or select, which require an array of items as an argument (see
Creating Radio
Buttons
and
Creating Select Pickers
for more details). Defaults to null.
• $options['error'] - Using this key allows you to override the default model error messages and can be used, for example, to set i18n messages. To disable the error message output & field classes set the 'error' key to false. Defaults to null.
E.g.
echo
$this -> Form -> control ( 'name' , [ 'error' =>
false
]);
To override the model error messages use an array with the keys matching the original validation error messages.
E.g.
$this -> Form -> control ( 'name' , [
'error' => [ 'Not long enough' => __( 'This is not long enough' )]
]);
As seen above you can set the error message for each validation rule you have in your models. In addition you can provide i18n messages for your forms.
• $options['nestedInput'] - Used with checkboxes and radio buttons. Controls whether the input element is generated inside or outside the label element. When control() generates a checkbox or a radio button, you can set this to false to force the generation of the HTML input element outside of the label element.
On the other hand you can set this to true for any control type to force the generated input element inside the label. If you change this for radio buttons then you need to also modify the default
radioWrapper
template.
Depending on the generated control type it defaults to true or false.
• $options['templates'] - The templates you want to use for this input. Any specified templates will be merged on top of the already loaded templates. This option can be either a filename (without extension) in
/config that contains the templates you want to load, or an array of templates to use.
• $options['labelOptions'] - Set this to false to disable labels around nestedWidgets or set it to an array of attributes to be provided to the label tag.
Generating Specific Types of Controls
In addition to the generic control() method, FormHelper has specific methods for generating a number of different types of controls. These can be used to generate just the control widget itself, and combined with other methods like
View\Helper\FormHelper::label()
and
View\Helper\FormHelper::error()
to generate fully custom form layouts.
Common Options For Specific Controls
Many of the various control element methods support a common set of options which, depending on the form method used, must be provided inside the $options or in the $attributes array argument. All of these options are also supported by the control() method. To reduce repetition, the common options shared by all control methods are as follows:
• 'id' - Set this key to force the value of the DOM id for the control. This will override the 'idPrefix' that may be set.
More About Views 293
CakePHP Cookbook Documentation, Release 3.5
• 'default' - Used to set a default value for the control field. The value is used if the data passed to the form does not contain a value for the field (or if no data is passed at all). An explicit default value will override any default values defined in the schema.
Example usage:
echo
$this -> Form -> text ( 'ingredient' , [ 'default' => 'Sugar' ]);
Example with select field (size “Medium” will be selected as default):
$sizes = [ 's' => 'Small' , 'm' => 'Medium' , 'l' => 'Large' ];
echo
$this -> Form -> select ( 'size' , $sizes , [ 'default' => 'm' ]);
Note: You cannot use default to check a checkbox - instead you might set the value in
$this->request->getData() in your controller, or set the control option 'checked' to true.
Beware of using false to assign a default value. A false value is used to disable/exclude options of a control field, so 'default' => false would not set any value at all. Instead use 'default' => 0.
• 'value' - Used to set a specific value for the control field. This will override any value that may else be injected from the context, such as Form, Entity or request->getData() etc.
Note: If you want to set a field to not render its value fetched from context or valuesSource you will need to set 'value' to '' (instead of setting it to null).
In addition to the above options, you can mixin any HTML attribute you wish to use. Any non-special option name will be treated as an HTML attribute, and applied to the generated HTML control element.
Changed in version 3.3.0: As of 3.3.0, FormHelper will automatically use any default values defined in your database schema. You can disable this behavior by setting the schemaDefault option to false.
Creating Input Elements
The rest of the methods available in the FormHelper are for creating specific form elements. Many of these methods also make use of a special $options or $attributes parameter. In this case, however, this parameter is used primarily to specify HTML tag attributes (such as the value or DOM id of an element in the form).
Creating Text Inputs
Cake\View\Helper\FormHelper::text( string $name , array $options)
• $name - A field name in the form 'Modelname.fieldname'.
• $options - An optional array including any of the
Common Options For Specific Controls
as well as any valid
HTML attributes.
Creates a simple input HTML element of text type.
E.g.
echo
$this -> Form -> text ( 'username' , [ 'class' => 'users' ]);
Will output:
294 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
<
input
name = "username" type = "text" class = "users" >
Creating Password Inputs
Cake\View\Helper\FormHelper::password( string $fieldName , array $options)
• $fieldName - A field name in the form 'Modelname.fieldname'.
• $options - An optional array including any of the
Common Options For Specific Controls
as well as any valid
HTML attributes.
Creates a simple input element of password type.
E.g.
echo
$this -> Form -> password ( 'password' );
Will output:
<
input
name = "password" value = "" type = "password" >
Creating Hidden Inputs
Cake\View\Helper\FormHelper::hidden( string $fieldName , array $options)
• $fieldName - A field name in the form 'Modelname.fieldname'.
• $options - An optional array including any of the
Common Options For Specific Controls
as well as any valid
HTML attributes.
Creates a hidden form input.
E.g.
echo
$this -> Form -> hidden ( 'id' );
Will output:
<
input
name = "id" type = "hidden" />
Creating Textareas
Cake\View\Helper\FormHelper::textarea( string $fieldName
, array $options)
• $fieldName - A field name in the form 'Modelname.fieldname'.
• $options - An optional array including any of the
Common Options For Specific Controls
textarea options (see below) as well as any valid HTML attributes.
Creates a textarea control field. The default widget template used is:
'textarea' => '<textarea name="{{name}}"{{attrs}}>{{value}}</textarea>'
For example:
More About Views 295
CakePHP Cookbook Documentation, Release 3.5
echo
$this -> Form -> textarea ( 'notes' );
Will output:
<
textarea
name = "notes" ></
textarea
>
If the form is being edited (i.e. the array $this->request->getData() contains the information previously saved for the User entity), the value corresponding to notes field will automatically be added to the HTML generated.
Example:
<
textarea
name = "notes" id = "notes" >
This text is to be edited.
</
textarea
>
Options for Textarea
In addition to the
Common Options For Specific Controls
, textarea() supports a couple of specific options:
• 'escape' - Determines whether or not the contents of the textarea should be escaped. Defaults to true.
E.g.
echo
$this -> Form -> textarea ( 'notes' , [ 'escape' =>
false
]);
// OR....
echo
$this -> Form -> control ( 'notes' , [ 'type' => 'textarea' , 'escape' =>
false
]);
• 'rows','cols' - You can use these two keys to set the HTML attributes which specify the number of rows and columns for the textarea field.
E.g.
echo
$this -> Form -> textarea ( 'comment' , [ 'rows' => '5' , 'cols' => '5' ]);
Output:
<
textarea
name = "comment" cols = "5" rows = "5" >
</
textarea
>
Creating Select, Checkbox and Radio Controls
These controls share some commonalities and a few options and thus, they are all grouped in this subsection for easier reference.
Options for Select, Checkbox and Radio Controls
You can find below the options which are shared by select(), checkbox() and radio() (the options particular only to one of the methods are described in each method’s own section.)
• 'value' - Sets or selects the value of the affected element(s):
– For checkboxes, it sets the HTML 'value' attribute assigned to the input element to whatever you provide as value.
296 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
– For radio buttons or select pickers it defines which element will be selected when the form is rendered (in this case 'value' must be assigned a valid, existent element value). May also be used in combination with any select-type control, such as date(), time(), dateTime():
echo
$this -> Form -> time ( 'close_time' , [
'value' => '13:30:00'
]);
Note: The 'value' key for date() and dateTime() controls may also have as value a UNIX timestamp, or a DateTime object.
For a select control where you set the 'multiple' attribute to true, you can provide an array with the values you want to select by default:
// HTML <option> elements with values 1 and 3 will be rendered preselected
echo
$this -> Form -> select ( 'rooms' , [
'multiple' =>
true
,
'value' => [ 1 , 3 ]
]);
• 'empty' - Applies to radio() and select(). Defaults to false.
– When passed to radio() and set to true it will create an extra input element as the first radio button, with a value of '' and a label caption equal to the string 'empty'. If you want to control the label caption set this option to a string instead.
– When passed to a select method, this creates a blank HTML option element with an empty value in your drop down list. If you want to have an empty value with text displayed instead of just a blank option
, pass a string to 'empty':
echo
$this -> Form -> select (
'field' ,
[ 1 , 2 , 3 , 4 , 5 ],
[ 'empty' => '(choose one)' ]
);
Output:
<
select
name = "field" >
<
option
value = "" >(choose one)</
option
>
<
option
value = "0" >1</
option
>
<
option
value = "1" >2</
option
>
<
option
value = "2" >3</
option
>
<
option
value = "3" >4</
option
>
<
option
value = "4" >5</
option
>
</
select
>
• 'hiddenField' - For checkboxes and radio buttons, by default, a hidden input element is also created, along with the main element, so that the key in $this->request->getData() will exist even without a value specified. For checkboxes its value defaults to 0 and for radio buttons to ''.
Example of default output:
<
input
type = "hidden" name = "published" value = "0" />
<
input
type = "checkbox" name = "published" value = "1" />
This can be disabled by setting 'hiddenField' to false:
More About Views 297
CakePHP Cookbook Documentation, Release 3.5
echo
$this -> Form -> checkbox ( 'published' , [ 'hiddenField' =>
false
]);
Which outputs:
<
input
type = "checkbox" name = "published" value = "1" >
If you want to create multiple blocks of controls on a form, that are all grouped together, you should set this parameter to false on all controls except the first. If the hidden input is on the page in multiple places, only the last group of inputs‘ values will be saved.
In this example, only the tertiary colors would be passed, and the primary colors would be overridden:
<
h2
>Primary Colors</
h2
>
<
input
type = "hidden" name = "color" value = "0" />
<
label
for = "color-red" >
<
input
type = "checkbox" name = "color[]" value = "5" id = "color-red" />
Red
</
label
>
<
label
for = "color-blue" >
<
input
type = "checkbox" name = "color[]" value = "5" id = "color-blue" />
Blue
</
label
>
<
label
for = "color-yellow" >
<
input
type = "checkbox" name = "color[]" value = "5" id = "color-yellow" />
Yellow
</
label
>
<
h2
>Tertiary Colors</
h2
>
<
input
type = "hidden" name = "color" value = "0" />
<
label
for = "color-green" >
<
input
type = "checkbox" name = "color[]" value = "5" id = "color-green" />
Green
</
label
>
<
label
for = "color-purple" >
<
input
type = "checkbox" name = "color[]" value = "5" id = "color-purple" />
Purple
</
label
>
<
label
for = "color-orange" >
<
input
type = "checkbox" name = "color[]" value = "5" id = "color-orange" />
Orange
</
label
>
Disabling 'hiddenField' on the second control group would prevent this behavior.
You can set a hidden field to a value other than 0, such as ‘N’:
echo
$this -> Form -> checkbox ( 'published' , [
'value' => 'Y' ,
'hiddenField' => 'N' ,
]);
Creating Checkboxes
Cake\View\Helper\FormHelper::checkbox( string $fieldName , array $options)
298 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
• $fieldName - A field name in the form 'Modelname.fieldname'.
• $options - An optional array including any of the
Common Options For Specific Controls
Options for Select, Checkbox and Radio Controls
above, of the checkbox-specific options (see below), as well as any valid HTML attributes.
Creates a checkbox form element. The widget template used is:
'checkbox' => '<input type="checkbox" name="{{name}}" value="{{value}}"{{attrs}}>'
Options for Checkboxes
• 'checked' - Boolean to indicate whether this checkbox will be checked. Defaults to false.
• 'disabled' - Create a disabled checkbox input.
This method also generates an associated hidden form input element to force the submission of data for the specified field.
E.g.
echo
$this -> Form -> checkbox ( 'done' );
Will output:
<
input
type = "hidden" name = "done" value = "0" >
<
input
type = "checkbox" name = "done" value = "1" >
It is possible to specify the value of the checkbox by using the $options array.
E.g.
echo
$this -> Form -> checkbox ( 'done' , [ 'value' => 555 ]);
Will output:
<
input
type = "hidden" name = "done" value = "0" >
<
input
type = "checkbox" name = "done" value = "555" >
If you don’t want the FormHelper to create a hidden input use 'hiddenField'.
E.g.
echo
$this -> Form -> checkbox ( 'done' , [ 'hiddenField' =>
false
]);
Will output:
<
input
type = "checkbox" name = "done" value = "1" >
Creating Radio Buttons
Cake\View\Helper\FormHelper::radio( string $fieldName , array $options, array $attributes)
• $fieldName - A field name in the form 'Modelname.fieldname'.
• $options - An optional array containing at minimum the labels for the radio buttons. Can also contain values and HTML attributes. When this array is missing, the method will either generate only the hidden input (if
'hiddenField' is true) or no element at all (if 'hiddenField' is false).
More About Views 299
CakePHP Cookbook Documentation, Release 3.5
• $attributes - An optional array including any of the
Common Options For Specific Controls
Options for Select, Checkbox and Radio Controls
, of the radio button specific attributes (see below), as well as
any valid HTML attributes.
Creates a set of radio button inputs. The default widget templates used are:
'radio' => '<input type="radio" name="{{name}}" value="{{value}}"{{attrs}}>'
'radioWrapper' => '{{label}}'
Attributes for Radio Buttons
• 'label' - Boolean to indicate whether or not labels for widgets should be displayed. Defaults to true.
• 'hiddenField' - If set to true a hidden input with a value of '' will be included. This is useful for creating radio sets that are non-continuous. Defaults to true.
• 'disabled' - Set to true or 'disabled' to disable all the radio buttons. Defaults to false.
You must provide the label captions for the radio buttons via the $options argument.
For example:
$this -> Form -> radio ( 'gender' , [ 'Masculine' , 'Feminine' , 'Neuter' ]);
Will output:
<
input
name = "gender" value = "" type = "hidden" >
<
label
for = "gender-0" >
<
input
name = "gender" value = "0" id = "gender-0" type = "radio" >
Masculine
</
label
>
<
label
for = "gender-1" >
<
input
name = "gender" value = "1" id = "gender-1" type = "radio" >
Feminine
</
label
>
<
label
for = "gender-2" >
<
input
name = "gender" value = "2" id = "gender-2" type = "radio" >
Neuter
</
label
>
Generally $options contains simple key => value pairs. However, if you need to put custom attributes on your radio buttons you can use an expanded format.
E.g.
echo
$this -> Form -> radio (
'favorite_color' ,
[
[ 'value' => 'r' , 'text' => 'Red' , 'style' => 'color:red;' ],
[ 'value' => 'u' , 'text' => 'Blue' , 'style' => 'color:blue;' ],
[ 'value' => 'g' , 'text' => 'Green' , 'style' => 'color:green;' ],
]
);
Will output:
<
input
type = "hidden" name = "favorite_color" value = "" >
<
label
for = "favorite-color-r" >
<
input
type = "radio" name = "favorite_color" value = "r" style = "color:red;" id =
˓→
"favorite-color-r" >
Red
300 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
</
label
>
<
label
for = "favorite-color-u" >
<
input
type = "radio" name = "favorite_color" value = "u" style = "color:blue;" id =
˓→
"favorite-color-u" >
Blue
</
label
>
<
label
for = "favorite-color-g" >
<
input
type = "radio" name = "favorite_color" value = "g" style = "color:green;" id =
˓→
"favorite-color-g" >
Green
</
label
>
Creating Select Pickers
Cake\View\Helper\FormHelper::select( string $fieldName
, array $options, array $attributes)
• $fieldName - A field name in the form 'Modelname.fieldname'. This will provide the name attribute of the select element.
• $options - An optional array containing the list of items for the select picker. When this array is missing, the method will generate only the empty select HTML element without any option elements inside it.
• $attributes - An optional array including any of the
Common Options For Specific Controls
Options for Select, Checkbox and Radio Controls
, or of the select-specific attributes (see below), as well as any
valid HTML attributes.
Creates a select element, populated with the items from the $options array. If $attributes['value'] is provided, then the HTML option element(s) which have the specified value(s) will be shown as selected when rendering the select picker.
By default select uses the following widget templates:
'select' => '<select name="{{name}}"{{attrs}}>{{content}}</select>'
'option' => '<option value="{{value}}"{{attrs}}>{{text}}</option>'
May also use:
'optgroup' => '<optgroup label="{{label}}"{{attrs}}>{{content}}</optgroup>'
'selectMultiple' => '<select name="{{name}}[]" multiple="multiple"{{attrs}}>{{content}
˓→
}</select>'
Attributes for Select Pickers
• 'multiple' - If set to true allows multiple selections in the select picker. If set to 'checkbox', multiple checkboxes will be created instead. Defaults to null.
• 'escape' - Boolean. If true the contents of the option elements inside the select picker will be HTML entity encoded. Defaults to true.
• 'val' - Allows preselecting a value in the select picker.
• 'disabled' - Controls the disabled attribute. If set to true disables the whole select picker. If set to an array it will disable only those specific option elements whose values are provided in the array.
The $options argument allows you to manually specify the contents of the option elements of a select control.
E.g.
More About Views 301
CakePHP Cookbook Documentation, Release 3.5
echo
$this -> Form -> select ( 'field' , [ 1 , 2 , 3 , 4 , 5 ]);
Output:
<
select
name = "field" >
<
option
value = "0" >1</
option
>
<
option
value = "1" >2</
option
>
<
option
value = "2" >3</
option
>
<
option
value = "3" >4</
option
>
<
option
value = "4" >5</
option
>
</
select
>
The array for $options can also be supplied as key-value pairs.
E.g.
echo
$this -> Form -> select ( 'field' , [
'Value 1' => 'Label 1' ,
'Value 2' => 'Label 2' ,
'Value 3' => 'Label 3'
]);
Output:
<
select
name = "field" >
<
option
value = "Value 1" >Label 1</
option
>
<
option
value = "Value 2" >Label 2</
option
>
<
option
value = "Value 3" >Label 3</
option
>
</
select
>
If you would like to generate a select with optgroups, just pass data in hierarchical format (nested array). This works on multiple checkboxes and radio buttons too, but instead of optgroup it wraps the elements in fieldset elements.
For example:
$options = [
'Group 1' => [
'Value 1' => 'Label 1' ,
'Value 2' => 'Label 2'
],
'Group 2' => [
'Value 3' => 'Label 3'
]
];
echo
$this -> Form -> select ( 'field' , $options );
Output:
<
select
name = "field" >
<
optgroup
label = "Group 1" >
<
option
value = "Value 1" >Label 1</
option
>
<
option
value = "Value 2" >Label 2</
option
>
</
optgroup
>
<
optgroup
label = "Group 2" >
<
option
value = "Value 3" >Label 3</
option
>
</
optgroup
>
</
select
>
302 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
To generate HTML attributes within an option tag:
$options = [
[ 'text' => 'Description 1' , 'value' => 'value 1' , 'attr_name' => 'attr_value 1' ],
[ 'text' => 'Description 2' , 'value' => 'value 2' , 'attr_name' => 'attr_value 2' ],
[ 'text' => 'Description 3' , 'value' => 'value 3' , 'other_attr_name' => 'other_
˓→ attr_value' ],
];
echo
$this -> Form -> select ( 'field' , $options );
Output:
<
select
name = "field" >
<
option
value = "value 1" attr_name = "attr_value 1" >Description 1</
option
>
<
option
value = "value 2" attr_name = "attr_value 2" >Description 2</
option
>
<
option
value = "value 3" other_attr_name = "other_attr_value" >Description 3</
option
>
</
select
>
Controlling Select Pickers via Attributes
By using specific options in the $attributes parameter you can control certain behaviors of the select() method.
• 'empty' - Set the 'empty' key in the $attributes argument to true (the default value is false) to add a blank option with an empty value at the top of your dropdown list.
For example:
$options = [ 'M' => 'Male' , 'F' => 'Female' ];
echo
$this -> Form -> select ( 'gender' , $options , [ 'empty' =>
true
]);
Will output:
<
select
name = "gender" >
<
option
value = "" ></
option
>
<
option
value = "M" >Male</
option
>
<
option
value = "F" >Female</
option
>
</
select
>
• 'escape' - The select() method allows for an attribute called 'escape' which accepts a boolean value and determines whether to HTML entity encode the contents of the select‘s option elements.
E.g.
// This will prevent HTML-encoding the contents of each option element
$options = [ 'M' => 'Male' , 'F' => 'Female' ];
echo
$this -> Form -> select ( 'gender' , $options , [ 'escape' =>
false
]);
• 'multiple' - If set to true, the select picker will allow multiple selections.
E.g.
echo
$this -> Form -> select ( 'field' , $options , [ 'multiple' =>
true
]);
Alternatively, set 'multiple' to 'checkbox' in order to output a list of related checkboxes:
$options = [
'Value 1' => 'Label 1' ,
'Value 2' => 'Label 2'
];
More About Views 303
CakePHP Cookbook Documentation, Release 3.5
304 echo
$this -> Form -> select ( 'field' , $options , [
'multiple' => 'checkbox'
]);
Output:
<
input
name = "field" value = "" type = "hidden" >
<
div
class = "checkbox" >
<
label
for = "field-1" >
<
input
name = "field[]" value = "Value 1" id = "field-1" type = "checkbox" >
Label 1
</
label
>
</
div
>
<
div
class = "checkbox" >
<
label
for = "field-2" >
<
input
name = "field[]" value = "Value 2" id = "field-2" type = "checkbox" >
Label 2
</
label
>
</
div
>
• 'disabled' - This option can be set in order to disable all or some of the select‘s option items. To disable all items set 'disabled' to true. To disable only certain items, assign to 'disabled' an array containing the keys of the items to be disabled.
E.g.
$options = [
'M' => 'Masculine' ,
'F' => 'Feminine' ,
'N' => 'Neuter'
];
echo
$this -> Form -> select ( 'gender' , $options , [
'disabled' => [ 'M' , 'N' ]
]);
Will output:
<
select
name = "gender" >
<
option
value = "M" disabled = "disabled" >Masculine</
option
>
<
option
value = "F" >Feminine</
option
>
<
option
value = "N" disabled = "disabled" >Neuter</
option
>
</
select
>
This option also works when 'multiple' is set to 'checkbox':
$options = [
'Value 1' => 'Label 1' ,
'Value 2' => 'Label 2'
];
echo
$this -> Form -> select ( 'field' , $options , [
'multiple' => 'checkbox' ,
'disabled' => [ 'Value 1' ]
]);
Output:
<
input
name = "field" value = "" type = "hidden" >
<
div
class = "checkbox" >
Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
<
label
for = "field-1" >
<
input
name = "field[]" disabled = "disabled" value = "Value 1" type = "checkbox" >
Label 1
</
label
>
</
div
>
<
div
class = "checkbox" >
<
label
for = "field-2" >
<
input
name = "field[]" value = "Value 2" id = "field-2" type = "checkbox" >
Label 2
</
label
>
</
div
>
Creating File Inputs
Cake\View\Helper\FormHelper::file( string $fieldName , array $options)
• $fieldName - A field name in the form 'Modelname.fieldname'.
• $options - An optional array including any of the
Common Options For Specific Controls
as well as any valid
HTML attributes.
Creates a file upload field in the form. The widget template used by default is:
'file' => '<input type="file" name="{{name}}"{{attrs}}>'
To add a file upload field to a form, you must first make sure that the form enctype is set to
'multipart/form-data'
.
So start off with a create() method such as the following:
echo
$this -> Form -> create ( $document , [ 'enctype' => 'multipart/form-data' ]);
// OR
echo
$this -> Form -> create ( $document , [ 'type' => 'file' ]);
Next add a line that looks like either of the following two lines to your form’s view template file:
echo
$this -> Form -> control ( 'submittedfile' , [
'type' => 'file'
]);
// OR
echo
$this -> Form -> file ( 'submittedfile' );
Note: Due to the limitations of HTML itself, it is not possible to put default values into input fields of type ‘file’.
Each time the form is displayed, the value inside will be empty.
Upon submission, file fields provide an expanded data array to the script receiving the form data.
For the example above, the values in the submitted data array would be organized as follows, if CakePHP was installed on a Windows server (the key 'tmp\_name' will contain a different path in a Unix environment):
$this -> request -> data [ 'submittedfile' ]
// would contain the following array:
[
'name' => 'conference_schedule.pdf' ,
More About Views 305
CakePHP Cookbook Documentation, Release 3.5
];
'type' => 'application/pdf' ,
'tmp_name' => 'C:/WINDOWS/TEMP/php1EE.tmp' ,
'error' => 0 , // On Windows this can be a string.
'size' => 41737 ,
This array is generated by PHP itself, so for more detail on the way PHP handles data passed via file fields read the
PHP manual section on file uploads
121
Note: When using $this->Form->file(), remember to set the form encoding-type, by setting the 'type' option to 'file' in $this->Form->create().
Creating Date & Time Related Controls
The date and time related methods share a number of common traits and options and hence are grouped together into this subsection.
Common Options for Date & Time Controls
These options are common for the date and time related controls:
• 'empty' - If true an extra, empty, option HTML element is added inside select at the top of the list. If a string, that string is displayed as the empty element. Defaults to true.
• 'default' | value - Use either of the two to set the default value to be shown by the field. A value in
$this->request->getData() matching the field name will override this value. If no default is provided time() will be used.
• 'year','month','day','hour','minute','second','meridian' - These options allow you to control which control elements are generated or not. By setting any of these options to false you can disable the generation of that specific that select picker (if by default it would be rendered in the used method).
In addition each option allows you to pass HTML attributes to that specific select element.
Options for Date-Related Controls
These options are concerning the date-related methods - i.e. year(), month(), day(), dateTime() and date()
:
• 'monthNames' - If false, 2 digit numbers will be used instead of text for displaying months in the select picker. If set to an array (e.g. ['01' => 'Jan','02' => 'Feb',...]), the given array will be used.
• 'minYear' - The lowest value to use in the year select picker.
• 'maxYear' - The maximum value to use in the year select picker.
• 'orderYear' - The order of year values in the year select picker. Possible values are 'asc' and 'desc'.
Defaults to 'desc'.
121 http://php.net/features.file-upload
306 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Options for Time-Related Controls
These options are concerning the time-related methods - hour(), minute(), second(), dateTime() and time() :
• 'interval' - The interval in minutes between the values which are displayed in the option elements of the minutes select picker. Defaults to 1.
• 'round' - Set to up or down if you want to force rounding minutes in either direction when the value doesn’t fit neatly into an interval. Defaults to null.
• timeFormat - Applies to dateTime() and time(). The time format to use in the select picker; either
12 or 24. When this option is set to anything else than 24 the format will be automatically set to 12 and the meridian select picker will be displayed automatically to the right of the seconds select picker. Defaults to
24.
• format - Applies to hour(). The time format to use; either 12 or 24. In case it’s set to 12 the meridian select picker won’t be automatically displayed. It’s up to you to either add it or provide means to infer from the form context the right period of the day. Defaults to 24.
• second - Applies to dateTime() and time(). Set to true to enable the seconds drop down. Defaults to false .
Creating DateTime Controls
Cake\View\Helper\FormHelper::dateTime(
$fieldName , $options = [])
• $fieldName - A string that will be used as a prefix for the HTML name attribute of the select elements.
• $options - An optional array including any of the
Common Options For Specific Controls
options (see above), as well as any valid HTML attributes.
Creates a set of select elements for date and time.
To control the order of controls, and any elements/content between the controls you can override the dateWidget template. By default the dateWidget template is:
{{year}}{{month}}{{day}}{{hour}}{{minute}}{{second}}{{meridian}}
Calling the method without additional options will generate, by default, 5 select pickers, for: year (4 digits), month
(full English name), day (num), hour (num), minutes (num).
For example
<?= $this -> form -> dateTime ( 'registered' ) ?>
Output:
<
select
name = "registered[year]" >
<
option
value = "" selected = "selected" ></
option
>
<
option
value = "2022" >2022</
option
>
...
<
option
value = "2012" >2012</
option
>
</
select
>
<
select
name = "registered[month]" >
<
option
value = "" selected = "selected" ></
option
>
<
option
value = "01" >January</
option
>
...
<
option
value = "12" >December</
option
>
More About Views 307
CakePHP Cookbook Documentation, Release 3.5
</
select
>
<
select
name = "registered[day]" >
<
option
value = "" selected = "selected" ></
option
>
<
option
value = "01" >1</
option
>
...
<
option
value = "31" >31</
option
>
</
select
>
<
select
name = "registered[hour]" >
<
option
value = "" selected = "selected" ></
option
>
<
option
value = "00" >0</
option
>
...
<
option
value = "23" >23</
option
>
</
select
>
<
select
name = "registered[minute]" >
<
option
value = "" selected = "selected" ></
option
>
<
option
value = "00" >00</
option
>
...
<
option
value = "59" >59</
option
>
</
select
>
To create datetime controls with custom classes/attributes on a specific select box, you can provide them as arrays of options for each component, within the $options argument.
For example:
echo
$this -> Form -> dateTime ( 'released' , [
'year' => [
'class' => 'year-classname' ,
],
'month' => [
'class' => 'month-class' ,
'data-type' => 'month' ,
],
]);
Which would create the following two select pickers:
<
select
name = "released[year]" class = "year-class" >
<
option
value = "" selected = "selected" ></
option
>
<
option
value = "00" >0</
option
>
<
option
value = "01" >1</
option
>
<!-- .. snipped for brevity .. -->
</
select
>
<
select
name = "released[month]" class = "month-class" data-type = "month" >
<
option
value = "" selected = "selected" ></
option
>
<
option
value = "01" >January</
option
>
<!-- .. snipped for brevity .. -->
</
select
>
Creating Date Controls
Cake\View\Helper\FormHelper::date( $fieldName , $options = [])
• $fieldName - A field name that will be used as a prefix for the HTML name attribute of the select elements.
308 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
• $options - An optional array including any of the
Common Options For Specific Controls
Common
Options for Date & Time Controls
Options for Time-Related Controls
HTML attributes.
Creates, by default, three select pickers populated with values for: year (4 digits), month (full English name) and day
(numeric), respectively.
You can further control the generated select elements by providing additional options.
For example:
// Assuming current year is 2017; this disables day picker, removes empty
// option on year picker, limits lowest year, adds HTML attributes on year,
// adds a string 'empty' option on month, changes month to numeric
<?
php
echo
$this -> Form -> date ( 'registered' , [
'minYear' => 2018 ,
'monthNames' =>
false
,
'empty' => [
'year' =>
false
,
'month' => 'Choose month...'
],
'day' =>
false
,
'year' => [
'class' => 'cool-years' ,
'title' => 'Registration Year'
]
]);
?>
Output:
<
select
class = "cool-years" name = "registered[year]" title = "Registration Year" >
<
option
value = "2022" >2022</
option
>
<
option
value = "2021" >2021</
option
>
...
<
option
value = "2018" >2018</
option
>
</
select
>
<
select
name = "registered[month]" >
<
option
value = "" selected = "selected" >Choose month...</
option
>
<
option
value = "01" >1</
option
>
...
<
option
value = "12" >12</
option
>
</
select
>
Creating Time Controls
Cake\View\Helper\FormHelper::time(
$fieldName , $options = [])
• $fieldName - A field name that will be used as a prefix for the HTML name attribute of the select elements.
• $options - An optional array including any of the
Common Options For Specific Controls
Common
Options for Date & Time Controls
Options for Time-Related Controls
HTML attributes.
Creates, by default, two select elements (hour and minute) populated with values for 24 hours and 60 minutes, respectively. Additionally, HTML attributes may be supplied in $options for each specific component. If
More About Views 309
CakePHP Cookbook Documentation, Release 3.5
$options['empty'] is false, the select picker will not include an empty default option.
For example, to create a time range with minutes selectable in 15 minute increments, and to apply classes to the select boxes, you could do the following:
echo
$this -> Form -> time ( 'released' , [
'interval' => 15 ,
'hour' => [
'class' => 'foo-class' ,
],
'minute' => [
'class' => 'bar-class' ,
],
]);
Which would create the following two select pickers:
<
select
name = "released[hour]" class = "foo-class" >
<
option
value = "" selected = "selected" ></
option
>
<
option
value = "00" >0</
option
>
<
option
value = "01" >1</
option
>
<!-- .. snipped for brevity .. -->
<
option
value = "22" >22</
option
>
<
option
value = "23" >23</
option
>
</
select
>
<
select
name = "released[minute]" class = "bar-class" >
<
option
value = "" selected = "selected" ></
option
>
<
option
value = "00" >00</
option
>
<
option
value = "15" >15</
option
>
<
option
value = "30" >30</
option
>
<
option
value = "45" >45</
option
>
</
select
>
Creating Year Controls
Cake\View\Helper\FormHelper::year( string $fieldName , array $options = [])
• $fieldName - A field name that will be used as a prefix for the HTML name attribute of the select element.
• $options - An optional array including any of the
Common Options For Specific Controls
Common
Options for Date & Time Controls
Options for Date-Related Controls
HTML attributes.
Creates a select element populated with the years from minYear to maxYear (when these options are provided) or else with values starting from -5 years to +5 years counted from today. Additionally, HTML attributes may be supplied in $options. If $options['empty'] is false, the select picker will not include an empty item in the list.
For example, to create a year range from 2000 to the current year you would do the following:
echo
$this -> Form -> year ( 'purchased' , [
'minYear' => 2000 ,
'maxYear' => date ( 'Y' )
]);
If it was 2009, you would get the following:
310 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
<
select
name = "purchased[year]" >
<
option
value = "" ></
option
>
<
option
value = "2009" >2009</
option
>
<
option
value = "2008" >2008</
option
>
<
option
value = "2007" >2007</
option
>
<
option
value = "2006" >2006</
option
>
<
option
value = "2005" >2005</
option
>
<
option
value = "2004" >2004</
option
>
<
option
value = "2003" >2003</
option
>
<
option
value = "2002" >2002</
option
>
<
option
value = "2001" >2001</
option
>
<
option
value = "2000" >2000</
option
>
</
select
>
Creating Month Controls
Cake\View\Helper\FormHelper::month( string $fieldName , array $attributes)
• $fieldName - A field name that will be used as a prefix for the HTML name attribute of the select element.
• $attributes - An optional array including any of the
Common Options For Specific Controls
Common
Options for Date & Time Controls
Options for Date-Related Controls
HTML attributes.
Creates a select element populated with month names.
For example:
echo
$this -> Form -> month ( 'mob' );
Will output:
<
select
name = "mob[month]" >
<
option
value = "" ></
option
>
<
option
value = "01" >January</
option
>
<
option
value = "02" >February</
option
>
<
option
value = "03" >March</
option
>
<
option
value = "04" >April</
option
>
<
option
value = "05" >May</
option
>
<
option
value = "06" >June</
option
>
<
option
value = "07" >July</
option
>
<
option
value = "08" >August</
option
>
<
option
value = "09" >September</
option
>
<
option
value = "10" >October</
option
>
<
option
value = "11" >November</
option
>
<
option
value = "12" >December</
option
>
</
select
>
You can pass in, your own array of months to be used by setting the 'monthNames' attribute, or have months displayed as numbers by passing false.
E.g.
echo
$this -> Form -> month ( 'mob' , [ 'monthNames' =>
false
]);
Note: The default months can be localized with CakePHP
Internationalization & Localization
features.
More About Views 311
CakePHP Cookbook Documentation, Release 3.5
Creating Day Controls
Cake\View\Helper\FormHelper::day( string $fieldName , array $attributes)
• $fieldName - A field name that will be used as a prefix for the HTML name attribute of the select element.
• $attributes - An optional array including any of the
Common Options For Specific Controls
Common
Options for Date & Time Controls
Options for Date-Related Controls
HTML attributes.
Creates a select element populated with the (numerical) days of the month.
To create an empty option element with a prompt text of your choosing (e.g. the first option is ‘Day’), you can supply the text in the 'empty' parameter.
For example:
echo
$this -> Form -> day ( 'created' , [ 'empty' => 'Day' ]);
Will output:
<
select
name = "created[day]" >
<
option
value = "" selected = "selected" >Day</
option
>
<
option
value = "01" >1</
option
>
<
option
value = "02" >2</
option
>
<
option
value = "03" >3</
option
>
...
<
option
value = "31" >31</
option
>
</
select
>
Creating Hour Controls
Cake\View\Helper\FormHelper::hour( string $fieldName , array $attributes)
• $fieldName - A field name that will be used as a prefix for the HTML name attribute of the select element.
• $attributes - An optional array including any of the
Common Options For Specific Controls
Common
Options for Date & Time Controls
Options for Time-Related Controls
HTML attributes.
Creates a select element populated with the hours of the day.
You can create either 12 or 24 hour pickers using the 'format' option:
echo
$this -> Form -> hour ( 'created' , [
'format' => 12
]);
echo
$this -> Form -> hour ( 'created' , [
'format' => 24
]);
Creating Minute Controls
Cake\View\Helper\FormHelper::minute( string $fieldName , array $attributes)
• $fieldName - A field name that will be used as a prefix for the HTML name attribute of the select element.
312 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
• $attributes - An optional array including any of the
Common Options For Specific Controls
Common
Options for Date & Time Controls
Options for Time-Related Controls
HTML attributes.
Creates a select element populated with values for the minutes of the hour. You can create a select picker that only contains specific values by using the 'interval' option.
For example, if you wanted 10 minutes increments you would do the following:
// In your view template file
echo
$this -> Form -> minute ( 'arrival' , [
'interval' => 10
]);
This would output:
<
select
name = "arrival[minute]" >
<
option
value = "" selected = "selected" ></
option
>
<
option
value = "00" >00</
option
>
<
option
value = "10" >10</
option
>
<
option
value = "20" >20</
option
>
<
option
value = "30" >30</
option
>
<
option
value = "40" >40</
option
>
<
option
value = "50" >50</
option
>
</
select
>
Creating Meridian Controls
Cake\View\Helper\FormHelper::meridian( string $fieldName , array $attributes)
• $fieldName - A field name that will be used as a prefix for the HTML name attribute of the select element.
• $attributes - An optional array including any of the
Common Options For Specific Controls
as well as any valid HTML attributes.
Creates a select element populated with ‘am’ and ‘pm’. This is useful when the hour format is set to 12 instead of
24
, as it allows to specify the period of the day to which the hour belongs.
Creating Labels
Cake\View\Helper\FormHelper::label( string $fieldName , string $text, array $options)
• $fieldName - A field name in the form 'Modelname.fieldname'.
• $text - An optional string providing the label caption text.
• $options - Optional. String or an array containing any of the
Common Options For Specific Controls
as well as any valid HTML attributes.
Creates a label element. The argument $fieldName is used for generating the HTML for attribute of the element; if $text is undefined, $fieldName will also be used to inflect the label’s text attribute.
E.g.
echo
$this -> Form -> label ( 'User.name' );
echo
$this -> Form -> label ( 'User.name' , 'Your username' );
Output:
More About Views 313
CakePHP Cookbook Documentation, Release 3.5
<
label
for = "user-name" >Name</
label
>
<
label
for = "user-name" >Your username</
label
>
When you set $options to a string it will be used as a class name:
echo
$this -> Form -> label ( 'User.name' ,
null
, [ 'id' => 'user-label' ]);
echo
$this -> Form -> label ( 'User.name' , 'Your username' , 'highlight' );
Output:
<
label
for = "user-name" id = "user-label" >Name</
label
>
<
label
for = "user-name" class = "highlight" >Your username</
label
>
Displaying and Checking Errors
FormHelper exposes a couple of methods that allow us to easily check for field errors and when necessary display customized error messages.
Displaying Errors
Cake\View\Helper\FormHelper::error( string $fieldName
, mixed $text, array $options)
• $fieldName - A field name in the form 'Modelname.fieldname'.
• $text - Optional. A string or array providing the error message(s). If an array, then it should be a hash of key names => messages. Defaults to null.
• $options - An optional array that can only contain a boolean with the key 'escape', which will define whether to HTML escape the contents of the error message. Defaults to true.
Shows a validation error message, specified by $text, for the given field, in the event that a validation error has occurred. If $text is not provided then the default validation error message for that field will be used.
Uses the following template widgets:
'error' => '<div class="error-message">{{content}}</div>'
'errorList' => '<ul>{{content}}</ul>'
'errorItem' => '<li>{{text}}</li>'
The 'errorList' and 'errorItem' templates are used to format mutiple error messages per field.
Example:
// If in TicketsTable you have a 'notEmpty' validation rule:
public function
validationDefault (Validator $validator )
{
$validator
-> requirePresence ( 'ticket' , 'create' )
-> notEmpty ( 'ticket' );
}
// And inside Templates/Tickets/add.ctp you have:
echo
$this -> Form -> text ( 'ticket' );
if
( $this -> Form -> isFieldError ( 'ticket' )) {
echo
$this -> Form -> error ( 'ticket' , 'Completely custom error message!' );
}
314 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
If you would click the Submit button of your form without providing a value for the Ticket field, your form would output:
<
input
name = "ticket" class = "form-error" required = "required" value = "" type = "text" >
<
div
class = "error-message" >Completely custom error message!</
div
>
Note: When using
View\Helper\FormHelper::control()
, errors are rendered by default, so you don’t
need to use isFieldError() or call error() manually.
Tip: If you use a certain model field to generate multiple form fields via control(), and you want the same validation error message displayed for each one, you will probably be better off defining a custom error message inside the respective
validator rules
Checking for Errors
Cake\View\Helper\FormHelper::isFieldError( string $fieldName)
• $fieldName - A field name in the form 'Modelname.fieldname'.
Returns true if the supplied $fieldName has an active validation error, otherwise returns false.
Example:
if
( $this -> Form -> isFieldError ( 'gender' )) {
echo
$this -> Form -> error ( 'gender' );
}
Creating Buttons and Submit Elements
Creating Submit Elements
Cake\View\Helper\FormHelper::submit( string $caption
, array $options)
• $caption - An optional string providing the button’s text caption or a path to an image.
Defaults to
'Submit'
.
• $options - An optional array including any of the
Common Options For Specific Controls
submit options (see below) as well as any valid HTML attributes.
Creates an input element of submit type, with $caption as value. If the supplied $caption is a URL pointing to an image (i.e. if the string contains ‘://’ or contains any of the extensions ‘.jpg, .jpe, .jpeg, .gif’), an image submit button will be generated, using the specified image if it exists. If the first character is ‘/’ then the image path is relative to webroot, else if the first character is not ‘/’ then the image path is relative to webroot/img.
By default it will use the following widget templates:
'inputSubmit' => '<input type="{{type}}"{{attrs}}/>'
'submitContainer' => '<div class="submit">{{content}}</div>'
Options for Submit
More About Views 315
CakePHP Cookbook Documentation, Release 3.5
• 'type' - Set this option to 'reset' in order to generate reset buttons. It defaults to 'submit'.
• 'templateVars' - Set this array to provide additional template variables for the input element and its container.
• Any other provided attributes will be assigned to the input element.
The following:
echo
$this -> Form -> submit ( 'Click me' );
Will output:
<
div
class = "submit" ><
input
value = "Click me" type = "submit" ></
div
>
You can pass a relative or absolute URL of an image to the caption parameter instead of the caption text:
echo
$this -> Form -> submit ( 'ok.png' );
Will output:
<
div
class = "submit" ><
input
type = "image" src = "/img/ok.png" ></
div
>
Submit inputs are useful when you only need basic text or images. If you need more complex button content you should use button().
Creating Button Elements
Cake\View\Helper\FormHelper::button( string $title , array $options = [])
• $title - Mandatory string providing the button’s text caption.
• $options - An optional array including any of the
Common Options For Specific Controls
button options (see below) as well as any valid HTML attributes.
Creates an HTML button with the specified title and a default type of 'button'.
Options for Button
• $options['type'] - You can set this to one of the following three possible values:
1. 'submit' - Similarly to the $this->Form->submit() method it will create a submit button. However this won’t generate a wrapping div as submit() does. This is the default type.
2. 'reset' - Creates a form reset button.
3. 'button' - Creates a standard push button.
• $options['escape'] - Boolean. If set to true it will HTML encode the value provided inside $title.
Defaults to false.
For example:
echo
$this -> Form -> button ( 'A Button' );
echo
$this -> Form -> button ( 'Another Button' , [ 'type' => 'button' ]);
echo
$this -> Form -> button ( 'Reset the Form' , [ 'type' => 'reset' ]);
echo
$this -> Form -> button ( 'Submit Form' , [ 'type' => 'submit' ]);
Will output:
316 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
<
button
type = "submit" >A Button</
button
>
<
button
type = "button" >Another Button</
button
>
<
button
type = "reset" >Reset the Form</
button
>
<
button
type = "submit" >Submit Form</
button
>
Example of use of the 'escape' option:
// Will render escaped HTML.
echo
$this -> Form -> button ( '<em>Submit Form</em>' , [
'type' => 'submit' ,
'escape' =>
true
]);
Closing the Form
Cake\View\Helper\FormHelper::end(
$secureAttributes = [])
• $secureAttributes - Optional. Allows you to provide secure attributes which will be passed as HTML attributes into the hidden input elements generated for the SecurityComponent.
The end() method closes and completes a form.
Often, end() will only output a closing form tag, but using end() is a good practice as it enables FormHelper to insert the hidden form elements that
Cake\Controller\Component\SecurityComponent requires:
<?
= $this -> Form -> create (); ?>
<!-- Form elements go here -->
<?
= $this -> Form -> end (); ?>
If you need to add additional attributes to the generated hidden inputs you can use the $secureAttributes argument.
E.g.
echo
$this -> Form -> end ([ 'data-type' => 'hidden' ]);
Will output:
<
div
style = "display:none;" >
<
input
type = "hidden" name = "_Token[fields]" data-type = "hidden" value = "2981c38990f3f6ba935e6561dc77277966fabd6d%3AAddresses.id" >
<
input
type = "hidden" name = "_Token[unlocked]" data-type = "hidden" value = "address%7Cfirst_name" >
</
div
>
Note: If you are using Cake\Controller\Component\SecurityComponent in your application you should always end your forms with end().
More About Views 317
CakePHP Cookbook Documentation, Release 3.5
Creating Standalone Buttons and POST Links
Creating POST Buttons
Cake\View\Helper\FormHelper::postButton( string $title
, mixed $url, array $options = [])
• $title - Mandatory string providing the button’s text caption. By default not HTML encoded.
• $url - The URL of the form provided as a string or as array.
• $options - An optional array including any of the
Common Options For Specific Controls
options (see below) as well as any valid HTML attributes.
Creates a <button> tag with a surrounding <form> element that submits via POST, by default. Also, by default, it generates hidden input fields for the SecurityComponent.
Options for POST Button
• 'data' - Array with key/value to pass in hidden input.
• 'method' - Request method to use. E.g. set to 'delete' to simulate a HTTP/1.1 DELETE request. Defaults to 'post'.
• 'form' - Array with any option that FormHelper::create() can take.
• Also, the postButton() method will accept the options which are valid for the button() method.
For example:
// In Templates/Tickets/index.ctp
<?= $this -> Form -> postButton ( 'Delete Record' , [ 'controller' => 'Tickets' , 'action' =>
˓→
'delete' , 5 ]) ?>
Will output HTML similar to:
<
form
method = "post" accept-charset = "utf-8" action = "/Rtools/tickets/delete/5" >
<
div
style = "display:none;" >
<
input
name = "_method" value = "POST" type = "hidden" >
</
div
>
<
button
type = "submit" >Delete Record</
button
>
<
div
style = "display:none;" >
<
input
name = "_Token[fields]" value = "186cfbfc6f519622e19d1e688633c4028229081f
˓→
%3A" type = "hidden" >
<
input
name = "_Token[unlocked]" value = "" type = "hidden" >
<
input
name = "_Token[debug]" value = "%5B%22%5C%2FRtools%5C%2Ftickets%5C%2Fdelete
˓→
%5C%2F1%22%2C%5B%5D%2C%5B%5D%5D" type = "hidden" >
</
div
>
</
form
>
Since this method generates a form element, do not use this method in an already opened form. Instead use
Cake\View\Helper\FormHelper::submit()
or
Cake\View\Helper\FormHelper::button()
to create buttons inside opened forms.
Creating POST Links
Cake\View\Helper\FormHelper::postLink( string $title , mixed $url = null, array $options = [])
• $title - Mandatory string providing the text to be wrapped in <a> tags.
318 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
• $url - Optional. String or array which contains the URL of the form (Cake-relative or external URL starting with http://).
• $options - An optional array including any of the
Common Options For Specific Controls
options (see below) as well as any valid HTML attributes.
Creates an HTML link, but accesses the URL using the method you specify (defaults to POST). Requires JavaScript to be enabled in browser.
Options for POST Link
• 'data' - Array with key/value to pass in hidden input.
• 'method' - Request method to use. E.g. set to 'delete' to simulate a HTTP/1.1 DELETE request. Defaults to 'post'.
• 'confirm' - The confirmation message to display on click. Defaults to null.
• 'block' - Set this option to true to append the form to view block 'postLink' or provide a custom block name. Defaults to null.
• Also, the postLink method will accept the options which are valid for the link() method.
This method creates a <form> element. If you want to use this method inside of an existing form, you must use the block option so that the new form is being set to a
view block
that can be rendered outside of the main form.
If all you are looking for is a button to submit your form, then you should use
Cake\View\Helper\FormHelper::button()
or
Cake\View\Helper\FormHelper::submit()
instead.
Note: Be careful to not put a postLink inside an open form. Instead use the block option to buffer the form into a
view block
Customizing the Templates FormHelper Uses
Like many helpers in CakePHP, FormHelper uses string templates to format the HTML it creates. While the default templates are intended to be a reasonable set of defaults, you may need to customize the templates to suit your application.
To change the templates when the helper is loaded you can set the 'templates' option when including the helper in your controller:
// In a View class
$this -> loadHelper ( 'Form' , [
'templates' => 'app_form' ,
]);
This would load the tags found in config/app_form.php. This file should contain an array of templates indexed by name
:
// in config/app_form.php
return
[
'inputContainer' => '<div class="form-control">{{content}}</div>' ,
];
Any templates you define will replace the default ones included in the helper. Templates that are not replaced, will continue to use the default values.
You can also change the templates at runtime using the setTemplates() method:
More About Views 319
CakePHP Cookbook Documentation, Release 3.5
$myTemplates = [
'inputContainer' => '<div class="form-control">{{content}}</div>' ,
];
$this -> Form -> setTemplates ( $myTemplates );
// Prior to 3.4
$this -> Form -> templates ( $myTemplates );
Warning: Template strings containing a percentage sign (%) need special attention; you should prefix this character with another percentage so it looks like %%. The reason is that internally templates are compiled to be used with sprintf(). Example: '<div style="width:{{size}}%%">{{content}}</div>'
List of Templates
The list of default templates, their default format and the variables they expect can be found in the FormHelper API documentation
122
Using Distinct Custom Control Containers
In addition to these templates, the control() method will attempt to use distinct templates for each control container. For example, when creating a datetime control the datetimeContainer will be used if it is present. If that container is missing the inputContainer template will be used.
For example:
// Add custom radio wrapping HTML
$this -> Form -> setTemplates ([
'radioContainer' => '<div class="form-radio">{{content}}</div>'
]);
// Create a radio set with our custom wrapping div.
echo
$this -> Form -> control ( 'User.email_notifications' , [
'options' => [ 'y' , 'n' ],
'type' => 'radio'
]);
Using Distinct Custom Form Groups
Similar to controlling containers, the control() method will also attempt to use distinct templates for each form group. A form group is a combo of label and control. For example, when creating a radio control the radioFormGroup will be used if it is present. If that template is missing by default each set of label & input is rendered using the default formGroup template.
For example:
// Add custom radio form group
$this -> Form -> setTemplates ([
'radioFormGroup' => '<div class="radio">{{label}}{{input}}</div>'
]);
122 https://api.cakephp.org/3.x/class-Cake.View.Helper.FormHelper.html#%24_defaultConfig
320 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Adding Additional Template Variables to Templates
You can add additional template placeholders in custom templates, and populate those placeholders when generating controls.
E.g.
// Add a template with the help placeholder.
$this -> Form -> setTemplates ([
'inputContainer' => '<div class="input {{type}}{{required}}">
{{content}} <span class="help">{{help}}</span></div>'
]);
// Generate an input and populate the help variable
echo
$this -> Form -> control ( 'password' , [
'templateVars' => [ 'help' => 'At least 8 characters long.' ]
]);
Output:
<
div
class = "input password" >
<
label
for = "password" >
Password
</
label
>
<
input
name = "password" id = "password" type = "password" >
<
span
class = "help" >At least 8 characters long.</
span
>
</
div
>
New in version 3.1: The templateVars option was added in 3.1.0
Moving Checkboxes & Radios Outside of a Label
By default CakePHP nests checkboxes created via control() and radio buttons created by both control() and radio() within label elements. This helps make it easier to integrate popular CSS frameworks. If you need to place checkbox/radio inputs outside of the label you can do so by modifying the templates:
$this -> Form -> setTemplates ([
'nestingLabel' => '{{input}}<label{{attrs}}>{{text}}</label>' ,
'formGroup' => '{{input}}{{label}}' ,
]);
This will make radio buttons and checkboxes render outside of their labels.
Generating Entire Forms
Creating Multiple Controls
Cake\View\Helper\FormHelper::controls( array $fields = [] , $options = [])
• $fields - An array of fields to generate. Allows setting custom types, labels and other options for each specified field.
• $options - Optional. An array of options. Valid keys are:
1. 'fieldset' - Set this to false to disable the fieldset. If empty, the fieldset will be enabled. Can also be an array of parameters to be applied as HTML attributes to the fieldset tag.
More About Views 321
CakePHP Cookbook Documentation, Release 3.5
2. legend - String used to customize the legend text. Set this to false to disable the legend for the generated input set.
Generates a set of controls for the given context wrapped in a fieldset. You can specify the generated fields by including them:
echo
$this -> Form -> controls ([
'name' ,
'email'
]);
You can customize the legend text using an option:
echo
$this -> Form -> controls ( $fields , [ 'legend' => 'Update news post' ]);
You can customize the generated controls by defining additional options in the $fields parameter:
echo
$this -> Form -> controls ([
'name' => [ 'label' => 'custom label' ]
]);
When customizing, $fields, you can use the $options parameter to control the generated legend/fieldset.
For example:
echo
$this -> Form -> controls (
[
'name' => [ 'label' => 'custom label' ]
],
[ 'legend' => 'Update your post' ]
);
If you disable the fieldset, the legend will not print.
Creating Controls for a Whole Entity
Cake\View\Helper\FormHelper::allControls( array $fields , $options = [])
• $fields - Optional. An array of customizations for the fields that will be generated. Allows setting custom types, labels and other options.
• $options - Optional. An array of options. Valid keys are:
1. 'fieldset' - Set this to false to disable the fieldset. If empty, the fieldset will be enabled. Can also be an array of parameters to be applied as HTMl attributes to the fieldset tag.
2. legend - String used to customize the legend text. Set this to false to disable the legend for the generated control set.
This method is closely related to controls(), however the $fields argument is defaulted to all fields in the current top-level entity. To exclude specific fields from the generated controls, set them to false in the $fields parameter:
echo
$this -> Form -> allControls ([ 'password' =>
false
]);
// Or prior to 3.4.0:
echo
$this -> Form -> allInputs ([ 'password' =>
false
]);
322 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Creating Inputs for Associated Data
Creating forms for associated data is straightforward and is closely related to the paths in your entity’s data. Assuming the following table relations:
• Authors HasOne Profiles
• Authors HasMany Articles
• Articles HasMany Comments
• Articles BelongsTo Authors
• Articles BelongsToMany Tags
If we were editing an article with its associations loaded we could create the following controls:
$this -> Form -> create ( $article );
// Article controls.
echo
$this -> Form -> control ( 'title' );
// Author controls (belongsTo)
echo
$this -> Form -> control ( 'author.id' );
echo
$this -> Form -> control ( 'author.first_name' );
echo
$this -> Form -> control ( 'author.last_name' );
// Author profile (belongsTo + hasOne)
echo
$this -> Form -> control ( 'author.profile.id' );
echo
$this -> Form -> control ( 'author.profile.username' );
// Tags controls (belongsToMany)
echo
$this -> Form -> control ( 'tags.0.id' );
echo
$this -> Form -> control ( 'tags.0.name' );
echo
$this -> Form -> control ( 'tags.1.id' );
echo
$this -> Form -> control ( 'tags.1.name' );
// Multiple select element for belongsToMany
echo
$this -> Form -> control ( 'tags._ids' , [
'type' => 'select' ,
'multiple' =>
true
,
'options' => $tagList ,
]);
// Inputs for the joint table (articles_tags)
echo
$this -> Form -> control ( 'tags.0._joinData.starred' );
echo
$this -> Form -> control ( 'tags.1._joinData.starred' );
// Comments controls (hasMany)
echo
$this -> Form -> control ( 'comments.0.id' );
echo
$this -> Form -> control ( 'comments.0.comment' );
echo
$this -> Form -> control ( 'comments.1.id' );
echo
$this -> Form -> control ( 'comments.1.comment' );
The above controls could then be marshalled into a completed entity graph using the following code in your controller:
$article = $this -> Articles -> patchEntity ( $article , $this -> request -> getData (), [
'associated' => [
'Authors' ,
'Authors.Profiles' ,
More About Views 323
CakePHP Cookbook Documentation, Release 3.5
]);
]
'Tags' ,
'Comments'
Adding Custom Widgets
CakePHP makes it easy to add custom control widgets in your application, and use them like any other control type.
All of the core control types are implemented as widgets, which means you can override any core widget with your own implementation as well.
Building a Widget Class
Widget classes have a very simple required interface.
They must implement the
Cake\View\Widget\WidgetInterface
.
This interface requires the render(array $data) and secureFields(array $data) methods to be implemented. The render() method expects an array of data to build the widget and is expected to return a string of HTML for the widget. The secureFields() method expects an array of data as well and is expected to return an array containing the list of fields to secure for this widget.
If CakePHP is constructing your widget you can expect to get a Cake\View\StringTemplate instance as the first argument, followed by any dependencies you define. If we wanted to build an Autocomplete widget you could do the following:
namespace
App\View\Widget;
use
Cake\View\Form\ContextInterface;
use
Cake\View\Widget\WidgetInterface;
class AutocompleteWidget implements
WidgetInterface
{
protected
$_templates ;
public function
__construct ( $templates )
{
$this -> _templates = $templates ;
}
public function
render (
array
$data , ContextInterface $context )
{
$data += [
'name' => '' ,
];
return
$this -> _templates -> format ( 'autocomplete' , [
'name' => $data [ 'name' ],
'attrs' => $this -> _templates -> formatAttributes ( $data , [ 'name' ])
]);
}
public function
secureFields (
array
$data )
{
return
[ $data [ 'name' ]];
}
}
324 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Obviously, this is a very simple example, but it demonstrates how a custom widget could be built. This widget would render the “autocomplete” string template, such as:
$this -> Form -> setTemplates ([
'autocomplete' => '<input type="autocomplete" name="{{name}}" {{attrs}} />'
]);
For more information on string templates, see
Customizing the Templates FormHelper Uses
Using Widgets
You can load custom widgets when loading FormHelper or by using the addWidget() method. When loading
FormHelper, widgets are defined as a setting:
// In View class
$this -> loadHelper ( 'Form' , [
'widgets' => [
'autocomplete' => [ 'Autocomplete' ]
]
]);
If your widget requires other widgets, you can have FormHelper populate those dependencies by declaring them:
$this -> loadHelper ( 'Form' , [
'widgets' => [
'autocomplete' => [
'App\View\Widget\AutocompleteWidget' ,
'text' ,
'label'
]
]
]);
In the above example, the autocomplete widget would depend on the text and label widgets. If your widget needs access to the View, you should use the _view ‘widget’. When the autocomplete widget is created, it will be passed the widget objects that are related to the text and label names. To add widgets using the addWidget() method would look like:
// Using a classname.
$this -> Form -> addWidget (
'autocomplete' ,
[ 'Autocomplete' , 'text' , 'label' ]
);
// Using an instance - requires you to resolve dependencies.
$autocomplete =
new
AutocompleteWidget(
$this -> Form -> getTemplater (),
$this -> Form -> widgetRegistry () -> get ( 'text' ),
$this -> Form -> widgetRegistry () -> get ( 'label' ),
);
$this -> Form -> addWidget ( 'autocomplete' , $autocomplete );
Once added/replaced, widgets can be used as the control ‘type’:
echo
$this -> Form -> control ( 'search' , [ 'type' => 'autocomplete' ]);
More About Views 325
CakePHP Cookbook Documentation, Release 3.5
This will create the custom widget with a label and wrapping div just like controls() always does. Alternatively, you can create just the control widget using the magic method:
echo
$this -> Form -> autocomplete ( 'search' , $options );
Working with SecurityComponent
Cake\Controller\Component\SecurityComponent offers several features that make your forms safer and more secure. By simply including the SecurityComponent in your controller, you’ll automatically benefit from form tampering-prevention features.
As mentioned previously when using SecurityComponent, you should always close your forms using
View\Helper\FormHelper::end()
. This will ensure that the special _Token inputs are generated.
Cake\View\Helper\FormHelper::unlockField(
$name)
• $name - Optional. The dot-separated name for the field.
Unlocks a field making it exempt from the SecurityComponent field hashing. This also allows the fields to be manipulated by JavaScript. The $name parameter should be the entity property name for the field:
$this -> Form -> unlockField ( 'id' );
Cake\View\Helper\FormHelper::secure( array $fields = [] , array $secureAttributes = [])
• $fields - Optional. An array containing the list of fields to use when generating the hash. If not provided, then $this->fields will be used.
• $secureAttributes - Optional. An array of HTML attributes to be passed into the generated hidden input elements.
Generates a hidden input field with a security hash based on the fields used in the form or an empty string when secured forms are not in use. If $secureAttributes is set, these HTML attributes will be merged into the hidden input tags generated for the SecurityComponent. This is especially useful to set HTML5 attributes like 'form'.
Html
class Cake\View\Helper\HtmlHelper(View $view, array $config = [])
The role of the HtmlHelper in CakePHP is to make HTML-related options easier, faster, and more resilient to change.
Using this helper will enable your application to be more light on its feet, and more flexible on where it is placed in relation to the root of a domain.
Many HtmlHelper methods include a $attributes parameter, that allow you to tack on any extra attributes on your tags. Here are a few examples of how to use the $attributes parameter:
Desired attributes: <
tag
class = "someClass" />
Array parameter: ['class' => 'someClass']
Desired attributes: <
tag
name = "foo" value = "bar" />
Array parameter: ['name' => 'foo', 'value' => 'bar']
Inserting Well-Formatted Elements
The most important task the HtmlHelper accomplishes is creating well formed markup. This section will cover some of the methods of the HtmlHelper and how to use them.
326 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Creating Charset Tags
Cake\View\Helper\HtmlHelper::charset( $charset=null)
Used to create a meta tag specifying the document’s character. The default value is UTF-8. An example use:
echo
$this -> Html -> charset ();
Will output:
<
meta
http-equiv = "Content-Type" content = "text/html; charset=utf-8" />
Alternatively,
echo
$this -> Html -> charset ( 'ISO-8859-1' );
Will output:
<
meta
http-equiv = "Content-Type" content = "text/html; charset=ISO-8859-1" />
Linking to CSS Files
Cake\View\Helper\HtmlHelper::css( mixed $path , array $options = [])
Creates a link(s) to a CSS style-sheet. If the block option is set to true, the link tags are added to the css block which you can print inside the head tag of the document.
You can use the block option to control which block the link element will be appended to. By default it will append to the css block.
If key ‘rel’ in $options array is set to ‘import’ the stylesheet will be imported.
This method of CSS inclusion assumes that the CSS file specified resides inside the webroot/css directory if path doesn’t start with a ‘/’.
echo
$this -> Html -> css ( 'forms' );
Will output:
<
link
rel = "stylesheet" href = "/css/forms.css" />
The first parameter can be an array to include multiple files.
echo
$this -> Html -> css ([ 'forms' , 'tables' , 'menu' ]);
Will output:
<
link
rel = "stylesheet" href = "/css/forms.css" />
<
link
rel = "stylesheet" href = "/css/tables.css" />
<
link
rel = "stylesheet" href = "/css/menu.css" />
You can include CSS files from any loaded plugin using
plugin syntax
ins/DebugKit/webroot/css/toolbar.css you could use the following:
echo
$this -> Html -> css ( 'DebugKit.toolbar.css' );
To include plug-
More About Views 327
CakePHP Cookbook Documentation, Release 3.5
If you want to include a CSS file which shares a name with a loaded plugin you can do the following. For example if you had a Blog plugin, and also wanted to include webroot/css/Blog.common.css, you would:
echo
$this -> Html -> css ( 'Blog.common.css' , [ 'plugin' =>
false
]);
Creating CSS Programatically
Cake\View\Helper\HtmlHelper::style( array $data , boolean $oneline = true)
Builds CSS style definitions based on the keys and values of the array passed to the method. Especially handy if your
CSS file is dynamic.
echo
$this -> Html -> style ([
'background' => '#633' ,
'border-bottom' => '1px solid #000' ,
'padding' => '10px'
]);
Will output: background : #633; border-bottom:1px solid #000; padding:10px;
Creating meta Tags
Cake\View\Helper\HtmlHelper::meta( string|array $type , string $url = null, array $options = [])
This method is handy for linking to external resources like RSS/Atom feeds and favicons. Like css(), you can specify whether or not you’d like this tag to appear inline or appended to the meta block by setting the ‘block’ key in the
$attributes parameter to true, ie - ['block' => true].
If you set the “type” attribute using the $attributes parameter, CakePHP contains a few shortcuts: type translated value html text/html rss application/rss+xml atom application/atom+xml icon image/x-icon
<?
= $this -> Html -> meta (
'favicon.ico' ,
'/favicon.ico' ,
[ 'type' => 'icon' ]
);
?>
// Output (line breaks added)
<link href="http://example.com/favicon.ico" title="favicon.ico" type="image/x-icon" rel="alternate"
/>
<?
= $this -> Html -> meta (
'Comments' ,
'/comments/index.rss' ,
[ 'type' => 'rss' ]
);
?>
328 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
// Output (line breaks added)
<link href="http://example.com/comments/index.rss" title="Comments" type="application/rss+xml" rel="alternate"
/>
This method can also be used to add the meta keywords and descriptions. Example:
<?= $this -> Html -> meta (
'keywords' ,
'enter any meta keyword here'
);
?>
// Output
<meta name="keywords" content="enter any meta keyword here" />
<?
= $this -> Html -> meta (
'description' ,
'enter any meta description here'
);
?>
// Output
<meta name="description" content="enter any meta description here" />
In addition to making predefined meta tags, you can create link elements:
<?= $this -> Html -> meta ([
'link' => 'http://example.com/manifest' ,
'rel' => 'manifest'
]);
?>
// Output
<link href="http://example.com/manifest" rel="manifest"/>
Any attributes provided to meta() when called this way will be added to the generated link tag.
Creating DOCTYPE
Cake\View\Helper\HtmlHelper::docType( string $type = ‘html5’)
Returns a (X)HTML DOCTYPE (document type declaration). Supply the document type according to the following table: type html4-strict html4-trans html4-frame translated value
HTML 4.01 Strict
HTML 4.01 Transitional
HTML 4.01 Frameset html5 (default) HTML5 xhtml-strict xhtml-trans xhtml-frame xhtml11
XHTML 1.0 Strict
XHTML 1.0 Transitional
XHTML 1.0 Frameset
XHTML 1.1
More About Views 329
CakePHP Cookbook Documentation, Release 3.5
echo
$this -> Html -> docType ();
// Outputs: <!DOCTYPE html>
echo
$this -> Html -> docType ( 'html4-trans' );
// Outputs:
// <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
// "http://www.w3.org/TR/html4/loose.dtd">
Linking to Images
Cake\View\Helper\HtmlHelper::image( string $path , array $options = [])
Creates a formatted image tag. The path supplied should be relative to webroot/img/.
echo
$this -> Html -> image ( 'cake_logo.png' , [ 'alt' => 'CakePHP' ]);
Will output:
<
img
src = "/img/cake_logo.png" alt = "CakePHP" />
To create an image link specify the link destination using the url option in $attributes.
echo
$this -> Html -> image ( "recipes/6.jpg" , [
"alt" => "Brownies" ,
'url' => [ 'controller' => 'Recipes' , 'action' => 'view' , 6 ]
]);
Will output:
<
a
href = "/recipes/view/6" >
<
img
src = "/img/recipes/6.jpg" alt = "Brownies" />
</
a
>
If you are creating images in emails, or want absolute paths to images you can use the fullBase option:
echo
$this -> Html -> image ( "logo.png" , [ 'fullBase' =>
true
]);
Will output:
<
img
src = "http://example.com/img/logo.jpg" alt = "" />
You can include image files from any loaded plugin using
plugin syntax
ins/DebugKit/webroot/img/icon.png You could use the following:
echo
$this -> Html -> image ( 'DebugKit.icon.png' );
To include plug-
If you want to include an image file which shares a name with a loaded plugin you can do the following. For example if you had a Blog plugin, and also wanted to include webroot/img/Blog.icon.png, you would:
echo
$this -> Html -> image ( 'Blog.icon.png' , [ 'plugin' =>
false
]);
Creating Links
Cake\View\Helper\HtmlHelper::link( string $title , mixed $url = null, array $options = [])
330 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
General purpose method for creating HTML links. Use $options to specify attributes for the element and whether or not the $title should be escaped.
echo
$this -> Html -> link (
'Enter' ,
'/pages/home' ,
[ 'class' => 'button' , 'target' => '_blank' ]
);
Will output:
<
a
href = "/pages/home" class = "button" target = "_blank" >Enter</
a
>
Use '_full'=>true option for absolute URLs:
echo
$this -> Html -> link (
'Dashboard' ,
[ 'controller' => 'Dashboards' , 'action' => 'index' , '_full' =>
true
]
);
Will output:
<
a
href = "http://www.yourdomain.com/dashboards/index" >Dashboard</
a
>
Specify confirm key in options to display a JavaScript confirm() dialog:
echo
$this -> Html -> link (
'Delete' ,
[ 'controller' => 'Recipes' , 'action' => 'delete' , 6 ],
[ 'confirm' => 'Are you sure you wish to delete this recipe?' ]
);
Will output:
<
a
href = "/recipes/delete/6" onclick = "return confirm(
'Are you sure you wish to delete this recipe?'
);" >
</
a
>
Delete
Query strings can also be created with link().
echo
$this -> Html -> link ( 'View image' , [
'controller' => 'Images' ,
'action' => 'view' ,
1 ,
'?' => [ 'height' => 400 , 'width' => 500 ]
]);
Will output:
<
a
href = "/images/view/1?height=400&width=500" >View image</
a
>
HTML special characters in $title will be converted to HTML entities. To disable this conversion, set the escape option to false in the $options array.
More About Views 331
CakePHP Cookbook Documentation, Release 3.5
echo
$this -> Html -> link (
$this -> Html -> image ( "recipes/6.jpg" , [ "alt" => "Brownies" ]),
"recipes/view/6" ,
[ 'escape' =>
false
]
);
Will output:
<
a
href = "/recipes/view/6" >
<
img
src = "/img/recipes/6.jpg" alt = "Brownies" />
</
a
>
Setting escape to false will also disable escaping of attributes of the link. You can use the option escapeTitle to disable just escaping of title and not the attributes.
echo
$this -> Html -> link (
$this -> Html -> image ( 'recipes/6.jpg' , [ 'alt' => 'Brownies' ]),
'recipes/view/6' ,
[ 'escapeTitle' =>
false
, 'title' => 'hi "howdy"' ]
);
Will output:
<
a
href = "/recipes/view/6" title = "hi "howdy"" >
</
a
>
<
img
src = "/img/recipes/6.jpg" alt = "Brownies" />
Also check
Cake\View\Helper\UrlHelper::build()
method for more examples of different types of
URLs.
Linking to Videos and Audio Files
Cake\View\Helper\HtmlHelper::media( string|array $path , array $options)
Options:
• type Type of media element to generate, valid values are “audio” or “video”. If type is not provided media type is guessed based on file’s mime type.
• text Text to include inside the video tag
• pathPrefix Path prefix to use for relative URLs, defaults to ‘files/’
• fullBase If provided the src attribute will get a full address including domain name
Returns a formatted audio/video tag:
<?
= $this -> Html -> media ( 'audio.mp3' ) ?>
// Output
<audio src="/files/audio.mp3"></audio>
<?
= $this -> Html -> media ( 'video.mp4' , [
'fullBase' =>
true
,
'text' => 'Fallback text'
]) ?>
// Output
332 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
<video src="http://www.somehost.com/files/video.mp4">Fallback text</video>
<?
= $this -> Html -> media (
[ 'video.mp4' , [ 'src' => 'video.ogg' , 'type' => "video/ogg; codecs='theora, vorbis
˓→
'" ]],
[ 'autoplay' ]
) ?>
// Output
<video autoplay="autoplay">
<source src="/files/video.mp4" type="video/mp4"/>
<source src="/files/video.ogg" type="video/ogg; codecs='theora, vorbis'"/>
</video>
Linking to Javascript Files
Cake\View\Helper\HtmlHelper::script( mixed $url , mixed $options)
Include a script file(s), contained either locally or as a remote URL.
By default, script tags are added to the document inline. If you override this by setting $options['block'] to true , the script tags will instead be added to the script block which you can print elsewhere in the document. If you wish to override which block name is used, you can do so by setting $options['block'].
$options['once'] controls whether or not you want to include this script once per request or more than once.
This defaults to true.
You can use $options to set additional properties to the generated script tag. If an array of script tags is used, the attributes will be applied to all of the generated script tags.
This method of JavaScript file inclusion assumes that the JavaScript file specified resides inside the webroot/js directory:
echo
$this -> Html -> script ( 'scripts' );
Will output:
<
script
src = "/js/scripts.js" ></
script
>
You can link to files with absolute paths as well to link files that are not in webroot/js:
echo
$this -> Html -> script ( '/otherdir/script_file' );
You can also link to a remote URL:
echo
$this -> Html -> script ( 'http://code.jquery.com/jquery.min.js' );
Will output:
<
script
src = "http://code.jquery.com/jquery.min.js" ></
script
>
The first parameter can be an array to include multiple files.
echo
$this -> Html -> script ([ 'jquery' , 'wysiwyg' , 'scripts' ]);
Will output:
More About Views 333
CakePHP Cookbook Documentation, Release 3.5
<
script
src = "/js/jquery.js" ></
script
>
<
script
src = "/js/wysiwyg.js" ></
script
>
<
script
src = "/js/scripts.js" ></
script
>
You can append the script tag to a specific block using the block option:
echo
$this -> Html -> script ( 'wysiwyg' , [ 'block' => 'scriptBottom' ]);
In your layout you can output all the script tags added to ‘scriptBottom’:
echo
$this -> fetch ( 'scriptBottom' );
You can include script files from any loaded plugin using
plugin syntax
ins/DebugKit/webroot/js/toolbar.js You could use the following:
echo
$this -> Html -> script ( 'DebugKit.toolbar.js' );
To include plug-
If you want to include a script file which shares a name with a loaded plugin you can do the following. For example if you had a Blog plugin, and also wanted to include webroot/js/Blog.plugins.js, you would:
echo
$this -> Html -> script ( 'Blog.plugins.js' , [ 'plugin' =>
false
]);
Creating Inline Javascript Blocks
Cake\View\Helper\HtmlHelper::scriptBlock( $code
, $options = [])
To generate Javascript blocks from PHP view code, you can use one of the script block methods. Scripts can either be output in place, or buffered into a block:
// Define a script block all at once, with the defer attribute.
$this -> Html -> scriptBlock ( 'alert("hi")' , [ 'defer' =>
true
]);
// Buffer a script block to be output later.
$this -> Html -> scriptBlock ( 'alert("hi")' , [ 'block' =>
true
]);
Cake\View\Helper\HtmlHelper::scriptStart( $options = [])
Cake\View\Helper\HtmlHelper::scriptEnd()
You can use the scriptStart() method to create a capturing block that will output into a <script> tag. Captured script snippets can be output inline, or buffered into a block:
// Append into the 'script' block.
$this -> Html -> scriptStart ([ 'block' =>
true
]);
echo
"alert('I am in the JavaScript');" ;
$this -> Html -> scriptEnd ();
Once you have buffered javascript, you can output it as you would any other
View Block
// In your layout
echo
$this -> fetch ( 'script' );
Creating Nested Lists
Cake\View\Helper\HtmlHelper::nestedList( array $list , array $options = [], array $itemOptions = [])
334 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Build a nested list (UL/OL) out of an associative array:
$list = [
'Languages' => [
'English' => [
'American' ,
'Canadian' ,
'British' ,
],
'Spanish' ,
'German' ,
]
];
echo
$this -> Html -> nestedList ( $list );
Output:
// Output (minus the whitespace)
<
ul
>
<
li
>Languages
<
ul
>
<
li
>English
<
ul
>
<
li
>American</
li
>
<
li
>Canadian</
li
>
<
li
>British</
li
>
</
ul
>
</
li
>
<
li
>Spanish</
li
>
<
li
>German</
li
>
</
ul
>
</
li
>
</
ul
>
Creating Table Headings
Cake\View\Helper\HtmlHelper::tableHeaders( array $names , array $trOptions = null, array
$thOptions = null)
Creates a row of table header cells to be placed inside of <table> tags.
echo
$this -> Html -> tableHeaders ([ 'Date' , 'Title' , 'Active' ]);
Output:
<
tr
>
<
th
>Date</
th
>
<
th
>Title</
th
>
<
th
>Active</
th
>
</
tr
>
echo
$this -> Html -> tableHeaders (
[ 'Date' , 'Title' , 'Active' ],
[ 'class' => 'status' ],
[ 'class' => 'product_table' ]
);
More About Views 335
CakePHP Cookbook Documentation, Release 3.5
Output:
<
tr
class = "status" >
<
th
class = "product_table" >Date</
th
>
</
tr
>
<
th
class = "product_table" >Title</
th
>
<
th
class = "product_table" >Active</
th
>
You can set attributes per column, these are used instead of the defaults provided in the $thOptions:
echo
$this -> Html -> tableHeaders ([
'id' ,
[ 'Name' => [ 'class' => 'highlight' ]],
[ 'Date' => [ 'class' => 'sortable' ]]
]);
Output:
<
tr
>
<
th
>id</
th
>
<
th
class = "highlight" >Name</
th
>
<
th
class = "sortable" >Date</
th
>
</
tr
>
Creating Table Cells
Cake\View\Helper\HtmlHelper::tableCells( array $data , array $oddTrOptions = null, array
$evenTrOptions = null , $useCount = false, $continueOddEven = true)
Creates table cells, in rows, assigning <tr> attributes differently for odd- and even-numbered rows. Wrap a single table cell within an [] for specific <td>-attributes.
echo
$this -> Html -> tableCells ([
[ 'Jul 7th, 2007' , 'Best Brownies' , 'Yes' ],
[ 'Jun 21st, 2007' , 'Smart Cookies' , 'Yes' ],
[ 'Aug 1st, 2006' , 'Anti-Java Cake' , 'No' ],
]);
Output:
<
tr
><
td
>Jul 7th, 2007</
td
><
td
>Best Brownies</
td
><
td
>Yes</
td
></
tr
>
<
tr
><
td
>Jun 21st, 2007</
td
><
td
>Smart Cookies</
td
><
td
>Yes</
td
></
tr
>
<
tr
><
td
>Aug 1st, 2006</
td
><
td
>Anti-Java Cake</
td
><
td
>No</
td
></
tr
>
echo
$this -> Html -> tableCells ([
[ 'Jul 7th, 2007' , [ 'Best Brownies' , [ 'class' => 'highlight' ]] , 'Yes' ],
[ 'Jun 21st, 2007' , 'Smart Cookies' , 'Yes' ],
[ 'Aug 1st, 2006' , 'Anti-Java Cake' , [ 'No' , [ 'id' => 'special' ]]],
]);
Output:
<
tr
>
<
td
>
Jul 7th, 2007
</
td
>
336 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
<
td
class = "highlight" >
Best Brownies
</
td
>
<
td
>
Yes
</
td
>
</
tr
>
<
tr
>
<
td
>
Jun 21st, 2007
</
td
>
<
td
>
Smart Cookies
</
td
>
<
td
>
Yes
</
td
>
</
tr
>
<
tr
>
<
td
>
Aug 1st, 2006
</
td
>
<
td
>
Anti-Java Cake
</
td
>
<
td
id = "special" >
No
</
td
>
</
tr
>
echo
$this -> Html -> tableCells (
[
[ 'Red' , 'Apple' ],
[ 'Orange' , 'Orange' ],
[ 'Yellow' , 'Banana' ],
],
[ 'class' => 'darker' ]
);
Output:
<
tr
class = "darker" ><
td
>Red</
td
><
td
>Apple</
td
></
tr
>
<
tr
><
td
>Orange</
td
><
td
>Orange</
td
></
tr
>
<
tr
class = "darker" ><
td
>Yellow</
td
><
td
>Banana</
td
></
tr
>
Changing the Tags Output by HtmlHelper
Cake\View\Helper\HtmlHelper::setTemplates(
$templates)
The $templates parameter can be either a string file path to the PHP file containing the tags you want to load, or an array of templates to add/replace:
// Load templates from config/my_html.php
$this -> Html -> setTemplates ( 'my_html' );
// Load specific templates.
More About Views 337
CakePHP Cookbook Documentation, Release 3.5
$this -> Html -> setTemplates ([
'javascriptlink' => '<script src="{{url}}" type="text/javascript"{{attrs}}></
˓→ script>'
]);
When loading files of templates, your file should look like:
<?
php
return
[
'javascriptlink' => '<script src="{{url}}" type="text/javascript"{{attrs}}></
˓→ script>'
];
Warning: Template strings containing a percentage sign (%) need special attention, you should prefix this character with another percentage so it looks like %%. The reason is that internally templates are compiled to be used with sprintf(). Example: ‘<div style=”width:{{size}}%%”>{{content}}</div>’
Creating Breadcrumb Trails with HtmlHelper
Cake\View\Helper\HtmlHelper::addCrumb( string $name , string $link = null, mixed $options = null)
Cake\View\Helper\HtmlHelper::getCrumbs( string $separator = ‘»’ , string $startText = false)
Cake\View\Helper\HtmlHelper::getCrumbList( array $options = [] , $startText = false)
Many applications have breadcrumb trails to ease end user navigations. You can create a breadcrumb trail in your app with some help from HtmlHelper. To make bread crumbs, first the following in your layout template:
echo
$this -> Html -> getCrumbs ( ' > ' , 'Home' );
The $startText option can also accept an array. This gives more control over the generated first link:
echo
$this -> Html -> getCrumbs ( ' > ' , [
'text' => $this -> Html -> image ( 'home.png' ),
'url' => [ 'controller' => 'Pages' , 'action' => 'display' , 'home' ],
'escape' =>
false
]);
Any keys that are not text or url will be passed to
link()
as the $options parameter.
Now, in your view you’ll want to add the following to start the breadcrumb trails on each of the pages:
$this -> Html -> addCrumb ( 'Users' , '/users' );
$this -> Html -> addCrumb ( 'Add User' , [ 'controller' => 'Users' , 'action' => 'add' ]);
This will add the output of “Home > Users > Add User” in your layout where getCrumbs was added.
You can also fetch the crumbs formatted inside an HTML list:
echo
$this -> Html -> getCrumbList ();
As options you can use regular HTML parameter that fits in the <ul> (Unordered List) such as class and for the specific options, you have: separator (will be between the <li> elements), firstClass and lastClass like:
338 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
echo
$this -> Html -> getCrumbList (
[
'firstClass' =>
false
,
'lastClass' => 'active' ,
'class' => 'breadcrumb'
],
'Home'
);
This method uses Cake\View\Helper\HtmlHelper::tag() to generate list and its elements.
Works similar to
View\Helper\HtmlHelper::getCrumbs()
, so it uses options which every crumb was added
with.
You can use the $startText parameter to provide the first breadcrumb link/text.
This is useful when you always want to include a root link.
This option works the same as the $startText option for
View\Helper\HtmlHelper::getCrumbs()
Number
class Cake\View\Helper\NumberHelper(View $view, array $config = [])
The NumberHelper contains convenient methods that enable display numbers in common formats in your views. These methods include ways to format currency, percentages, data sizes, format numbers to specific precisions and also to give you more flexibility with formatting numbers.
All of these functions return the formatted number; they do not automatically echo the output into the view.
Formatting Currency Values
Cake\View\Helper\NumberHelper::currency( mixed $value , string $currency = null, array $options = [])
This method is used to display a number in common currency formats (EUR, GBP, USD). Usage in a view looks like:
// Called as NumberHelper
echo
$this -> Number -> currency ( $value , $currency );
// Called as Number
echo
Number :: currency ( $value , $currency );
The first parameter, $value, should be a floating point number that represents the amount of money you are expressing. The second parameter is a string used to choose a predefined currency formatting scheme:
$currency 1234.56, formatted by currency type
EUR C1.234,56
GBP £1,234.56
USD $1,234.56
The third parameter is an array of options for further defining the output. The following options are available:
More About Views 339
CakePHP Cookbook Documentation, Release 3.5
Option before after zero places precision locale
Description
Text to display before the rendered number.
Text to display after the rendered number.
The text to use for zero values; can be a string or a number. ie. 0, ‘Free!’.
Number of decimal places to use, ie. 2
Maximal number of decimal places to use, ie. 2
The locale name to use for formatting number, ie. “fr_FR”.
fractionSymbol String to use for fraction numbers, ie. ‘ cents’.
fractionPosition Either ‘before’ or ‘after’ to place the fraction symbol.
pattern useIntlCode
An ICU number pattern to use for formatting the number ie. #,###.00
Set to true to replace the currency symbol with the international currency code.
If $currency value is null , the
Cake\I18n\Number::defaultCurrency()
default currency will be retrieved from
Setting the Default Currency
Cake\View\Helper\NumberHelper::defaultCurrency(
$currency)
Setter/getter for the default currency.
This removes the need to always pass the currency to
Cake\I18n\Number::currency()
and change all currency outputs by setting other default. If $currency is set to false, it will clear the currently stored value. By default, it will retrieve the intl.default_locale if set and ‘en_US’ if not.
Formatting Floating Point Numbers
Cake\View\Helper\NumberHelper::precision( float $value
, int $precision = 3, array $options =
[])
This method displays a number with the specified amount of precision (decimal places). It will round in order to maintain the level of precision defined.
// Called as NumberHelper
echo
$this -> Number -> precision ( 456.91873645
, 2 );
// Outputs
456.92
// Called as Number
echo
Number :: precision ( 456.91873645
, 2 );
Formatting Percentages
Cake\View\Helper\NumberHelper::toPercentage( mixed $value , int $precision = 2, array $options = [])
Option Description multiply Boolean to indicate whether the value has to be multiplied by 100. Useful for decimal percentages.
Like
Cake\I18n\Number::precision()
, this method formats a number according to the supplied precision
(where numbers are rounded to meet the given precision). This method also expresses the number as a percentage and appends the output with a percent sign.
340 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
// Called as NumberHelper. Output: 45.69%
echo
$this -> Number -> toPercentage ( 45.691873645
);
// Called as Number. Output: 45.69%
echo
Number :: toPercentage ( 45.691873645
);
// Called with multiply. Output: 45.7%
echo
Number :: toPercentage ( 0.45691
, 1 , [
'multiply' =>
true
]);
Interacting with Human Readable Values
Cake\View\Helper\NumberHelper::toReadableSize( string $size)
This method formats data sizes in human readable forms. It provides a shortcut way to convert bytes to KB, MB, GB, and TB. The size is displayed with a two-digit precision level, according to the size of data supplied (i.e. higher sizes are expressed in larger terms):
// Called as NumberHelper
echo
$this -> Number -> toReadableSize ( 0 ); // 0 Byte
echo
$this -> Number -> toReadableSize ( 1024 ); // 1 KB
echo
$this -> Number -> toReadableSize ( 1321205.76
); // 1.26 MB
echo
$this -> Number -> toReadableSize ( 5368709120 ); // 5 GB
// Called as Number
echo
Number :: toReadableSize ( 0 ); // 0 Byte
echo
Number :: toReadableSize ( 1024 ); // 1 KB
echo
Number :: toReadableSize ( 1321205.76
); // 1.26 MB
echo
Number :: toReadableSize ( 5368709120 ); // 5 GB
Formatting Numbers
Cake\View\Helper\NumberHelper::format( mixed $value , array $options = [])
This method gives you much more control over the formatting of numbers for use in your views (and is used as the main method by most of the other NumberHelper methods). Using this method might looks like:
// Called as NumberHelper
$this -> Number -> format ( $value , $options );
// Called as Number
Number :: format ( $value , $options );
The $value parameter is the number that you are planning on formatting for output. With no $options supplied, the number 1236.334 would output as 1,236. Note that the default precision is zero decimal places.
The $options parameter is where the real magic for this method resides.
• If you pass an integer then this becomes the amount of precision or places for the function.
• If you pass an associated array, you can use the following keys:
More About Views 341
CakePHP Cookbook Documentation, Release 3.5
Option places
Description
Number of decimal places to use, ie. 2 precision Maximum number of decimal places to use, ie. 2 pattern locale before after
An ICU number pattern to use for formatting the number ie. #,###.00
The locale name to use for formatting number, ie. “fr_FR”.
Text to display before the rendered number.
Text to display after the rendered number.
Example:
// Called as NumberHelper
echo
$this -> Number -> format ( '123456.7890' , [
'places' => 2 ,
'before' => '¥ ' ,
'after' => ' !'
]);
// Output '¥ 123,456.79 !'
echo
$this -> Number -> format ( '123456.7890' , [
'locale' => 'fr_FR'
]);
// Output '123 456,79 !'
// Called as Number
echo
Number :: format ( '123456.7890' , [
'places' => 2 ,
'before' => '¥ ' ,
'after' => ' !'
]);
// Output '¥ 123,456.79 !'
echo
Number :: format ( '123456.7890' , [
'locale' => 'fr_FR'
]);
// Output '123 456,79 !'
Cake\View\Helper\NumberHelper::ordinal( mixed $value , array $options = [])
This method will output an ordinal number.
Examples:
echo
Number :: ordinal ( 1 );
// Output '1st'
echo
Number :: ordinal ( 2 );
// Output '2nd'
echo
Number :: ordinal ( 2 , [
'locale' => 'fr_FR'
]);
// Output '2e'
echo
Number :: ordinal ( 410 );
// Output '410th'
342 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Format Differences
Cake\View\Helper\NumberHelper::formatDelta( mixed $value , array $options = [])
This method displays differences in value as a signed number:
// Called as NumberHelper
$this -> Number -> formatDelta ( $value , $options );
// Called as Number
Number :: formatDelta ( $value , $options );
The $value parameter is the number that you are planning on formatting for output. With no $options supplied, the number 1236.334 would output as 1,236. Note that the default precision is zero decimal places.
The $options parameter takes the same keys as Number::format() itself:
Option places
Description
Number of decimal places to use, ie. 2 precision Maximum number of decimal places to use, ie. 2 locale before after
The locale name to use for formatting number, ie. “fr_FR”.
Text to display before the rendered number.
Text to display after the rendered number.
Example:
// Called as NumberHelper
echo
$this -> Number -> formatDelta ( '123456.7890' , [
'places' => 2 ,
'before' => '[' ,
'after' => ']'
]);
// Output '[+123,456.79]'
// Called as Number
echo
Number :: formatDelta ( '123456.7890' , [
'places' => 2 ,
'before' => '[' ,
'after' => ']'
]);
// Output '[+123,456.79]'
Warning: All symbols are UTF-8.
Paginator
class Cake\View\Helper\PaginatorHelper(View $view, array $config = [])
The PaginatorHelper is used to output pagination controls such as page numbers and next/previous links. It works in tandem with PaginatorComponent.
See also
Pagination
for information on how to create paginated datasets and do paginated queries.
More About Views 343
CakePHP Cookbook Documentation, Release 3.5
PaginatorHelper Templates
Internally PaginatorHelper uses a series of simple HTML templates to generate markup. You can modify these templates to customize the HTML generated by the PaginatorHelper.
Templates use {{var}} style placeholders. It is important to not add any spaces around the {{}} or the replacements will not work.
Loading Templates from a File
When adding the PaginatorHelper in your controller, you can define the ‘templates’ setting to define a template file to load. This allows you to customize multiple templates and keep your code DRY:
// In your AppView.php
public function
initialize ()
{
...
$this -> loadHelper ( 'Paginator' , [ 'templates' => 'paginator-templates' ]);
}
This will load the file located at config/paginator-templates.php. See the example below for how the file should look like. You can also load templates from a plugin using
plugin syntax
// In your AppView.php
public function
initialize ()
{
...
$this -> loadHelper ( 'Paginator' , [ 'templates' => 'MyPlugin.paginator-templates' ]);
}
Whether your templates are in the primary application or a plugin, your templates file should look something like:
return
[
'number' => '<a href="{{url}}">{{text}}</a>' ,
];
Changing Templates at Run-time
Cake\View\Helper\PaginatorHelper::setTemplates(
$templates)
This method allows you to change the templates used by PaginatorHelper at runtime. This can be useful when you want to customize templates for a particular method call:
// Read the current template value.
$result = $this -> Paginator -> getTemplates ( 'number' );
// Prior to 3.4
$result = $this -> Paginator -> templates ( 'number' );
// Change a template
$this -> Paginator -> setTemplates ([
'number' => '<em><a href="{{url}}">{{text}}</a></em>'
]);
344 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Warning: Template strings containing a percentage sign (%) need special attention, you should prefix this character with another percentage so it looks like %%. The reason is that internally templates are compiled to be used with sprintf(). Example: ‘<div style=”width:{{size}}%%”>{{content}}</div>’
Template Names
PaginatorHelper uses the following templates:
• nextActive The active state for a link generated by next().
• nextDisabled The disabled state for next().
• prevActive The active state for a link generated by prev().
• prevDisabled The disabled state for prev()
• counterRange The template counter() uses when format == range.
• counterPages The template counter() uses when format == pages.
• first The template used for a link generated by first().
• last The template used for a link generated by last()
• number The template used for a link generated by numbers().
• current The template used for the current page.
• ellipsis The template used for ellipses generated by numbers().
• sort The template for a sort link with no direction.
• sortAsc The template for a sort link with an ascending direction.
• sortDesc The template for a sort link with a descending direction.
Creating Sort Links
Cake\View\Helper\PaginatorHelper::sort( $key , $title = null, $options = [])
Parameters
• $key (string) – The name of the column that the recordset should be sorted.
• $title (string) – Title for the link. If $title is null, $key will be used converted to
“Title Case” format and used as the title.
• $options (array) – Options for sorting link.
Generates a sorting link. Sets querystring parameters for the sort and direction. Links will default to sorting by asc.
After the first click, links generated with sort() will handle direction switching automatically. If the resultset is sorted ‘asc’ by the specified key the returned link will sort by ‘desc’.
Accepted keys for $options:
• escape Whether you want the contents HTML entity encoded, defaults to true.
• model The model to use, defaults to PaginatorHelper::defaultModel().
• direction The default direction to use when this link isn’t active.
• lock Lock direction. Will only use the default direction then, defaults to false.
More About Views 345
CakePHP Cookbook Documentation, Release 3.5
Assuming you are paginating some posts, and are on page one:
echo
$this -> Paginator -> sort ( 'user_id' );
Output:
<
a
href = "/posts/index?page=1&sort=user_id&direction=asc" >User Id</
a
>
You can use the title parameter to create custom text for your link:
echo
$this -> Paginator -> sort ( 'user_id' , 'User account' );
Output:
<
a
href = "/posts/index?page=1&sort=user_id&direction=asc" >User account</
a
>
If you are using HTML like images in your links remember to set escaping off:
echo
$this -> Paginator -> sort (
'user_id' ,
'<em>User account</em>' ,
);
[ 'escape' =>
false
]
Output:
<
a
href = "/posts/index?page=1&sort=user_id&direction=asc" ><
em
>User account</
em
>
˓→
</
a
>
The direction option can be used to set the default direction for a link. Once a link is active, it will automatically switch directions like normal:
echo
$this -> Paginator -> sort ( 'user_id' ,
null
, [ 'direction' => 'desc' ]);
Output:
<
a
href = "/posts/index?page=1&sort=user_id&direction=desc" >User Id</
a
>
The lock option can be used to lock sorting into the specified direction:
echo
$this -> Paginator -> sort ( 'user_id' ,
null
, [ 'direction' => 'asc' , 'lock' =>
true
]);
Cake\View\Helper\PaginatorHelper::sortDir( string $model = null
, mixed $options = [])
Gets the current direction the recordset is sorted.
Cake\View\Helper\PaginatorHelper::sortKey( string $model = null , mixed $options = [])
Gets the current key by which the recordset is sorted.
Creating Page Number Links
Cake\View\Helper\PaginatorHelper::numbers(
$options = [])
Returns a set of numbers for the paged result set. Uses a modulus to decide how many numbers to show on each side of the current page By default 8 links on either side of the current page will be created if those pages exist. Links will not be generated for pages that do not exist. The current page is also not a link.
Supported options are:
346 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
• before Content to be inserted before the numbers.
• after Content to be inserted after the numbers.
• model Model to create numbers for, defaults to PaginatorHelper::defaultModel().
• modulus how many numbers to include on either side of the current page, defaults to 8.
• first Whether you want first links generated, set to an integer to define the number of ‘first’ links to generate.
Defaults to false. If a string is set a link to the first page will be generated with the value as the title:
echo
$this -> Paginator -> numbers ([ 'first' => 'First page' ]);
• last Whether you want last links generated, set to an integer to define the number of ‘last’ links to generate.
Defaults to false. Follows the same logic as the first option. There is a last()` method to be used separately as well if you wish.
While this method allows a lot of customization for its output. It is also ok to just call the method without any params.
echo
$this -> Paginator -> numbers ();
Using the first and last options you can create links to the beginning and end of the page set. The following would create a set of page links that include links to the first 2 and last 2 pages in the paged results:
echo
$this -> Paginator -> numbers ([ 'first' => 2 , 'last' => 2 ]);
Creating Jump Links
In addition to generating links that go directly to specific page numbers, you’ll often want links that go to the previous and next links, first and last pages in the paged data set.
Cake\View\Helper\PaginatorHelper::prev( $title = ‘<< Previous’
, $options = [])
Parameters
• $title (string) – Title for the link.
• $options (mixed) – Options for pagination link.
Generates a link to the previous page in a set of paged records.
$options supports the following keys:
•escape Whether you want the contents HTML entity encoded, defaults to true.
•model The model to use, defaults to PaginatorHelper::defaultModel().
•disabledTitle The text to use when the link is disabled. Defaults to the $title parameter.
A simple example would be:
echo
$this -> Paginator -> prev ( ' << ' .
__( 'previous' ));
If you were currently on the second page of posts, you would get the following:
<
li
class = "prev" >
<
a
rel = "prev" href = "/posts/index?page=1&sort=title&order=desc" >
<<
previous
</
a
>
</
li
>
More About Views 347
CakePHP Cookbook Documentation, Release 3.5
If there were no previous pages you would get:
<
li
class = "prev disabled" ><
span
>
<<
previous</
span
></
li
>
To change the templates used by this method see
PaginatorHelper Templates
Cake\View\Helper\PaginatorHelper::next( $title = ‘Next >>’ , $options = [])
This method is identical to prev() with a few exceptions. It creates links pointing to the next page instead of the previous one. It also uses next as the rel attribute value instead of prev
Cake\View\Helper\PaginatorHelper::first( $first = ‘<< first’
, $options = [])
Returns a first or set of numbers for the first pages. If a string is given, then only a link to the first page with the provided text will be created:
echo
$this -> Paginator -> first ( '< first' );
The above creates a single link for the first page. Will output nothing if you are on the first page. You can also use an integer to indicate how many first paging links you want generated:
echo
$this -> Paginator -> first ( 3 );
The above will create links for the first 3 pages, once you get to the third or greater page. Prior to that nothing will be output.
The options parameter accepts the following:
•model The model to use defaults to PaginatorHelper::defaultModel()
•escape Whether or not the text should be escaped. Set to false if your content contains HTML.
Cake\View\Helper\PaginatorHelper::last( $last = ‘last >>’ , $options = [])
This method works very much like the
first()
method. It has a few differences though. It will not generate any links if you are on the last page for a string values of $last. For an integer value of $last no links will be generated once the user is inside the range of last pages.
Creating Header Link Tags
PaginatorHelper can be used to create pagination link tags in your page <head> elements:
// Create next/prev links for the current model.
echo
$this -> Paginator -> meta ();
// Create next/prev & first/last links for the current model.
echo
$this -> Paginator -> meta ([ 'first' =>
true
, 'last' =>
true
]);
New in version 3.4.0: The first and last options were added in 3.4.0
Checking the Pagination State
Cake\View\Helper\PaginatorHelper::current( string $model = null)
Gets the current page of the recordset for the given model:
// Our URL is: http://example.com/comments/view/page:3
echo
$this -> Paginator -> current ( 'Comment' );
// Output is 3
348 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Cake\View\Helper\PaginatorHelper::hasNext( string $model = null)
Returns true if the given result set is not at the last page.
Cake\View\Helper\PaginatorHelper::hasPrev( string $model = null)
Returns true if the given result set is not at the first page.
Cake\View\Helper\PaginatorHelper::hasPage( string $model = null
, integer $page = 1)
Returns true if the given result set has the page number given by $page.
Cake\View\Helper\PaginatorHelper::total( string $model = null)
Returns the total number of pages for the provided model.
New in version 3.4.0.
Creating a Page Counter
Cake\View\Helper\PaginatorHelper::counter(
$options = [])
Returns a counter string for the paged result set. Using a provided format string and a number of options you can create localized and application specific indicators of where a user is in the paged data set.
There are a number of options for counter(). The supported ones are:
• format Format of the counter. Supported formats are ‘range’, ‘pages’ and custom. Defaults to pages which would output like ‘1 of 10’. In the custom mode the supplied string is parsed and tokens are replaced with actual values. The available tokens are:
– {{page}} - the current page displayed.
– {{pages}} - total number of pages.
– {{current}} - current number of records being shown.
– {{count}} - the total number of records in the result set.
– {{start}} - number of the first record being displayed.
– {{end}} - number of the last record being displayed.
– {{model}} - The pluralized human form of the model name.
If your model was ‘RecipePage’,
{{model}} would be ‘recipe pages’.
You could also supply only a string to the counter method using the tokens available. For example:
echo
$this -> Paginator -> counter (
'Page {{page}} of {{pages}}, showing {{current}} records out of
{{count}} total, starting on record {{start}}, ending on {{end}}'
);
Setting ‘format’ to range would output like ‘1 - 3 of 13’:
echo
$this -> Paginator -> counter ([
'format' => 'range'
]);
• model The name of the model being paginated, defaults to PaginatorHelper::defaultModel(). This is used in conjunction with the custom string on ‘format’ option.
More About Views 349
CakePHP Cookbook Documentation, Release 3.5
Generating Pagination URLs
Cake\View\Helper\PaginatorHelper::generateUrl( array $options = [] , $model = null, $full
= false)
By default returns a full pagination URL string for use in non-standard contexts (i.e. JavaScript).
echo
$this -> Paginator -> generateUrl ([ 'sort' => 'title' ]);
Creating a Limit Selectbox Control
Cake\View\Helper\PaginatorHelper::limitControl( array $limits = [] , $default = null, array
$options = [])
Create a dropdown control that changes the limit query parameter:
// Use the defaults.
echo
$this -> Paginator -> limitControl ();
// Define which limit options you want.
echo
$this -> Paginator -> limitControl ([ 25 => 25 , 50 => 50 ]);
// Custom limits and set the selected option
echo
$this -> Paginator -> limitControl ([ 25 => 25 , 50 => 50 ], $user -> perPage );
The generated form and control will automatically submit on change.
New in version 3.5.0: The limitControl() method was added in 3.5.0
Configuring Pagination Options
Cake\View\Helper\PaginatorHelper::options(
$options = [])
Sets all the options for the PaginatorHelper. Supported options are:
• url The URL of the paginating action. ‘url’ has a few sub options as well:
– sort The key that the records are sorted by.
– direction The direction of the sorting. Defaults to ‘ASC’.
– page The page number to display.
The above mentioned options can be used to force particular pages/directions. You can also append additional
URL content into all URLs generated in the helper:
$this -> Paginator -> options ([
'url' => [
'sort' => 'email' ,
'direction' => 'desc' ,
'page' => 6 ,
'lang' => 'en'
]
]);
The above adds the en route parameter to all links the helper will generate. It will also create links with specific sort, direction and page values. By default PaginatorHelper will merge in all of the current passed arguments and query string parameters.
350 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
• escape Defines if the title field for links should be HTML escaped. Defaults to true.
• model The name of the model being paginated, defaults to PaginatorHelper::defaultModel().
Example Usage
It’s up to you to decide how to show records to the user, but most often this will be done inside HTML tables.
The examples below assume a tabular layout, but the PaginatorHelper available in views doesn’t always need to be restricted as such.
See the details on PaginatorHelper
123 in the API. As mentioned, the PaginatorHelper also offers sorting features which can be integrated into your table column headers:
<!-- src/Template/Posts/index.ctp -->
<table>
<tr>
<th> <?
= $this -> Paginator -> sort ( 'id' , 'ID' ) ?> </th>
<th> <?
= $this -> Paginator -> sort ( 'title' , 'Title' ) ?> </th>
</tr>
<?php foreach ( $recipes
as
$recipe ) : ?>
<tr>
<td> <?
= $recipe -> id ?> </td>
<td> <?
= h( $recipe -> title ) ?> </td>
</tr>
<?php endforeach ; ?>
</table>
The links output from the sort() method of the PaginatorHelper allow users to click on table headers to toggle the sorting of the data by a given field.
It is also possible to sort a column based on associations:
<table>
<tr>
<th> <?
= $this -> Paginator -> sort ( 'title' , 'Title' ) ?> </th>
<th> <?
= $this -> Paginator -> sort ( 'Authors.name' , 'Author' ) ?> </th>
</tr>
<?php foreach ( $recipes
as
$recipe ) : ?>
<tr>
</tr>
<?php endforeach ; ?>
</table>
<td> <?
= h( $recipe -> title ) ?> </td>
<td> <?
= h( $recipe -> name ) ?> </td>
The final ingredient to pagination display in views is the addition of page navigation, also supplied by the Pagination-
Helper:
// Shows the page numbers
<?= $this -> Paginator -> numbers () ?>
// Shows the next and previous links
<?
= $this -> Paginator -> prev ( '« Previous' ) ?>
<?
= $this -> Paginator -> next ( 'Next »' ) ?>
123 https://api.cakephp.org/3.x/class-Cake.View.Helper.PaginatorHelper.html
More About Views 351
CakePHP Cookbook Documentation, Release 3.5
// Prints X of Y, where X is current page and Y is number of pages
<?
= $this -> Paginator -> counter () ?>
The wording output by the counter() method can also be customized using special markers:
<?= $this -> Paginator -> counter ([
'format' => 'Page {{page}} of {{pages}}, showing {{current}} records out of
{{count}} total, starting on record {{start}}, ending on {{end}}'
]) ?>
Paginating Multiple Results
If you are
paginating multiple queries
you’ll need to set the model option when generating pagination related elements. You can either use the model option on every method call you make to PaginatorHelper, or use options() to set the default model:
// Pass the model option
echo
$this -> Paginator -> sort ( 'title' , [ 'model' => 'Articles' ]);
// Set the default model.
$this -> Paginator -> options ([ 'defaultModel' => 'Articles' ]);
echo
$this -> Paginator -> sort ( 'title' );
By using the model option, PaginatorHelper will automatically use the scope defined in when the query was paginated.
New in version 3.3.0: Multiple Pagination was added in 3.3.0
Rss
class Cake\View\Helper\RssHelper(View $view, array $config = [])
The RssHelper makes generating XML for RSS feeds
124 easy.
Deprecated since version 3.5.0: RssHelper is deprecated as of 3.5.0, and will be removed in 4.0.0
Creating an RSS Feed with the RssHelper
This example assumes you have a Articles Controller, Articles Table and an Article Entity already created and want to make an alternative view for RSS.
Creating an XML/RSS version of articles/index is a snap with CakePHP. After a few simple steps you can simply append the desired extension .rss to articles/index making your URL articles/index.rss. Before we jump too far ahead trying to get our webservice up and running we need to do a few things. First extensions parsing needs to be activated, this is done in config/routes.php:
Router :: extensions ( 'rss' );
In the call above we’ve activated the .rss extension. When using
Cake\Routing\Router::extensions()
you can pass a string or an array of extensions as first argument. This will activate each extension/content-type for use in your application. Now when the address articles/index.rss is requested you will get an XML version of your articles/index
. However, first we need to edit the controller to add in the rss-specific code.
124 https://en.wikipedia.org/wiki/RSS
352 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Controller Code
It is a good idea to add RequestHandler to your ArticlesController’s initialize() method. This will allow a lot of automagic to occur:
public function
initialize ()
{
parent
:: initialize ();
$this -> loadComponent ( 'RequestHandler' );
}
Before we can make an RSS version of our articles/index we need to get a few things in order.
It may be tempting to put the channel metadata in the controller action and pass it to your view using the
Cake\Controller\Controller::set()
method but this is inappropriate. That information can also go in the view. That will come later though, for now if you have a different set of logic for the data used to make the RSS feed and the data for the HTML view you can use the Cake\Controller\Component\RequestHandler::isRss() method, otherwise your controller can stay the same:
// Modify the Posts Controller action that corresponds to
// the action which deliver the rss feed, which is the
// Index action in our example.
public function
index ()
{
if
( $this -> RequestHandler -> isRss () ) {
$articles = $this -> Articles
-> find ()
-> limit ( 20 )
-> order ([ 'created' => 'desc' ]);
$this -> set ( compact ( 'articles' ));
}
else
{
// this is not an Rss request, so deliver
// data used by website's interface.
$this -> paginate = [
'order' => [ 'created' => 'desc' ],
'limit' => 10
];
$this -> set ( 'articles' , $this -> paginate ( $this -> Articles ));
$this -> set ( '_serialize' , [ 'articles' ]);
}
}
With all the View variables set we need to create an rss layout.
Layout
An Rss layout is very simple, put the following contents in src/Template/Layout/rss/default.ctp:
if
( !
isset ( $documentData )) {
$documentData = [];
}
if
( !
isset ( $channelData )) {
$channelData = [];
}
if
( !
isset ( $channelData [ 'title' ])) {
$channelData [ 'title' ] = $this -> fetch ( 'title' );
More About Views 353
CakePHP Cookbook Documentation, Release 3.5
}
$channel = $this -> Rss -> channel ([], $channelData , $this -> fetch ( 'content' ));
echo
$this -> Rss -> document ( $documentData , $channel );
It doesn’t look like much but thanks to the power in the RssHelper it’s doing a lot of lifting for us. We haven’t set
$documentData or $channelData in the controller, however in CakePHP your views can pass variables back to the layout. Which is where our $channelData array will come from setting all of the meta data for our feed.
Next up is view file for my articles/index.
Much like the layout file we created, we need to create a src/Template/Posts/rss/ directory and create a new index.ctp inside that folder. The contents of the file are below.
View
Our view, located at src/Template/Posts/rss/index.ctp, begins by setting the $documentData and
$channelData variables for the layout, these contain all the metadata for our RSS feed. This is done by using the
Cake\View\View::set()
method which is analogous to the
Cake\Controller\Controller::set()
method. Here though we are passing the channel’s metadata back to the layout:
$this -> set ( 'channelData' , [
'title' => __( "Most Recent Posts" ),
'link' => $this -> Url -> build ( '/' ,
true
),
'description' => __( "Most recent posts." ),
'language' => 'en-us'
]);
The second part of the view generates the elements for the actual records of the feed. This is accomplished by looping through the data that has been passed to the view ($items) and using the RssHelper::item() method. The other method you can use, RssHelper::items() which takes a callback and an array of items for the feed. The callback method is usually called transformRss(). There is one downfall to this method, which is that you cannot use any of the other helper classes to prepare your data inside the callback method because the scope inside the method does not include anything that is not passed inside, thus not giving access to the TimeHelper or any other helper that you may need. The RssHelper::item() transforms the associative array into an element for each key value pair.
Note: You will need to modify the $link variable as appropriate to your application. You might also want to use a
virtual property
in your Entity.
foreach
( $articles
as
$article ) {
$created = strtotime ( $article -> created );
$link = [
'controller' => 'Articles' ,
'action' => 'view' ,
'year' => date ( 'Y' , $created ),
'month' => date ( 'm' , $created ),
'day' => date ( 'd' , $created ),
'slug' => $article -> slug
];
// Remove & escape any HTML to make sure the feed content will validate.
$body = h( strip_tags ( $article -> body ));
$body = $this -> Text -> truncate ( $body , 400 , [
'ending' => '...' ,
'exact' =>
true
,
'html' =>
true
,
354 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
]);
echo
$this -> Rss -> item ([], [
'title' => $article -> title ,
'link' => $link ,
'guid' => [ 'url' => $link , 'isPermaLink' => 'true' ],
'description' => $body ,
'pubDate' => $article -> created
]);
}
You can see above that we can use the loop to prepare the data to be transformed into XML elements. It is important to filter out any non-plain text characters out of the description, especially if you are using a rich text editor for the body of your blog. In the code above we used strip_tags() and
h()
to remove/escape any XML special characters from the content, as they could cause validation errors. Once we have set up the data for the feed, we can then use the
RssHelper::item() method to create the XML in RSS format. Once you have all this setup, you can test your
RSS feed by going to your site /posts/index.rss and you will see your new feed. It is always important that you validate your RSS feed before making it live. This can be done by visiting sites that validate the XML such as
Feed Validator or the w3c site at http://validator.w3.org/feed/ .
Note: You may need to set the value of ‘debug’ in your core configuration to false to get a valid feed, because of the various debug information added automagically under higher debug settings that break XML syntax or feed validation rules.
Session
class Cake\View\Helper\SessionHelper(View $view, array $config = [])
Deprecated since version 3.0.0: The SessionHelper is deprecated in 3.x. Instead you should use either the
FlashHelper
or
access the session via the request
As a natural counterpart to the Session object, the Session Helper replicates most of the object’s functionality and makes it available in your view.
The major difference between the SessionHelper and the Session object is that the helper does not have the ability to write to the session.
As with the session object, data is read by using
dot notation
array structures:
[ 'User' => [
'username' => '[email protected]'
]];
Given the previous array structure, the node would be accessed by User.username, with the dot indicating the nested array. This notation is used for all SessionHelper methods wherever a $key is used.
Cake\View\Helper\SessionHelper::read( string $key)
Return type mixed
Read from the Session. Returns a string or array depending on the contents of the session.
Cake\View\Helper\SessionHelper::check( string $key)
Return type boolean
Check to see whether a key is in the Session. Returns a boolean representing the key’s existence.
More About Views 355
CakePHP Cookbook Documentation, Release 3.5
Text
class Cake\View\Helper\TextHelper(View $view, array $config = [])
The TextHelper contains methods to make text more usable and friendly in your views. It aids in enabling links, formatting URLs, creating excerpts of text around chosen words or phrases, highlighting key words in blocks of text, and gracefully truncating long stretches of text.
Linking Email addresses
Cake\View\Helper\TextHelper::autoLinkEmails( string $text , array $options = [])
Adds links to the well-formed email addresses in $text, according to any options defined in $options (see
HtmlHelper::link()
$myText = 'For more information regarding our world-famous ' .
'pastries and desserts, contact [email protected]' ;
$linkedText = $this -> Text -> autoLinkEmails ( $myText );
Output:
For
more information regarding our world famous pastries
and
desserts, contact < a href = "mailto:[email protected]" > info @ example .
com </ a >
This method automatically escapes its input. Use the escape option to disable this if necessary.
Linking URLs
Cake\View\Helper\TextHelper::autoLinkUrls( string $text , array $options = [])
Same as autoLinkEmails(), only this method searches for strings that start with https, http, ftp, or nntp and links them appropriately.
This method automatically escapes its input. Use the escape option to disable this if necessary.
Linking Both URLs and Email Addresses
Cake\View\Helper\TextHelper::autoLink( string $text , array $options = [])
Performs the functionality in both autoLinkUrls() and autoLinkEmails() on the supplied $text. All
URLs and emails are linked appropriately given the supplied $options.
This method automatically escapes its input. Use the escape option to disable this if necessary.
Converting Text into Paragraphs
Cake\View\Helper\TextHelper::autoParagraph( string $text)
Adds proper <p> around text where double-line returns are found, and <br> where single-line returns are found.
$myText = 'For more information regarding our world-famous pastries and desserts.
contact [email protected]' ;
$formattedText = $this -> Text -> autoParagraph ( $myText );
356 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Output:
< p >
For
more information < br /> regarding our world famous pastries
and
desserts .</ p >
< p > contact info @ example .
com </ p >
Highlighting Substrings
Cake\View\Helper\TextHelper::highlight( string $haystack
, string $needle, array $options =
[])
Highlights $needle in $haystack using the $options['format'] string specified or a default string.
Options:
• format string - The piece of HTML with the phrase that will be highlighted
• html bool - If true, will ignore any HTML tags, ensuring that only the correct text is highlighted
Example:
// Called as TextHelper
echo
$this -> Text -> highlight (
$lastSentence ,
'using' ,
[ 'format' => '<span class="highlight">\1</span>' ]
);
// Called as Text
use
Cake\Utility\Text;
echo
Text :: highlight (
$lastSentence ,
'using' ,
[ 'format' => '<span class="highlight">\1</span>' ]
);
Output:
Highlights $needle in $haystack < span class = "highlight" > using </ span > the
$options [ 'format' ] string specified
or
a
default
string .
Removing Links
Cake\View\Helper\TextHelper::stripLinks(
$text)
Strips the supplied $text of any HTML links.
Truncating Text
Cake\View\Helper\TextHelper::truncate( string $text , int $length = 100, array $options)
If $text is longer than $length, this method truncates it at $length and adds a suffix consisting of
'ellipsis'
, if defined. If 'exact' is passed as false, the truncation will occur at the first whitespace after the point at which $length is exceeded. If 'html' is passed as true, HTML tags will be respected and will not be cut off.
More About Views 357
CakePHP Cookbook Documentation, Release 3.5
$options is used to pass all extra parameters, and has the following possible keys by default, all of which are optional:
[
'ellipsis' => '...' ,
'exact' =>
true
,
'html' =>
false
]
Example:
// Called as TextHelper
echo
$this -> Text -> truncate (
'The killer crept forward and tripped on the rug.' ,
22 ,
[
'ellipsis' => '...' ,
'exact' =>
false
]
);
// Called as Text
use
Cake\Utility\Text;
echo
Text :: truncate (
'The killer crept forward and tripped on the rug.' ,
22 ,
[
'ellipsis' => '...' ,
'exact' =>
false
]
);
Output:
The killer crept ...
Truncating the Tail of a String
Cake\View\Helper\TextHelper::tail( string $text , int $length = 100, array $options)
If $text is longer than $length, this method removes an initial substring with length consisting of the difference and prepends a prefix consisting of 'ellipsis', if defined. If 'exact' is passed as false, the truncation will occur at the first whitespace prior to the point at which truncation would otherwise take place.
$options is used to pass all extra parameters, and has the following possible keys by default, all of which are optional:
[
'ellipsis' => '...' ,
'exact' =>
true
]
Example:
$sampleText = 'I packed my bag and in it I put a PSP, a PS3, a TV, ' .
'a C# program that can divide by zero, death metal t-shirts'
358 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
// Called as TextHelper
echo
$this -> Text -> tail (
$sampleText ,
70 ,
[
'ellipsis' => '...' ,
'exact' =>
false
]
);
// Called as Text
use
Cake\Utility\Text;
echo
Text :: tail (
$sampleText ,
70 ,
[
'ellipsis' => '...' ,
'exact' =>
false
]
);
Output:
...
a TV, a C # program that can divide by zero, death metal t-shirts
Extracting an Excerpt
Cake\View\Helper\TextHelper::excerpt( string $haystack , string $needle, integer $radius=100, string $ellipsis=”...”)
Extracts an excerpt from $haystack surrounding the $needle with a number of characters on each side determined by $radius, and prefix/suffix with $ellipsis. This method is especially handy for search results. The query string or keywords can be shown within the resulting document.
// Called as TextHelper
echo
$this -> Text -> excerpt ( $lastParagraph , 'method' , 50 , '...' );
// Called as Text
use
Cake\Utility\Text;
echo
Text :: excerpt ( $lastParagraph , 'method' , 50 , '...' );
Output:
...
by $radius ,
and
prefix / suffix with $ellipsis .
This
method is especially handy
for
search results .
The query ...
Converting an Array to Sentence Form
Cake\View\Helper\TextHelper::toList( array $list
, $and=’and’, $separator=’, ‘)
Creates a comma-separated list where the last two items are joined with ‘and’:
More About Views 359
CakePHP Cookbook Documentation, Release 3.5
$colors = [ 'red' , 'orange' , 'yellow' , 'green' , 'blue' , 'indigo' , 'violet' ];
// Called as TextHelper
echo
$this -> Text -> toList ( $colors );
// Called as Text
use
Cake\Utility\Text;
echo
Text :: toList ( $colors );
Output: red, orange, yellow, green, blue, indigo
and
violet
Time
class Cake\View\Helper\TimeHelper(View $view, array $config = [])
The TimeHelper allows for the quick processing of time related information. The TimeHelper has two main tasks that it can perform:
1. It can format time strings.
2. It can test time.
Using the Helper
A common use of the TimeHelper is to offset the date and time to match a user’s time zone. Lets use a forum as an example.
Your forum has many users who may post messages at any time from any part of the world. An easy way to manage the time is to save all dates and times as GMT+0 or UTC. Uncomment the line date_default_timezone_set('UTC'); in config/bootstrap.php to ensure your application’s time zone is set to GMT+0.
Next add a time zone field to your users table and make the necessary modifications to allow your users to set their time zone. Now that we know the time zone of the logged in user we can correct the date and time on our posts using the TimeHelper:
echo
$this -> Time -> format (
$post -> created ,
\IntlDateFormatter :: FULL ,
null
,
);
$user -> time_zone
// Will display 'Saturday, August 22, 2011 at 11:53:00 PM GMT'
// for a user in GMT+0. While displaying,
// 'Saturday, August 22, 2011 at 03:53 PM GMT-8:00'
// for a user in GMT-8
Most of TimeHelper’s features are intended as backwards compatible interfaces for applications that are upgrading from older versions of CakePHP. Because the ORM returns
Cake\I18n\Time
instances for every timestamp and datetime column, you can use the methods there to do most tasks. For example, to read about the accepted formatting strings take a look at the Cake\I18n\Time::i18nFormat()
125 method.
125 https://api.cakephp.org/3.x/class-Cake.I18n.Time.html#_i18nFormat
360 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
Url
class Cake\View\Helper\UrlHelper(View $view, array $config = [])
The UrlHelper makes it easy for you to generate URL’s from your other helpers. It also gives you a single place to customize how URLs are generated by overriding the core helper with an application one. See the
Aliasing Helpers
section for how to do this.
Generating URLs
Cake\View\Helper\UrlHelper::build( mixed $url = null , boolean|array $full = false)
Returns a URL pointing to a combination of controller and action. If $url is empty, it returns the REQUEST\_URI, otherwise it generates the URL for the controller and action combo. If full is true, the full base URL will be prepended to the result:
echo
$this -> Url -> build ([
"controller" => "Posts" ,
"action" => "view" ,
"bar"
]);
// Output
/ posts / view / bar
Here are a few more usage examples:
URL with extension:
echo
$this -> Url -> build ([
"controller" => "Posts" ,
"action" => "list" ,
"_ext" => "rss"
]);
// Output
/ posts /
list
.
rss
URL (starting with ‘/’) with the full base URL prepended:
echo
$this -> Url -> build ( '/posts' ,
true
);
// Output http :// somedomain .
com / posts
URL with GET params and fragment anchor:
echo
$this -> Url -> build ([
"controller" => "Posts" ,
"action" => "search" ,
"?" => [ "foo" => "bar" ],
"#" => "first"
]);
// Output
/ posts / search ?
foo = bar #first
More About Views 361
CakePHP Cookbook Documentation, Release 3.5
The above example uses the ? key which is useful when you want to be explicit about the query string parameters you are using, or if you want a query string parameter that shares a name with one of your route placeholders.
URL for named route:
echo
$this -> Url -> build ([ '_name' => 'product-page' , 'slug' => 'i-m-slug' ]);
// Assuming route is setup like:
// $router->connect(
//
//
'/products/:slug',
[
//
//
//
'controller' => 'Products',
'action' => 'view'
//
//
//
// );
],
[
]
'_name' => 'product-page'
/ products / i m slug
The 2nd parameter allows you to define options controlling HTML escaping, and whether or not the base path should be added:
$this -> Url -> build ( '/posts' , [
'escape' =>
false
,
'fullBase' =>
true
]);
New in version 3.3.5: build() accepts an array as the 2nd argument as of 3.3.5
If you are generating URLs for CSS, Javascript or image files there are helper methods for each of these asset types:
// Outputs /img/icon.png
$this -> Url -> image ( 'icon.png' );
// Outputs /js/app.js
$this -> Url -> script ( 'app.js' );
// Outputs /css/app.css
$this -> Url -> css ( 'app.css' );
New in version 3.2.4: The asset helper methods were added in 3.2.4.
For further information check Router::url
126 in the API.
Configuring Helpers
You load helpers in CakePHP by declaring them in a view class. An AppView class comes with every CakePHP application and is the ideal place to load helpers:
class AppView extends
View
{
public function
initialize ()
{
parent
:: initialize ();
$this -> loadHelper ( 'Html' );
$this -> loadHelper ( 'Form' );
126 https://api.cakephp.org/3.x/class-Cake.Routing.Router.html#_url
362 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
$this -> loadHelper ( 'Flash' );
}
}
To load helpers from plugins use the
plugin syntax
used elsewhere in CakePHP:
$this -> loadHelper ( 'Blog.Comment' );
You don’t have to explicitly load Helpers that come from CakePHP or your application. 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. For example, view templates in the ‘Blog’ plugin, can lazily load helpers from the same plugin.
Conditionally Loading Helpers
You can use the current action name to conditionally load helpers:
class AppView extends
View
{
public function
initialize ()
{
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 (Event $event )
{
parent
:: beforeRender ( $event );
$this -> viewBuilder () -> helpers ([ 'MyHelper' ]);
}
}
Configuration options
You can pass configuration options to helpers. These options can be used to set attribute values or modify the behavior of a helper:
namespace
App\View\Helper;
use
Cake\View\Helper;
use
Cake\View\View;
class AwesomeHelper extends
Helper
More About Views 363
CakePHP Cookbook Documentation, Release 3.5
{
// initialize() hook is available since 3.2. For prior versions you can
// override the constructor if required.
public function
initialize (
array
$config )
{ debug( $config );
}
}
Options can be specified when declaring helpers in controller as shown:
namespace
App\Controller;
use
App\Controller\AppController;
class AwesomeController extends
AppController
{
public
$helpers = [ 'Awesome' => [ 'option1' => 'value1' ]];
}
By default all configuration options will be merged with the $_defaultConfig property. This property should define the default values of any configuration your helper requires. For example:
namespace
App\View\Helper;
use
Cake\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 the default values during construction and the merged data will be set to _config. You can use the config() method to read runtime configuration:
// Read the errorClass config option.
$class = $this -> Awesome -> config ( 'errorClass' );
Using helper configuration allows you to declaratively configure your helpers and keep configuration logic out of your controller actions. If you have configuration 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 (Event $event )
{
parent
:: beforeRender ( $event );
$builder = $this -> viewBuilder ();
364 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
}
}
$builder -> helpers ([
'CustomStuff' => $this -> _getCustomStuffConfig (),
]);
Aliasing Helpers
One common setting to use is the className option, which allows you to create aliased helpers in your views.
This feature is useful when you want to replace $this->Html or another common Helper reference with a custom implementation:
// src/View/AppView.php
class AppView extends
View
{
public function
initialize ()
{
$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.
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 you were using the HtmlHelper you would be able to access it by doing the following:
echo
$this -> Html -> css ( 'styles' );
The above would call the css() method on the HtmlHelper.
You can access any loaded helper using
$this->{$helperName}
.
Loading Helpers On The Fly
There may be situations where you need to dynamically load a helper from inside a view. You can use the view’s
Cake\View\HelperRegistry to do this:
More About Views 365
CakePHP Cookbook Documentation, Release 3.5
// Either one works.
$mediaHelper = $this -> loadHelper ( 'Media' , $mediaConfig );
$mediaHelper = $this -> helpers () -> load ( 'Media' , $mediaConfig );
The HelperRegistry is a
registry
and supports the registry API used elsewhere in CakePHP.
Callback Methods
Helpers feature several callbacks that allow you to augment the view rendering process. See the
Helper Class
and the
Events 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.
$this->loadHelper('Link');
.
You’ll also want to extend Helper to ensure things work correctly:
For example:
/* 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 do so, you can specify helpers you wish to use with a $helpers array, formatted just 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 )
{
366 Chapter 11. Views
CakePHP Cookbook Documentation, Release 3.5
}
}
// 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 can load it in your views:
class AppView extends
View
{
public function
initialize ()
{
parent
:: initialize ();
$this -> loadHelper ( 'Link' );
}
}
Once your helper has been loaded, you can use it in your views by accessing the matching 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 not specifically 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:
class AwesomeHelper extends
Helper
{
public
$helpers = [ 'Html' ];
public
someMethod()
{
// set meta description
echo
$this -> Html -> meta (
'description' , $this -> _View -> get ( 'metaDescription' ), [ 'block' => 'meta' ]
);
}
}
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:
More About Views 367
CakePHP Cookbook Documentation, Release 3.5
class AwesomeHelper extends
Helper
{
public
someFunction()
{
// output directly in your helper
echo
$this -> _View -> element (
'/path/to/element' ,
[ 'foo' => 'bar' , 'bar' => 'foo' ]
);
// or return it to your view
return
$this -> _View -> element (
'/path/to/element' ,
[ 'foo' => 'bar' , 'bar' => 'foo' ]
);
}
}
Helper Class
class Helper
Callbacks
By implementing a callback method in a helper, CakePHP will automatically subscribe your helper to the relevant event. Unlike previous versions of CakePHP you should not call parent in your callbacks, as the base Helper class does 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 to change 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 method but before the controller renders view and layout. Receives the file being rendered as an argument.
Helper::afterRender( Event $event , $viewFile)
Is called after the view has been rendered but before layout rendering has started.
Helper::beforeLayout( Event $event
, $layoutFile)
Is called before layout rendering starts. Receives the layout filename as an argument.
Helper::afterLayout(
Event $event , $layoutFile)
Is called after layout rendering is complete. Receives the layout filename as an argument.
368 Chapter 11. Views
डाउनलोड
विज्ञापन