Views. CakePHP CakePHP
विज्ञापन
विज्ञापन
CHAPTER 5
Views
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 PDFs 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
• To serve protected files, or dynamically generated files, you can use
• To create multiple themed views, you can use
View Templates
The view layer of CakePHP is how you speak to your users. Most of the time your views will be showing
(X)HTML documents to browsers, but you might also need to serve AMF data to a Flash object, reply to a remote application via SOAP, or output a CSV file for a user.
By default CakePHP view files are written in plain PHP and have a default extension of .ctp (CakePHP Template). These files contain all the presentational logic needed to get the data it received from the controller in a format that is ready for the audience you’re serving to. If you’d prefer using a templating language like
Twig, or Smarty, a subclass of View will bridge your templating language and CakePHP.
A view file is stored in /app/View/, in a subfolder named after the controller that uses the file. It has a filename corresponding to its action. For example, the view file for the Products controller’s “view()” action would normally be found in /app/View/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: Views are the part of the page that is unique to the action being run. They form the meat of your application’s response.
• elements: smaller, reusable bits of view code. Elements are usually rendered inside views.
85
CakePHP Cookbook Documentation, Release 2.x
• layouts: view 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.
Extending Views
New in version 2.1.
View extending allows you to wrap one view in another. Combining this with
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:
// app/View/Common/view.ctp
<h1> <?php echo $this -> fetch ( 'title' ); ?> </h1>
<?php echo $this -> fetch ( 'content' ); ?>
<div class="actions">
<h3>Related actions</h3>
<ul>
<?php echo $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:
<?php
// app/View/Posts/view.ctp
$this -> extend ( '/Common/view' );
$this -> assign ( 'title' , $post );
$this -> start ( 'sidebar' );
?>
<li>
<?php
echo
$this -> Html -> link ( 'edit' ,
array
(
'action' => 'edit' ,
$post [ 'Post' ][ 'id' ]
)); ?>
</li>
<?php
$this -> end (); ?>
// The remaining content will be available as the 'content' block
// in the parent view.
<?php echo h( $post [ 'Post' ][ 'body' ]);
86 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
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.
Note: You should avoid using content as a block name in your application. CakePHP uses this for uncaptured content in extended views.
Using view blocks
New in version 2.1.
View blocks replace $scripts_for_layout and 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() 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 -> append ( 'sidebar' );
echo
$this -> element ( 'sidebar/popular_topics' );
$this -> end ();
You can also append into a block using start() multiple times. assign() can be used to clear or overwrite a block at any time:
// Clear the previous content from the sidebar block.
$this -> assign ( 'sidebar' , '' );
In 2.3, a few new methods were added for working with blocks. The prepend() method was added to prepend content to an existing block:
// Prepend to sidebar
$this -> prepend ( 'sidebar' , 'this content goes on top of sidebar' );
Using view blocks 87
CakePHP Cookbook Documentation, Release 2.x
The method startIfEmpty() can be used to start a block only if it is empty or undefined. If the block already exists, the captured content will be discarded. This is useful when you want to conditionally define default content for a block if it does not already exist:
// In a view file.
// Create a navbar block
$this->startIfEmpty('navbar'); echo $this->element('navbar'); echo $this->element('notifications');
$this->end();
// In a parent view/layout
<?php
$this -> startIfEmpty ( 'navbar' ); ?>
<p>If the block is not defined by now - show this instead</p>
<?php
$this -> end (); ?>
// Somewhere later in the parent view/layout echo $this->fetch('navbar');
In the above example, the navbar block will only contain the content added in the first section. Since the block was defined in the child view, the default content with the <p> tag will be discarded.
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
New in version 2.1.
You can display blocks using the fetch() method. fetch() will safely output a block, returning ‘’ if a block does not exist:
echo
$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 app/View/Layouts/default.ctp
<?php if ( $this -> fetch ( 'menu' )) : ?>
<div class="menu">
<h3>Menu options</h3>
<?php echo $this -> fetch ( 'menu' ); ?>
</div>
<?php endif ; ?>
As of 2.3.0, you can also provide a default value for a block should it not have any content. This allows you to easily add placeholder content for empty states. You can provide a default value using the second argument:
<div class="shopping-cart">
<h3>Your Cart</h3>
88 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
<?php echo $this -> fetch ( 'cart' , 'Your cart is empty' ); ?>
</div>
Changed in version 2.3: The $default argument was added in 2.3.
Using blocks for script and CSS files
New in version 2.1.
Blocks replace the deprecated $scripts_for_layout layout variable. Instead you should use blocks.
The
ties into view blocks, and its
methods each update a block with the same name when used with the inline = false option:
<?php
// In your view file
$this -> Html -> script ( 'carousel' ,
array
( 'inline' =>
false
));
$this -> Html -> css ( 'carousel' ,
array
( 'inline' =>
false
));
?>
// In your layout file.
<!DOCTYPE html>
<html lang="en">
<head>
<title> <?php echo $this -> fetch ( 'title' ); ?> </title>
<?php echo $this -> fetch ( 'script' ); ?>
<?php echo $this -> fetch ( 'css' ); ?>
</head>
// Rest of the layout follows
The
also allows you to control which block the scripts and CSS go to:
// In your view
$this -> Html -> script ( 'carousel' ,
array
( 'block' => 'scriptBottom' ));
// In your layout
echo
$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 /app/View/Layouts/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 /app/View/Layouts. 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:
Layouts 89
CakePHP Cookbook Documentation, Release 2.x
<!DOCTYPE html>
<html lang="en">
<head>
<title> <?php echo $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 -->
<?php echo $this -> fetch ( 'content' ); ?>
<!-- Add a footer to each displayed page -->
<div id="footer">...</div>
</body>
</html>
Note: Prior to version 2.1, method fetch() was not available, fetch(’content’) is a replacement for
$content_for_layout and lines fetch(’meta’), fetch(’css’) and fetch(’script’) are contained in the $scripts_for_layout variable in version 2.0
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.
Note: When using
or
in view files, specify ‘false’ for the ‘inline’ option 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.
$title_for_layout contains the page title. This variable is generated automatically, but you can override it by setting it in your controller/view as you would any other view variable.
Note: The $title_for_layout is deprecated as of 2.5, use $this->fetch(’title’) in your layout and $this->assign(’title’, ’page title’) instead.
You can create as many layouts as you wish: just place them in the app/View/Layouts directory, and switch between them inside of your controller actions using the controller or view’s
property:
90 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
// From a controller
public function
admin_view () {
// Stuff
$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:
class UsersController extends
AppController {
public function
view_active () {
$this -> set ( 'title_for_layout' , 'View Active Users' );
$this -> layout = 'default_small_ad' ;
}
public function
view_image () {
$this -> layout = 'image' ;
// Output user image
}
}
CakePHP features two core layouts (besides CakePHP’s default layout) you can use in your own application:
‘ajax’ and ‘flash’. 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 fully-rendered interface.) The flash layout is used for messages shown by
method.
Three other layouts, xml, js, and rss, exist in the core for a quick and easy way to serve up content that isn’t text/html.
Using layouts from plugins
New in version 2.1.
If you want to use a layout that exists in a plugin, you can use
. For example, to use the contact
layout from the Contacts plugin:
class UsersController extends
AppController {
public function
view_active () {
$this -> layout = 'Contacts.contact' ;
}
}
Elements
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,
Elements 91
CakePHP Cookbook Documentation, Release 2.x
login forms, and callouts are often implemented in CakePHP as elements. An element is basically a miniview 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 /app/View/Elements/ 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' ,
array
(
"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
in the controller works with view files). In the above example, the
/app/View/Elements/helpbox.ctp
file can use the $helptext variable:
// Inside app/View/Elements/helpbox.ctp
echo
$helptext ; // Outputs "Oh, this text is very helpful."
The
method also supports options for the element. The options supported are ‘cache’ and ‘callbacks’. An example:
echo
$this -> element ( 'helpbox' ,
array
(
"helptext" => "This is passed to the element as $helptext " ,
"foobar" => "This is passed to the element as $foobar " ,
),
array
(
// 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
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' ,
array
(),
array
(
"cache" =>
array
( 'config' => 'short' , 'key' => 'unique value' )
)
);
You can take full advantage of elements by using requestAction(), which fetches view variables from a controller action and returns them as an array. This enables your elements to perform in true MVC style.
92 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
Create a controller action that prepares the view variables for your elements, then call requestAction() inside the second parameter of element() to feed the element the view variables from your controller.
To do this, in your controller add something like the following for the Post example:
class PostsController extends
AppController {
// ...
public function
index () {
$posts = $this -> paginate ();
if
( $this -> request -> is ( 'requested' )) {
return
$posts ;
}
$this -> set ( 'posts' , $posts );
}
}
And then in the element we can access the paginated posts model. To get the latest five posts in an ordered list, we would do something like the following:
<h2>Latest Posts</h2>
<?php
$posts = $this -> requestAction (
'posts/index/sort:created/direction:asc/limit:5'
?>
);
<ol>
<?php foreach ( $posts
as
$post ) : ?>
<li> <?php echo $post [ 'Post' ][ 'title' ]; ?> </li>
<?php endforeach ; ?>
</ol>
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
for more information on configuring
. A simple example of caching an
element would be:
echo
$this -> element ( 'helpbox' ,
array
(),
array
( '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' ,
array
( 'var' => $var ),
array
( 'cache' =>
array
( 'key' => 'first_use' , 'config' => 'view_long' )
);
echo
$this -> element (
'helpbox' ,
Elements 93
CakePHP Cookbook Documentation, Release 2.x
array
( 'var' => $differenVar ),
array
( 'cache' =>
array
( '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
to the cache configuration you want to use. CakePHP will use this configuration when none is given.
Requesting Elements from a Plugin
2.0
To load an element from a plugin, use the plugin option (moved out of the data option in 1.x):
echo
$this -> element ( 'helpbox' ,
array
(),
array
( 'plugin' => 'Contacts' ));
2.1
If you are using a plugin and wish to use elements from within the plugin, just use the familiar
If the 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.
Changed in version 2.1: The $options[plugin] option was deprecated and support for
Plugin.element
was added.
Creating your own view classes
You may need to create custom view classes to enable new types of data views, or add additional custom view-rendering logic to your application. Like most components of CakePHP, view classes have a few conventions:
• View class files should be put in App/View. For example: App/View/PdfView.php
• View classes should be suffixed with View. For example: PdfView.
• When referencing view class names you should omit the View suffix.
For example:
$this->viewClass = ’Pdf’;
.
94 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
You’ll also want to extend View to ensure things work correctly:
// In App/View/PdfView.php
App :: uses ( 'View' , 'View' );
class PdfView extends
View {
public function
render ( $view =
null
, $layout =
null
) {
// Custom logic here.
}
}
Replacing the render method lets you take full control over how your content is rendered.
View API
class View
View methods are accessible in all view, element and layout files.
To call any view method use
$this->method()
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
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’.
View::get( string $var , $default = null)
Get the value of a viewVar with the name $var.
As of 2.5, you can provide a default value in case the variable is not already set.
Changed in version 2.5: The $default argument was added in 2.5.
View::getVar( string $var)
Gets the value of the viewVar with the name $var.
Deprecated since version 2.3: Use
instead.
View::getVars()
Gets a list of all the available view variables in the current rendering scope. Returns an array of variable names.
View::element( string $elementPath , array $data, array $options = array())
Renders an element or view partial. See the section on
for more information and examples.
View::uuid( string $object , mixed $url)
Generates a unique non-random DOM ID for an object, based on the object type and URL. This
View API 95
CakePHP Cookbook Documentation, Release 2.x
method is often used by helpers that need to generate unique DOM ID’s for elements such as the
$uuid = $this -> uuid (
'form' ,
);
array
( 'controller' => 'posts' , 'action' => 'index' )
// $uuid contains 'form0425fe3bad'
View::addScript( string $name , string $content)
Adds content to the internal scripts buffer.
This buffer is made available in the layout as
$scripts_for_layout
. This method is helpful when creating helpers that need to add javascript or css directly to the layout. Keep in mind that scripts added from the layout and elements in the layout will not be added to $scripts_for_layout. This method is most often used from inside helpers, such as the
and
Helpers.
Deprecated since version 2.1: Use the
features instead.
View::blocks()
Get the names of all defined blocks as an array.
View::start(
$name)
Start a capturing block for a view block. See the section on
for examples.
New in version 2.1.
View::end()
End the top most open capturing block. See the section on
for examples.
New in version 2.1.
View::append(
$name , $content)
Append into the block with $name. See the section on
for examples.
New in version 2.1.
View::prepend( $name , $content)
Prepend to the block with $name. See the section on
for examples.
New in version 2.3.
View::startIfEmpty(
$name)
Start a block if it is empty. All content in the block will be captured and discarded if the block is already defined.
New in version 2.3.
View::assign( $name , $content)
Assign the value of a block. This will overwrite any existing content. See the section on
for examples.
New in version 2.1.
View::fetch(
$name , $default = ‘’)
Fetch the value of a block. If a block is empty or undefined, ‘’ will be returned. See the section on
for examples.
96 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
New in version 2.1.
View::extend(
$name)
Extend the current view/element/layout with the named one. See the section on
for examples.
New in version 2.1.
property View::$layout
Set the layout the current view will be wrapped in.
property View::$elementCache
The cache configuration used to cache elements. Setting this property will change the default configuration used to cache elements. This default can be overridden using the ‘cache’ option in the element method.
property View::$request
An instance of
. Use this instance to access information about the current request.
property View::$output
Contains the last rendered content from a view, either the view file, or the layout content.
Deprecated since version 2.1: Use $view->Blocks->get(’content’); instead.
property View::$Blocks
An instance of ViewBlock. Used to provide view block functionality in view rendering.
New in version 2.1.
More about Views
Themes
You can take advantage of themes, making it easy to switch the look and feel of your page quickly and easily.
To use themes, specify the theme name in your controller:
class ExampleController extends
AppController {
public
$theme = 'Example' ;
}
Changed in version 2.1: Versions previous to 2.1 required setting the $this->viewClass =
’Theme’
. 2.1 removes this requirement as the normal View class supports themes
You can also set or change the theme name within an action or within the beforeFilter or beforeRender callback functions:
$this -> theme = 'AnotherExample' ;
Theme view files need to be within the /app/View/Themed/ folder. Within the themed folder, create a folder using the same name as your theme name. For example, the above theme would be found in
/app/View/Themed/AnotherExample
.
More about Views 97
CakePHP Cookbook Documentation, Release 2.x
Note: It is important to remember that CakePHP expects CamelCase theme names.
Beyond that, the folder structure within the /app/View/Themed/Example/ folder is exactly the same as /app/View/.
For example, the view file for an edit action of a Posts controller would reside at
/app/View/Themed/Example/Posts/edit.ctp
/app/View/Themed/Example/Layouts/
.
.
Layout files would reside in
If a view file can’t be found in the theme, CakePHP will try to locate the view file in the /app/View/ folder. This way, you can create master view files and simply override them on a case-by-case basis within your theme folder.
Theme assets
Themes can contain static assets as well as view files. A theme can include any necessary assets in its webroot directory. This allows for easy packaging and distribution of themes. While in development, requests for theme assets will be handled by Dispatcher. To improve performance for production environments, it’s recommended that you either symlink or copy theme assets into the application’s webroot. See below for more information.
To use the new theme webroot create directories like: app / View / Themed /< themeName >/ webroot < path_to_file > in your theme. The Dispatcher will handle finding the correct theme assets in your view paths.
All of CakePHP’s built-in helpers are aware of themes and will create the correct paths automatically. Like view files, if a file isn’t in the theme folder, it will default to the main webroot folder:
//When in a theme with the name of 'purple_cupcake'
$this -> Html -> css ( 'main.css' );
//creates a path like
/ theme / purple_cupcake / css / main .
css
//and links to app / View / Themed / PurpleCupcake / webroot / css / main .
css
Increasing performance of plugin and theme assets
It’s a well known fact that serving assets through PHP is guaranteed to be slower than serving those assets without invoking PHP. And while the core team has taken steps to make plugin and theme asset serving as fast as possible, there may be situations where more performance is required. In these situations it’s recommended that you either symlink or copy out plugin/theme assets to directories in app/webroot with paths matching those used by CakePHP.
• app/Plugin/DebugKit/webroot/js/my_file.js
app/webroot/debug_kit/js/my_file.js
becomes
98 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
• app/View/Themed/Navy/webroot/css/navy.css
app/webroot/theme/Navy/css/navy.css
becomes
Media Views
class MediaView
Deprecated since version 2.3: Use
instead.
Media views allow you to send binary files to the user. For example, you may wish to have a directory of files outside of the webroot to prevent users from direct linking them. You can use the Media view to pull the file from a special folder within /app/, allowing you to perform authentication before delivering the file to the user.
To use the Media view, you need to tell your controller to use the MediaView class instead of the default
View class. After that, just pass in additional parameters to specify where your file is located:
class ExampleController extends
AppController {
public function
download () {
$this -> viewClass = 'Media' ;
// Download app/outside_webroot_dir/example.zip
$params =
array
(
'id' => 'example.zip' ,
'name' => 'example' ,
'download' =>
true
,
'extension' => 'zip' ,
'path' => APP .
'outside_webroot_dir' .
DS
);
$this -> set ( $params );
}
}
Here’s an example of rendering a file whose mime type is not included in the MediaView’s $mimeType array. We are also using a relative path which will default to your app/webroot folder:
public function
download () {
$this -> viewClass = 'Media' ;
// Render app/webroot/files/example.docx
$params =
array
(
'id' => 'example.docx' ,
'name' => 'example' ,
'extension' => 'docx' ,
'mimeType' =>
array
(
'docx' => 'application/vnd.openxmlformats-officedocument' .
'.wordprocessingml.document'
),
'path' => 'files' .
DS
);
$this -> set ( $params );
}
More about Views 99
CakePHP Cookbook Documentation, Release 2.x
Settable Parameters id
The ID is the file name as it resides on the file server including the file extension.
name
The name allows you to specify an alternate file name to be sent to the user. Specify the name without the file extension.
download
A boolean value indicating whether headers should be set to force download.
extension
The file extension. This is matched against an internal list of acceptable mime types. If the mime type specified is not in the list (or set in the mimeType parameter array), the file will not be downloaded.
path
The folder name, including the final directory separator. The path should be absolute but can be relative to the app/webroot folder.
mimeType
An array with additional mime types to be merged with MediaView internal list of acceptable mime types.
cache
A boolean or integer value - If set to true it will allow browsers to cache the file (defaults to false if not set); otherwise set it to the number of seconds in the future for when the cache should expire.
JSON and XML views
New in CakePHP 2.1 are two new view classes. The XmlView and JsonView let you easily create XML and JSON responses, and integrate with the
By enabling RequestHandlerComponent in your application, and enabling support for the xml and or json extensions, you can automatically leverage the new view classes. XmlView and JsonView 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 view files.
Enabling data views in your application
Before you can use the data view classes, you’ll need to do a bit of setup:
1. Enable the json and or xml extensions with
Router to handle multiple extensions.
2. Add the
to your controller’s list of components. This 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.
New in version 2.3:
RequestHandlerComponent::viewClassMap()
method has been added to map types to viewClasses. The viewClassMap setting will not work on earlier versions.
After adding Router::parseExtensions(’json’); to your routes file, CakePHP will automatically switch view classes when a request is done with the .json extension, or the Accept header is application/json
.
100 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
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 view 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 view files. The value of _serialize can be either a string or an array of view variables to serialize:
class PostsController extends
AppController {
public
$components =
array
( 'RequestHandler' );
public function
index () {
$this -> set ( 'posts' , $this -> Paginator -> paginate ());
$this -> set ( '_serialize' ,
array
( 'posts' ));
}
}
You can also define _serialize as an array of view variables to combine:
class PostsController extends
AppController {
public
$components =
array
( 'RequestHandler' );
public function
index () {
// some code that created $posts and $comments
$this -> set ( compact ( 'posts' , 'comments' ));
$this -> set ( '_serialize' ,
array
( 'posts' , 'comments' ));
}
}
Defining _serialize as an array has the added benefit of automatically appending a top-level
<response> element when using
. 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.
Using a data view with view files
You should use view files if you need to do some manipulation of your view content before creating the final output. For example if we had posts, 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:
// Controller code
class PostsController extends
AppController {
public function
index () {
$this -> set ( compact ( 'posts' , 'comments' ));
}
}
// View code - app/View/Posts/json/index.ctp
foreach
( $posts
as
& $post ) { unset ( $post [ 'Post' ][ 'generated_html' ]);
More about Views 101
CakePHP Cookbook Documentation, Release 2.x
}
echo
json_encode ( compact ( 'posts' , 'comments' ));
You can do more complex manipulations, or use helpers to do formatting as well.
Note: The data view classes don’t support layouts. They assume that the view file will output the serialized content.
class XmlView
A view class for generating Xml view data. See above for how you can use XmlView in your application.
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.
New in version 2.3: The _rootNode feature was added.
New in version 2.6: The XmlView class supports the _xmlOptions variable that allows you to customize the options used to generate XML, e.g. tags vs attributes.
class JsonView
A view class for generating Json view data. See above for how you can use JsonView in your application.
New in version 2.6: JsonView now supports the _jsonOptions view variable. This allows you to configure the bit-mask options used when generating JSON.
JSONP response
New in version 2.4.
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 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.
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 create your own helpers, and outline the basic tasks CakePHP’s core helpers can help you accomplish.
CakePHP features 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:
CacheHelper
class CacheHelper(View $view, array $settings = array())
102 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
The Cache helper assists in caching entire layouts and views, saving time repetitively retrieving data. View
Caching in CakePHP temporarily stores parsed layouts and views as simple PHP + HTML files. It should be noted that the Cache helper works quite differently than other helpers. It does not have methods that are directly called. Instead, a view is marked with cache tags indicating which blocks of content should not be cached. The CacheHelper then uses helper callbacks to process the file and output to generate the cache file.
When a URL is requested, CakePHP checks to see if that request string has already been cached. If it has, the rest of the URL dispatching process is skipped. Any nocache blocks are processed normally and the view is served. This creates a big savings in processing time for each request to a cached URL as minimal code is executed. If CakePHP doesn’t find a cached view, or the cache has expired for the requested URL it continues to process the request normally.
Using the Helper
There are two steps you have to take before you can use the CacheHelper.
First in your
APP/Config/core.php
uncomment the Configure write call for Cache.check.
This will tell
CakePHP to check for, and generate view cache files when handling requests.
Once you’ve uncommented the Cache.check line you will need to add the helper to your controller’s
$helpers array:
class PostsController extends
AppController {
public
$helpers =
array
( 'Cache' );
}
You will also need to add the CacheDispatcher to your dispatcher filters in your bootstrap:
Configure :: write ( 'Dispatcher.filters' ,
array
(
'CacheDispatcher'
));
New in version 2.3: If you have a setup with multiple domains or languages you can use Configure::write(‘Cache.viewPrefix’, ‘YOURPREFIX’); to store the view cache files prefixed.
Additional configuration options CacheHelper has a few additional configuration options you can use to tune and tweak its behavior. This is done through the $cacheAction variable in your controllers.
$cacheAction should be set to an array which contains the actions you want cached, and the duration in seconds you want those views cached. The time value can be expressed in a strtotime() format (e.g.
“1 hour”, or “3 minutes”).
Using the example of an ArticlesController, that receives a lot of traffic that needs to be cached:
public
$cacheAction =
array
(
'view' => 36000 ,
'index' => 48000
);
This will cache the view action 10 hours, and the index action 13 hours. By making $cacheAction a strtotime() friendly value you can cache every action in the controller:
More about Views 103
CakePHP Cookbook Documentation, Release 2.x
public
$cacheAction = "1 hour" ;
You can also enable controller/component callbacks for cached views created with CacheHelper. To do so you must use the array format for $cacheAction and create an array like the following:
public
$cacheAction =
array
(
'view' =>
array
( 'callbacks' =>
true
, 'duration' => 21600 ),
'add' =>
array
( 'callbacks' =>
true
, 'duration' => 36000 ),
'index' =>
array
( 'callbacks' =>
true
, 'duration' => 48000 )
);
By setting callbacks => true you tell CacheHelper that you want the generated files to create the components and models for the controller. Additionally, fire the component initialize, controller beforeFilter, and component startup callbacks.
Note: Setting callbacks => true partly defeats the purpose of caching. This is also the reason it is disabled by default.
Marking Non-Cached Content in Views
There will be times when you don’t want an entire view cached. For example, certain parts of the page may look different whether a user is currently logged in or browsing your site as a guest.
To indicate blocks of content that are not to be cached, wrap them in <!--nocache-->
<!--/nocache--> like so:
<!--nocache-->
<?php if ( $this -> Session -> check ( 'User.name' )) : ?>
Welcome, <?php echo h( $this -> Session -> read ( 'User.name' )); ?> .
<?php else : ?>
<?php echo $this -> Html -> link ( 'Login' , 'users/login' ); ?>
<?php endif ; ?>
<!--/nocache-->
Note: You cannot use nocache tags in elements. Since there are no callbacks around elements, they cannot be cached.
It should be noted that once an action is cached, the controller method for the action will not be called. When a cache file is created, the request object, and view variables are serialized with PHP’s serialize().
Warning: If you have view variables that contain un-serializable content such as SimpleXML objects, resource handles, or closures you might not be able to use view caching.
Clearing the Cache
It is important to remember that CakePHP will clear a cached view if a model used in the cached view is modified. For example, if a cached view uses data from the Post model, and there has been an INSERT,
104 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
UPDATE, or DELETE query made to a Post, the cache for that view is cleared, and new content is generated on the next request.
Note: This automatic cache clearing requires the controller/model name to be part of the URL. If you’ve used routing to change your URLs this feature will not work.
If you need to manually clear the cache, you can do so by calling Cache::clear(). This will clear all cached data, excluding cached view files. If you need to clear the cached view files, use clearCache().
FlashHelper
class FlashHelper(View $view, array $config = array())
FlashHelper provides a way to render flash messages that were set in $_SESSION by
and FlashHelper primarily use elements to render flash messages. Flash elements are found under the app/View/Elements/Flash directory. You’ll notice that CakePHP’s App template comes with two flash elements: success.ctp and error.ctp.
The FlashHelper replaces the flash() method on SessionHelper and should be used instead of that method.
Rendering Flash Messages
To render a flash message, you can simply use FlashHelper’s render() method:
<?
php
echo
$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
, you can specify which flash key to render:
<?
php
echo
$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.' ,
array
(
'element' => 'success'
));
// In your View: Will use great_success.ctp instead of success.ctp
<?
php
echo
$this -> Flash -> render ( 'flash' ,
array
(
'element' => 'great_success'
));
Note: By default, CakePHP does not escape the HTML in flash messages. If you are using any request or user data in your flash messages, you should escape it with
when formatting your messages.
For more information about the available array options, please refer to the
section.
More about Views 105
CakePHP Cookbook Documentation, Release 2.x
FormHelper
class FormHelper(View $view, array $settings = array())
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.
Creating Forms
The first method you’ll need to use in order to take advantage of the FormHelper is create(). This special method outputs an opening form tag.
FormHelper::create( string $model = null , array $options = array())
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. The form element is also returned with a DOM ID. The ID is generated using the name of the model, and the name of the controller action, CamelCased. If I were to call create() inside a UsersController view, I’d see something like the following output in the rendered view:
<form
id="UserAddForm" method="post" action="/users/add"
>
Note: You can also pass false for
$model
.
data into the array:
$this->request->data
This
(instead will of in place the your form sub-array:
$this->request->data[’Model’]
).
This can be handy for short forms that may not represent anything in your database.
The create() method allows us to customize much more using the parameters, however. First, you can specify a model name. By specifying a model for a form, you are creating that form’s context.
All fields are assumed to belong to this model (unless otherwise specified), and all models referenced are assumed to be associated with it. If you do not specify a model, then it assumes you are using the default model for the current controller:
// If you are on /recipes/add
echo
$this -> Form -> create ( 'Recipe' );
Output:
<form id="RecipeAddForm" method="post" action="/recipes/add">
This will POST the form data to the add() action of RecipesController. However, you can also use the same logic to create an edit form. The FormHelper uses the $this->request->data property to automatically detect whether to create an add or edit form. If $this->request->data contains an array element named after the form’s model, and that array contains a non-empty value of the model’s primary key, then the FormHelper will create an edit form for that record. For example, if we browse to http://site.com/recipes/edit/5 , we would get the following:
106 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
// Controller/RecipesController.php:
public function
edit ( $id =
null
) {
if
(
empty
( $this -> request -> data )) {
$this -> request -> data = $this -> Recipe -> findById ( $id );
}
else
{
// Save logic goes here
}
}
// View/Recipes/edit.ctp:
// Since $this->request->data['Recipe']['id'] = 5,
// we will get an edit form
<?
php
echo
$this -> Form -> create ( 'Recipe' ); ?>
Output:
<form
id="RecipeEditForm" method="post" action="/recipes/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.
When creating forms for models in plugins, you should always use
when creating a form. This will ensure the form is correctly generated:
echo
$this -> Form -> create ( 'ContactManager.Contact' );
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.
Changed in version 2.0: The default URL for all forms, is now the current URL including passed, named, and querystring parameters. You can override this default by supplying $options[’url’] in the second parameter of $this->Form->create().
Options for create() There are a number of options for create():
• $options[’type’] This key is used to specify the type of form to be created. Valid values include
‘post’, ‘get’, ‘file’, ‘put’ and ‘delete’.
Supplying either ‘post’ or ‘get’ changes the form submission method accordingly:
echo
$this -> Form -> create ( 'User' ,
array
( 'type' => 'get' ));
Output:
<form
id="UserAddForm" method="get" action="/users/add"
>
Specifying ‘file’ 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:
More about Views 107
CakePHP Cookbook Documentation, Release 2.x
echo
$this -> Form -> create ( 'User' ,
array
( 'type' => 'file' ));
Output:
<form
id="UserAddForm" enctype="multipart/form-data" method="post" action="/users/add"
>
When using ‘put’ or ‘delete’, your form will be functionally equivalent to a ‘post’ form, but when submitted, the HTTP request method will be overridden with ‘PUT’ or ‘DELETE’, respectively. This allows CakePHP to emulate proper REST support in web browsers.
• $options[’action’] The action key allows you to point the form to a specific action in your current controller. 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 ( 'User' ,
array
( 'action' => 'login' ));
Output:
<form
id="UserLoginForm" method="post" action="/users/login"
>
• $options[’url’] If the desired form action isn’t in the current controller, you can specify a URL for the form action using the ‘url’ key of the $options array. The supplied URL can be relative to your
CakePHP application:
echo
$this -> Form -> create (
null
,
array
(
'url' =>
array
( 'controller' => 'recipes' , 'action' => 'add' )
));
Output:
<form
method="post" action="/recipes/add"
>
or can point to an external domain:
echo
$this -> Form -> create (
null
,
array
(
'url' => 'http://www.google.com/search' ,
'type' => 'get'
));
Output:
<form
method="get" action="http://www.google.com/search"
>
Also check
method for more examples of different types of URLs.
• $options[’default’] If ‘default’ has been set to boolean false, the form’s submit action is changed so that pressing the submit button does not submit the form. If the form is meant to be submitted via AJAX, setting ‘default’ to false suppresses the form’s default behavior so you can grab the data and submit it via AJAX instead.
• $options[’inputDefaults’] You can declare a set of default options for input() with the inputDefaults key to customize your default input creation:
108 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
echo
$this -> Form -> create ( 'User' ,
array
(
'inputDefaults' =>
array
(
'label' =>
false
,
'div' =>
false
)
));
All inputs created from that point forward would inherit the options declared in inputDefaults. You can override the defaultOptions by declaring the option in the input() call:
echo
$this -> Form -> input ( 'password' ); // No div, no label
// has a label element
echo
$this -> Form -> input (
'username' ,
array
( 'label' => 'Username' )
);
Closing the Form
FormHelper::end(
$options = null , $secureAttributes = array())
The FormHelper includes an end() method that completes the form. Often, end() only outputs a closing form tag, but using end() also allows the FormHelper to insert needed hidden form elements that
requires:
<?php echo $this -> Form -> create (); ?>
<!-- Form elements go here -->
<?php echo $this -> Form -> end (); ?>
If a string is supplied as the first parameter to end(), the FormHelper outputs a submit button named accordingly along with the closing form tag:
<?
php
echo
$this -> Form -> end ( 'Finish' ); ?>
Will output:
<div
class="submit"
>
<input
type="submit" value="Finish"
/>
</div>
</form>
You can specify detail settings by passing an array to end():
$options =
array
(
'label' => 'Update' ,
'div' =>
array
(
'class' => 'glass-pill' ,
)
);
echo
$this -> Form -> end ( $options );
More about Views 109
CakePHP Cookbook Documentation, Release 2.x
Will output:
<div
class="glass-pill"
><input
type="submit" value="Update" name="Update"
>
</div>
See the Form Helper API
1 for further details.
Note: If you are using
in your application you should always end your forms with end().
Changed in version 2.5: The $secureAttributes parameter was added in 2.5.
Creating form elements
There are a few ways to create form inputs with the FormHelper. We’ll start by looking at input(). This method will automatically inspect the model field it has been supplied in order to create an appropriate input for that field. Internally input() delegates to other methods in FormHelper.
FormHelper::input( string $fieldName , array $options = array())
Creates the following elements given a particular Model.field:
•Wrapping div.
•Label element
•Input element(s)
•Error element with message if applicable.
The type of input created depends on the column datatype:
Column Type Resulting Form Field string (char, varchar, etc.) text boolean, tinyint(1) checkbox text textarea text, with name of password, passwd, or psword 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
1 http://api.cakephp.org/2.8/class-FormHelper.html
110 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
The $options parameter allows you to customize how input() works, and finely control what is generated.
The wrapping div will have a required class name appended if the validation rules for the Model’s field do not specify allowEmpty => true. One limitation of this behavior is the field’s model must have been loaded during this request. Or be directly associated to the model supplied to
New in version 2.5: The binary type now maps to a file input.
New in version 2.3. Since 2.3 the HTML5 required attribute will also be added to the input based on validation rules. You can explicitly set required key in options array to override it for a field. To skip browser validation triggering for the whole form you can set option ’formnovalidate’ => true for the input button you generate using
or set ’novalidate’
=> true in options for
For example, let’s assume that your User model includes fields for a username (varchar), password
(varchar), approved (datetime) and quote (text). You can use the input() method of the FormHelper to create appropriate inputs for all of these form fields:
echo
$this -> Form -> create ();
echo
$this -> Form -> input ( 'username' );
echo
$this -> Form -> input ( 'password' );
echo
$this -> Form -> input ( 'approved' );
echo
$this -> Form -> input ( 'quote' );
echo
$this -> Form -> end ( 'Add' );
//text
//password
//day, month, year, hour, minute,
//meridian
//textarea
A more extensive example showing some options for a date field:
echo
$this -> Form -> input ( 'birth_dt' ,
array
(
'label' => 'Date of birth' ,
'dateFormat' => 'DMY' ,
'minYear' => date ( 'Y' ) 70 ,
'maxYear' => date ( 'Y' ) 18 ,
));
Besides the specific options for input() found below, you can specify any option for the input type & any HTML attribute (for instance onfocus). For more information on $options and
$htmlAttributes see
Assuming that User hasAndBelongsToMany Group. In your controller, set a camelCase plural variable (group -> groups in this case, or ExtraFunkyModel -> extraFunkyModels) with the select options.
In the controller action you would put the following:
$this -> set ( 'groups' , $this -> User -> Group -> find ( 'list' ));
And in the view a multiple select can be created with this simple code:
echo
$this -> Form -> input ( 'Group' );
More about Views 111
CakePHP Cookbook Documentation, Release 2.x
If you want to create a select field while using a belongsTo - or hasOne - Relation, you can add the following to your Users-controller (assuming your User belongsTo Group):
$this -> set ( 'groups' , $this -> User -> Group -> find ( 'list' ));
Afterwards, add the following to your form-view:
echo
$this -> Form -> input ( 'group_id' );
If your model name consists of two or more words, e.g., “UserGroup”, when passing the data using set() you should name your data in a pluralised and camelCased format as follows:
$this -> set ( 'userGroups' , $this -> UserGroup -> find ( 'list' ));
// or
$this -> set (
'reallyInappropriateModelNames' ,
$this -> ReallyInappropriateModelName -> find ( 'list' )
);
Note: Try to avoid using FormHelper::input() to generate submit buttons.
instead.
Use
FormHelper::inputs( mixed $fields = null , array $blacklist = null, $options = array())
Generate a set of inputs for $fields. If $fields is null all fields, except of those defined in
$blacklist
, of the current model will be used.
In addition to controller fields output, $fields can be used to control legend and fieldset rendering with the fieldset and legend keys. $this->Form->inputs(array(’legend’ =>
’My legend’));
Would generate an input set with a custom legend. You can customize individual inputs through $fields as well.
echo
$this -> Form -> inputs (
array
(
'name' =>
array
( 'label' => 'custom label' )
));
In addition to fields control, inputs() allows you to use a few additional options.
•fieldset Set to false to disable the fieldset. If a string is supplied it will be used as the class name for the fieldset element.
•legend Set to false to disable the legend for the generated input set. Or supply a string to customize the legend text.
Field naming conventions The Form helper is pretty smart. Whenever you specify a field name with the form helper methods, it’ll automatically use the current model name to build an input with a format like the following:
<input
type="text" id="ModelnameFieldname" name="data[Modelname][fieldname]"
>
This allows you to omit the model name when generating inputs for the model that the form was created for.
You can create inputs for associated models, or arbitrary models by passing in Modelname.fieldname as the first parameter:
112 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
echo
$this -> Form -> input ( 'Modelname.fieldname' );
If you need to specify multiple fields using the same field name, thus creating an array that can be saved in one shot with saveAll(), use the following convention:
echo
$this -> Form -> input ( 'Modelname.0.fieldname' );
echo
$this -> Form -> input ( 'Modelname.1.fieldname' );
Output:
<input
type="text" id="Modelname0Fieldname" name="data[Modelname][0][fieldname]"
>
<input
type="text" id="Modelname1Fieldname" name="data[Modelname][1][fieldname]"
>
FormHelper uses several field-suffixes internally for datetime input creation. If you are using fields named year
, month, day, hour, minute, or meridian and having issues getting the correct input, you can set the name attribute to override the default behavior:
echo
$this -> Form -> input ( 'Model.year' ,
array
(
'type' => 'text' ,
'name' => 'data[Model][year]'
));
Options
FormHelper::input() supports a large number of options. In addition to its own options input() accepts options for the generated input types, as well as HTML attributes. The following will cover the options specific to FormHelper::input().
• $options[’type’] You can force the type of an input, overriding model introspection, by specifying a type. In addition to the field types found in the
Creating form elements , you can also create
‘file’, ‘password’, and any type supported by HTML5:
echo
$this -> Form -> input ( 'field' ,
array
( 'type' => 'file' ));
echo
$this -> Form -> input ( 'email' ,
array
( 'type' => 'email' ));
Output:
<div
class="input file"
>
<label
for="UserField"
>
Field
</label>
<input
type="file" name="data[User][field]" value="" id="UserField"
/>
</div>
<div
class="input email"
>
<label
for="UserEmail"
>
</label>
<input
type="email" name="data[User][email]" value="" id="UserEmail"
/>
</div>
• $options[’div’] Use this option to set attributes of the input’s containing div. Using a string value will set the div’s class name. An array will set the div’s attributes to those specified by the array’s keys/values. Alternatively, you can set this key to false to disable the output of the div.
Setting the class name:
More about Views 113
CakePHP Cookbook Documentation, Release 2.x
echo
$this -> Form -> input ( 'User.name' ,
array
(
'div' => 'class_name'
));
Output:
<div
class="class_name"
>
<label
for="UserName"
>
Name
</label>
<input
name="data[User][name]" type="text" value="" id="UserName"
/>
</div>
Setting multiple attributes:
echo
$this -> Form -> input ( 'User.name' ,
array
(
'div' =>
array
(
'id' => 'mainDiv' ,
'title' => 'Div Title' ,
'style' => 'display:block'
)
));
Output:
<div
class="input text" id="mainDiv" title="Div Title" style="display:block"
>
<label
for="UserName"
>
Name
</label>
<input
name="data[User][name]" type="text" value="" id="UserName"
/>
</div>
Disabling div output:
echo
$this -> Form -> input ( 'User.name' ,
array
( 'div' =>
false
)); ?>
Output:
<label
for="UserName"
>
Name
</label>
<input
name="data[User][name]" type="text" value="" id="UserName"
/>
• $options[’label’] Set this key to the string you would like to be displayed within the label that usually accompanies the input:
echo
$this -> Form -> input ( 'User.name' ,
array
(
'label' => 'The User Alias'
));
Output:
<div
class="input"
>
<label
for="UserName"
>
The User Alias
</label>
<input
name="data[User][name]" type="text" value="" id="UserName"
/>
</div>
Alternatively, set this key to false to disable the output of the label:
114 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
echo
$this -> Form -> input ( 'User.name' ,
array
( 'label' =>
false
));
Output:
<div
class="input"
>
<input
name="data[User][name]" type="text" value="" id="UserName"
/>
</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:
echo
$this -> Form -> input ( 'User.name' ,
array
(
'label' =>
array
(
'class' => 'thingy' ,
'text' => 'The User Alias'
)
));
Output:
<div
class="input"
>
<label
for="UserName" class="thingy"
>
The User Alias
</label>
<input
name="data[User][name]" type="text" value="" id="UserName"
/>
</div>
• $options[’error’] Using this key allows you to override the default model error messages and can be used, for example, to set i18n messages. It has a number of suboptions which control the wrapping element, wrapping element class name, and whether HTML in the error message will be escaped.
To disable error message output & field classes set the error key to false:
$this -> Form -> input ( 'Model.field' ,
array
( 'error' =>
false
));
To disable only the error message, but retain the field classes, set the errorMessage key to false:
$this -> Form -> input ( 'Model.field' ,
array
( 'errorMessage' =>
false
));
To modify the wrapping element type and its class, use the following format:
$this -> Form -> input ( 'Model.field' ,
array
(
'error' =>
array
(
'attributes' =>
array
( 'wrap' => 'span' , 'class' => 'bzzz' )
)
));
To prevent HTML being automatically escaped in the error message output, set the escape suboption to false:
$this -> Form -> input ( 'Model.field' ,
array
(
'error' =>
array
(
'attributes' =>
array
( 'escape' =>
false
)
)
));
More about Views 115
CakePHP Cookbook Documentation, Release 2.x
To override the model error messages use an array with the keys matching the validation rule names:
$this -> Form -> input ( 'Model.field' ,
array
(
'error' =>
array
( 'tooShort' => __( '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.
New in version 2.3: Support for the errorMessage option was added in 2.3
• $options[’before’],
$options[’between’]
,
$options[’separator’]
, and
$options[’after’]
Use these keys if you need to inject some markup inside the output of the input() method:
echo
$this -> Form -> input ( 'field' ,
array
(
'before' => '--before--' ,
'after' => '--after--' ,
'between' => '--between---'
));
Output:
<div
class="input"
>
--before--
<label
for="UserField"
>
Field
</label>
--between---
<input
name="data[User][field]" type="text" value="" id="UserField"
/>
--after--
</div>
For radio inputs the ‘separator’ attribute can be used to inject markup to separate each input/label pair:
echo
$this -> Form -> input ( 'field' ,
array
(
'before' => '--before--' ,
'after' => '--after--' ,
'between' => '--between---' ,
'separator' => '--separator--' ,
'options' =>
array
( '1' , '2' )
));
Output:
<div
class="input"
>
--before--
<input
name="data[User][field]" type="radio" value="1" id="UserField1"
/>
<label
for="UserField1"
>
1
</label>
--separator--
<input
name="data[User][field]" type="radio" value="2" id="UserField2"
/>
<label
for="UserField2"
>
2
</label>
--between---
--after--
</div>
116 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
For date and datetime type elements the ‘separator’ attribute can be used to change the string between select elements. Defaults to ‘-‘.
• $options[’format’] The ordering of the HTML generated by FormHelper is controllable as well. The ‘format’ options supports an array of strings describing the template you would like said element to follow. The supported array keys are: array(’before’, ’input’, ’between’,
’label’, ’after’,’error’) .
• $options[’inputDefaults’] If you find yourself repeating the same options in multiple input() calls, you can use inputDefaults‘ to keep your code dry:
echo
$this -> Form -> create ( 'User' ,
array
(
'inputDefaults' =>
array
(
'label' =>
false
,
'div' =>
false
)
));
All inputs created from that point forward would inherit the options declared in inputDefaults. You can override the defaultOptions by declaring the option in the input() call:
// No div, no label
echo
$this -> Form -> input ( 'password' );
// has a label element
echo
$this -> Form -> input ( 'username' ,
array
( 'label' => 'Username' ));
If you need to later change the defaults you can use FormHelper::inputDefaults().
GET Form Inputs When using FormHelper to generate inputs for GET forms, the input names will automatically be shortened to provide more human friendly names. For example:
// Makes <input name="email" type="text" />
echo
$this -> Form -> input ( 'User.email' );
// Makes <select name="Tags" multiple="multiple">
echo
$this -> Form -> input ( 'Tags.Tags' ,
array
( 'multiple' =>
true
));
If you want to override the generated name attributes you can use the name option:
// Makes the more typical <input name="data[User][email]" type="text" />
echo
$this -> Form -> input ( 'User.email' ,
array
( 'name' => 'data[User][email]' ));
Generating specific types of inputs
In addition to the generic input() method, FormHelper has specific methods for generating a number of different types of inputs. These can be used to generate just the input widget itself, and combined with other methods like
and
to generate fully custom form layouts.
More about Views 117
CakePHP Cookbook Documentation, Release 2.x
Common options Many of the various input element methods support a common set of options. All of these options are also supported by input(). To reduce repetition the common options shared by all input methods are as follows:
• $options[’class’] You can set the class name for an input:
echo
$this -> Form -> input ( 'title' ,
array
( 'class' => 'custom-class' ));
• $options[’id’] Set this key to force the value of the DOM id for the input.
• $options[’default’] Used to set a default value for the input 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).
Example usage:
echo
$this -> Form -> input ( 'ingredient' ,
array
( 'default' => 'Sugar' ));
Example with select field (Size “Medium” will be selected as default):
$sizes =
array
( 's' => 'Small' , 'm' => 'Medium' , 'l' => 'Large' );
echo
$this -> Form -> input (
'size' ,
array
( 'options' => $sizes , 'default' => 'm' )
);
Note: You cannot use default to check a checkbox - instead you might set the value in
$this->request->data in your controller, or set the input option checked to true.
Date and datetime fields’ default values can be set by using the ‘selected’ key.
Beware of using false to assign a default value. A false value is used to disable/exclude options of an input field, so ’default’ => false would not set any value at all. Instead use ’default’
=> 0
.
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 input element.
Options for select, checkbox and radio inputs
• $options[’selected’] Used in combination with a select-type input (i.e. For types select, date, time, datetime). Set ‘selected’ to the value of the item you wish to be selected by default when the input is rendered:
echo
$this -> Form -> input ( 'close_time' ,
array
(
'type' => 'time' ,
'selected' => '13:30:00'
));
Note: The selected key for date and datetime inputs may also be a UNIX timestamp.
• $options[’empty’] If set to true, forces the input to remain empty.
118 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
When passed to a select list, this creates a blank option with an empty value in your drop down list. If you want to have a empty value with text displayed instead of just a blank option, pass in a string to empty:
echo
$this -> Form -> input ( 'field' ,
array
(
'options' =>
array
( 1 , 2 , 3 , 4 , 5 ),
'empty' => '(choose one)'
));
Output:
<div
class="input"
>
<label
for="UserField"
>
Field
</label>
<select
name="data[User][field]" id="UserField"
>
<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>
</div>
Note: If you need to set the default value in a password field to blank, use ‘value’ => ‘’ instead.
A list of key-value pairs can be supplied for a date or datetime field:
echo
$this -> Form -> dateTime ( 'Contact.date' , 'DMY' , '12' ,
array
(
'empty' =>
array
(
'day' => 'DAY' , 'month' => 'MONTH' , 'year' => 'YEAR' ,
'hour' => 'HOUR' , 'minute' => 'MINUTE' , 'meridian' =>
false
)
)
);
Output:
<select
name="data[Contact][date][day]" id="ContactDateDay"
>
<option
value=""
>
DAY
</option>
<option
value="01"
>
1
</option>
// ...
<option
value="31"
>
31
</option>
</select>
-
<select
name="data[Contact][date][month]" id="ContactDateMonth"
>
<option
value=""
>
MONTH
</option>
<option
value="01"
>
January
</option>
// ...
<option
value="12"
>
December
</option>
</select>
-
<select
name="data[Contact][date][year]" id="ContactDateYear"
>
<option
value=""
>
YEAR
</option>
<option
value="2036"
>
2036
</option>
// ...
<option
value="1996"
>
1996
</option>
More about Views 119
CakePHP Cookbook Documentation, Release 2.x
120
</select> <select
name="data[Contact][date][hour]" id="ContactDateHour"
>
<option
value=""
>
HOUR
</option>
<option
value="01"
>
1
</option>
// ...
<option
value="12"
>
12
</option>
</select>
:
<select
name="data[Contact][date][min]" id="ContactDateMin"
>
<option
value=""
>
MINUTE
</option>
<option
value="00"
>
00
</option>
// ...
<option
value="59"
>
59
</option>
</select> <select
name="data[Contact][date][meridian]" id="ContactDateMeridian"
>
<option
value="am"
>
am
</option>
<option
value="pm"
>
pm
</option>
</select>
• $options[’hiddenField’] For certain input types (checkboxes, radios) a hidden input is created so that the key in $this->request->data will exist even without a value specified:
<input
type="hidden" name="data[Post][Published]" id="PostPublished_" value="0"
/>
<input
type="checkbox" name="data[Post][Published]" value="1" id="PostPublished"
/>
This can be disabled by setting the $options[’hiddenField’] = false:
echo
$this -> Form -> checkbox ( 'published' ,
array
( 'hiddenField' =>
false
));
Which outputs:
<input
type="checkbox" name="data[Post][Published]" value="1" id="PostPublished"
/>
If you want to create multiple blocks of inputs on a form that are all grouped together, you should use this parameter on all inputs except the first. If the hidden input is on the page in multiple places, only the last group of input’s 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="data[Color][Color]" id="Colors_" value="0"
/>
<input
type="checkbox" name="data[Color][Color][]" value="5" id="ColorsRed"
/>
<label
for="ColorsRed"
>
Red
</label>
<input
type="checkbox" name="data[Color][Color][]" value="5" id="ColorsBlue"
/>
<label
for="ColorsBlue"
>
Blue
</label>
<input
type="checkbox" name="data[Color][Color][]" value="5" id="ColorsYellow"
/>
<label
for="ColorsYellow"
>
Yellow
</label>
<h2>
Tertiary Colors
</h2>
<input
type="hidden" name="data[Color][Color]" id="Colors_" value="0"
/>
<input
type="checkbox" name="data[Color][Color][]" value="5" id="ColorsGreen"
/>
Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
<label
for="ColorsGreen"
>
Green
</label>
<input
type="checkbox" name="data[Color][Color][]" value="5" id="ColorsPurple"
/>
<label
for="ColorsPurple"
>
Purple
</label>
<input
type="checkbox" name="data[Addon][Addon][]" value="5" id="ColorsOrange"
/>
<label
for="ColorsOrange"
>
Orange
</label>
Disabling the ’hiddenField’ on the second input group would prevent this behavior.
You can set a different hidden field value other than 0 such as ‘N’:
echo
$this -> Form -> checkbox ( 'published' ,
array
(
'value' => 'Y' ,
'hiddenField' => 'N' ,
));
Datetime options
• $options[’timeFormat’] Used to specify the format of the select inputs for a time-related set of inputs. Valid values include 12, 24, and null.
• $options[’dateFormat’] Used to specify the format of the select inputs for a date-related set of inputs. Valid values include any combination of ‘D’, ‘M’ and ‘Y’ or null. The inputs will be put in the order defined by the dateFormat option.
• $options[’minYear’], $options[’maxYear’] Used in combination with a date/datetime input.
Defines the lower and/or upper end of values shown in the years select field.
• $options[’orderYear’] Used in combination with a date/datetime input. Defines the order in which the year values will be set. Valid values include ‘asc’, ‘desc’. The default value is ‘desc’.
• $options[’interval’] This option specifies the number of minutes between each option in the minutes select box:
echo
$this -> Form -> input ( 'Model.time' ,
array
(
'type' => 'time' ,
'interval' => 15
));
Would create 4 options in the minute select. One for each 15 minutes.
• $options[’round’] Can be set to up or down to force rounding in either direction. Defaults to null which rounds half up according to interval.
New in version 2.4.
Form Element-Specific Methods
All elements are created under a form for the User model as in the examples above.
For this reason, the HTML code generated will contain attributes that reference to the User model.
Ex:
More about Views 121
CakePHP Cookbook Documentation, Release 2.x
name=data[User][username], id=UserUsername
FormHelper::label( string $fieldName , string $text, array $options)
Create a label element. $fieldName is used for generating the DOM id. If $text is undefined,
$fieldName will be used to inflect the label’s text:
echo
$this -> Form -> label ( 'User.name' );
echo
$this -> Form -> label ( 'User.name' , 'Your username' );
Output:
<label
for="UserName"
>
Name
</label>
<label
for="UserName"
>
Your username
</label>
$options can either be an array of HTML attributes, or a string that will be used as a class name:
echo
$this -> Form -> label ( 'User.name' ,
null
,
array
( 'id' => 'user-label' ));
echo
$this -> Form -> label ( 'User.name' , 'Your username' , 'highlight' );
Output:
<label
for="UserName" id="user-label"
>
Name
</label>
<label
for="UserName" class="highlight"
>
Your username
</label>
FormHelper::text( string $name
, array $options)
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 parameter. In this case, however, $options is used primarily to specify HTML tag attributes (such as the value or DOM id of an element in the form):
echo
$this -> Form -> text ( 'username' ,
array
( 'class' => 'users' ));
Will output:
<input
name="data[User][username]" type="text" class="users" id="UserUsername"
/>
FormHelper::password( string $fieldName , array $options)
Creates a password field.
echo
$this -> Form -> password ( 'password' );
Will output:
<input
name="data[User][password]" value="" id="UserPassword" type="password"
/>
FormHelper::hidden( string $fieldName
, array $options)
Creates a hidden form input. Example:
echo
$this -> Form -> hidden ( 'id' );
Will output:
<input
name="data[User][id]" id="UserId" type="hidden"
/>
122 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
If the form is edited (that is, the array $this->request->data will contain the information saved for the User model), the value corresponding to id field will automatically be added to the
HTML generated. Example for data[User][id] = 10:
<input
name="data[User][id]" id="UserId" type="hidden" value="10"
/>
Changed in version 2.0: Hidden fields no longer remove the class attribute. This means that if there are validation errors on hidden fields, the error-field class name will be applied.
FormHelper::textarea( string $fieldName , array $options)
Creates a textarea input field.
echo
$this -> Form -> textarea ( 'notes' );
Will output:
<textarea
name="data[User][notes]" id="UserNotes"
></textarea>
If the form is edited (that is, the array $this->request->data will contain the information saved for the User model), the value corresponding to notes field will automatically be added to the HTML generated. Example:
<textarea
name="data[User][notes]" id="UserNotes"
>
This text is to be edited.
</textarea>
Note: The textarea input type allows for the $options attribute of ’escape’ which determines whether or not the contents of the textarea should be escaped. Defaults to true.
echo
$this -> Form -> textarea ( 'notes' ,
array
( 'escape' =>
false
);
// OR....
echo
$this -> Form -> input (
'notes' ,
array
( 'type' => 'textarea' , 'escape' =>
false
)
);
Options
In addition to the
Common options , textarea() supports a few specific options:
•$options[’rows’], $options[’cols’] These two keys specify the number of rows and columns:
echo
$this -> Form -> textarea (
'textarea' ,
array
( 'rows' => '5' , 'cols' => '5' )
);
Output:
<textarea
name="data[Form][textarea]" cols="5" rows="5" id="FormTextarea"
>
</textarea>
More about Views 123
CakePHP Cookbook Documentation, Release 2.x
FormHelper::checkbox( string $fieldName , array $options)
Creates a checkbox form element. This method also generates an associated hidden form input to force the submission of data for the specified field.
echo
$this -> Form -> checkbox ( 'done' );
Will output:
<input
type="hidden" name="data[User][done]" value="0" id="UserDone_"
/>
<input
type="checkbox" name="data[User][done]" value="1" id="UserDone"
/>
It is possible to specify the value of the checkbox by using the $options array:
echo
$this -> Form -> checkbox ( 'done' ,
array
( 'value' => 555 ));
Will output:
<input
type="hidden" name="data[User][done]" value="0" id="UserDone_"
/>
<input
type="checkbox" name="data[User][done]" value="555" id="UserDone"
/>
If you don’t want the Form helper to create a hidden input:
echo
$this -> Form -> checkbox ( 'done' ,
array
( 'hiddenField' =>
false
));
Will output:
<input
type="checkbox" name="data[User][done]" value="1" id="UserDone"
/>
FormHelper::radio( string $fieldName , array $options, array $attributes)
Creates a set of radio button inputs.
Options
•$attributes[’value’] to set which value should be selected default.
•$attributes[’separator’] to specify HTML in between radio buttons (e.g. <br />).
•$attributes[’between’] specify some content to be inserted between the legend and first element.
•$attributes[’disabled’] Setting this to true or ’disabled’ will disable all of the generated radio buttons.
•$attributes[’legend’] Radio elements are wrapped with a legend and fieldset by default. Set $attributes[’legend’] to false to remove them.
$options =
array
( 'M' => 'Male' , 'F' => 'Female' );
$attributes =
array
( 'legend' =>
false
);
echo
$this -> Form -> radio ( 'gender' , $options , $attributes );
Will output:
<input
name="data[User][gender]" id="UserGender_" value="" type="hidden"
/>
<input
name="data[User][gender]" id="UserGenderM" value="M" type="radio"
/>
124 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
<label
for="UserGenderM"
>
Male
</label>
<input
name="data[User][gender]" id="UserGenderF" value="F" type="radio"
/>
<label
for="UserGenderF"
>
Female
</label>
If for some reason you don’t want the hidden input, setting $attributes[’value’] to a selected value or boolean false will do just that.
Changed in version 2.1: The $attributes[’disabled’] option was added in 2.1.
FormHelper::select( string $fieldName , array $options, array $attributes)
Creates a select element, populated with the items in $options, with the option specified by $attributes[’value’] shown as selected by default.
Set the ‘empty’ key in the
$attributes variable to false to turn off the default empty option:
$options =
array
( 'M' => 'Male' , 'F' => 'Female' );
echo
$this -> Form -> select ( 'gender' , $options );
Will output:
<select
name="data[User][gender]" id="UserGender"
>
<option
value=""
></option>
<option
value="M"
>
Male
</option>
<option
value="F"
>
Female
</option>
</select>
The select input type allows for a special $option attribute called ’escape’ which accepts a bool and determines whether to HTML entity encode the contents of the select options. Defaults to true:
$options =
array
( 'M' => 'Male' , 'F' => 'Female' );
echo
$this -> Form -> select ( 'gender' , $options ,
array
( 'escape' =>
false
));
•$attributes[’options’] This key allows you to manually specify options for a select input, or for a radio group. Unless the ‘type’ is specified as ‘radio’, the FormHelper will assume that the target output is a select input:
echo
$this -> Form -> select ( 'field' ,
array
( 1 , 2 , 3 , 4 , 5 ));
Output:
<select
name="data[User][field]" id="UserField"
>
<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>
Options can also be supplied as key-value pairs:
echo
$this -> Form -> select ( 'field' ,
array
(
'Value 1' => 'Label 1' ,
'Value 2' => 'Label 2' ,
More about Views 125
CakePHP Cookbook Documentation, Release 2.x
126
));
'Value 3' => 'Label 3'
Output:
<select
name="data[User][field]" id="UserField"
>
<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. This works on multiple checkboxes and radio buttons too, but instead of optgroups wraps elements in fieldsets:
$options =
array
(
'Group 1' =>
array
(
'Value 1' => 'Label 1' ,
'Value 2' => 'Label 2'
),
'Group 2' =>
array
(
'Value 3' => 'Label 3'
)
);
echo
$this -> Form -> select ( 'field' , $options );
Output:
<select
name="data[User][field]" id="UserField"
>
<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>
•$attributes[’multiple’] If ‘multiple’ has been set to true for an input that outputs a select, the select will allow multiple selections:
echo
$this -> Form -> select (
'Model.field' ,
$options ,
array
( 'multiple' =>
true
)
);
Alternatively set ‘multiple’ to ‘checkbox’ to output a list of related check boxes:
$options =
array
(
'Value 1' => 'Label 1' ,
'Value 2' => 'Label 2'
);
echo
$this -> Form -> select ( 'Model.field' , $options ,
array
(
Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
));
'multiple' => 'checkbox'
Output:
<div
class="input select"
>
<label
for="ModelField"
>
Field
</label>
<input
name="data[Model][field]" value="" id="ModelField" type="hidden"
>
<div
class="checkbox"
>
<input
name="data[Model][field][]" value="Value 1" id="ModelField1" type="checkbox"
>
<label
for="ModelField1"
>
Label 1
</label>
</div>
<div
class="checkbox"
>
<input
name="data[Model][field][]" value="Value 2" id="ModelField2" type="checkbox"
>
<label
for="ModelField2"
>
Label 2
</label>
</div>
</div>
•$attributes[’disabled’] When creating checkboxes, this option can be set to disable all or some checkboxes. To disable all checkboxes set disabled to true:
$options =
array
(
'Value 1' => 'Label 1' ,
'Value 2' => 'Label 2'
);
echo
$this -> Form -> select ( 'Model.field' , $options ,
array
(
'multiple' => 'checkbox' ,
'disabled' =>
array
( 'Value 1' )
));
Output:
<div
class="input select"
>
<label
for="ModelField"
>
Field
</label>
<input
name="data[Model][field]" value="" id="ModelField" type="hidden"
>
<div
class="checkbox"
>
<input
name="data[Model][field][]" disabled="disabled" value="Value 1" id="ModelField1" type="checkbox"
>
<label
for="ModelField1"
>
Label 1
</label>
</div>
<div
class="checkbox"
>
<input
name="data[Model][field][]" value="Value 2" id="ModelField2" type="checkbox"
>
<label
for="ModelField2"
>
Label 2
</label>
</div>
</div>
Changed in version 2.3: Support for arrays in $attributes[’disabled’] was added in 2.3.
FormHelper::file( string $fieldName
, array $options)
More about Views 127
CakePHP Cookbook Documentation, Release 2.x
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 function such as the following:
echo
$this -> Form -> create ( 'Document' ,
array
(
'enctype' => 'multipart/form-data'
));
// OR
echo
$this -> Form -> create ( 'Document' ,
array
( 'type' => 'file' ));
Next add either of the two lines to your form view file:
echo
$this -> Form -> input ( 'Document.submittedfile' ,
array
(
'between' => '<br />' ,
'type' => 'file'
));
// OR
echo
$this -> Form -> file ( 'Document.submittedfile' );
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 the CakePHP was installed on a Windows server. ‘tmp_name’ will have a different path in a Unix environment:
$this -> request -> data [ 'Document' ][ 'submittedfile' ] =
array
(
'name' => 'conference_schedule.pdf' ,
'type' => 'application/pdf' ,
'tmp_name' => 'C:/WINDOWS/TEMP/php1EE.tmp' ,
'error' => 0 ,
'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
2
Validating Uploads Below is an example validation method you could define in your model to validate whether a file has been successfully uploaded:
public function
isUploadedFile ( $params ) {
$val = array_shift ( $params );
if
(( isset ( $val [ 'error' ]) && $val [ 'error' ] == 0 ) ||
( !
empty
( $val [ 'tmp_name' ]) && $val [ 'tmp_name' ] != 'none' )
) {
return
is_uploaded_file ( $val [ 'tmp_name' ]);
}
return false
;
}
2 http://php.net/features.file-upload
128 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
Creates a file input:
echo
$this -> Form -> create ( 'User' ,
array
( 'type' => 'file' ));
echo
$this -> Form -> file ( 'avatar' );
Will output:
<form
enctype="multipart/form-data" method="post" action="/users/add"
>
<input
name="data[User][avatar]" value="" id="UserAvatar" type="file"
>
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 buttons and submit elements
FormHelper::submit( string $caption , array $options)
Creates a submit button with caption $caption. If the supplied $caption is a URL to an image
(it contains a ‘.’ character), the submit button will be rendered as an image.
It is enclosed between div tags by default; you can avoid this by declaring $options[’div’] = false :
echo
$this -> Form -> submit ();
Will output:
<div
class="submit"
><input
value="Submit" type="submit"
></div>
You can also pass a relative or absolute URL to an image for the caption parameter instead of caption text.
echo
$this -> Form -> submit ( 'ok.png' );
Will output:
<div
class="submit"
><input
type="image" src="/img/ok.png"
></div>
FormHelper::button( string $title , array $options = array())
Creates an HTML button with the specified title and a default type of “button”.
Setting
$options[’type’] will output one of the three possible button types:
1.submit: Same as the $this->Form->submit method - (the default).
2.reset: Creates a form reset button.
3.button: Creates a standard push button.
echo
$this -> Form -> button ( 'A Button' );
echo
$this -> Form -> button ( 'Another Button' ,
array
( 'type' => 'button' ));
echo
$this -> Form -> button ( 'Reset the Form' ,
array
( 'type' => 'reset' ));
echo
$this -> Form -> button ( 'Submit Form' ,
array
( 'type' => 'submit' ));
Will output:
More about Views 129
CakePHP Cookbook Documentation, Release 2.x
<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>
The button input type supports the escape option, which accepts a bool and determines whether to HTML entity encode the $title of the button. Defaults to false:
echo
$this -> Form -> button ( 'Submit Form' ,
array
(
'type' => 'submit' ,
'escape' =>
true
));
FormHelper::postButton( string $title
, mixed $url, array $options = array ())
Create a <button> tag with a surrounding <form> that submits via POST.
This method creates a <form> element. So do not use this method in some opened form. Instead use
or
to create buttons inside opened forms.
FormHelper::postLink( string $title
, mixed $url = null, array $options = array ())
Creates an HTML link, but access the URL using method POST. Requires JavaScript to be enabled in browser.
This method creates a <form> element. If you want to use this method inside of an existing form, you must use the inline or block options so that the new form can be rendered outside of its parent.
If all you are looking for is a button to submit your form, then you should use
instead.
Changed in version 2.3: The method option was added.
Changed in version 2.5: The inline and block options were added. They allow buffering the generated form tag, instead of returning with the link. This helps avoiding nested form tags. Setting
’inline’ => false will add the form tag to the postLink content block, if you want to use a custom block you can specify it using the block option instead.
Changed in version 2.6: The argument $confirmMessage was deprecated. Use confirm key in
$options instead.
Creating date and time inputs
FormHelper::dateTime( $fieldName
, $dateFormat = ‘DMY’, $timeFormat = ‘12’, $attributes
= array())
Creates a set of select inputs for date and time. Valid values for $dateformat are ‘DMY’, ‘MDY’,
‘YMD’ or ‘NONE’. Valid values for $timeFormat are ‘12’, ‘24’, and null.
You can specify not to display empty values by setting “array(‘empty’ => false)” in the attributes parameter. It will also pre-select the fields with the current datetime.
FormHelper::year( string $fieldName , int $minYear, int $maxYear, array $attributes)
Creates a select element populated with the years from $minYear to $maxYear. HTML attributes
130 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
may be supplied in $attributes. If $attributes[’empty’] is false, the select will not include an empty option:
echo
$this -> Form -> year ( 'purchased' , 2000 , date ( 'Y' ));
Will output:
<select
name="data[User][purchased][year]" id="UserPurchasedYear"
>
<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>
FormHelper::month( string $fieldName , array $attributes)
Creates a select element populated with month names:
echo
$this -> Form -> month ( 'mob' );
Will output:
<select
name="data[User][mob][month]" id="UserMobMonth"
>
<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. (Note: the default months are internationalized and can be translated using localization.):
echo
$this -> Form -> month ( 'mob' ,
array
( 'monthNames' =>
false
));
FormHelper::day( string $fieldName , array $attributes)
Creates a select element populated with the (numerical) days of the month.
To create an empty option with prompt text of your choosing (e.g. the first option is ‘Day’), you can supply the text as the final parameter as follows:
More about Views 131
CakePHP Cookbook Documentation, Release 2.x
echo
$this -> Form -> day ( 'created' );
Will output:
<select
name="data[User][created][day]" id="UserCreatedDay"
>
<option
value=""
></option>
<option
value="01"
>
1
</option>
<option
value="02"
>
2
</option>
<option
value="03"
>
3
</option>
...
<option
value="31"
>
31
</option>
</select>
FormHelper::hour( string $fieldName
, boolean $format24Hours, array $attributes)
Creates a select element populated with the hours of the day.
FormHelper::minute( string $fieldName , array $attributes)
Creates a select element populated with the minutes of the hour.
FormHelper::meridian( string $fieldName , array $attributes)
Creates a select element populated with ‘am’ and ‘pm’.
Displaying and checking errors
FormHelper::error( string $fieldName , mixed $text, array $options)
Shows a validation error message, specified by $text, for the given field, in the event that a validation error has occurred.
Options:
•‘escape’ bool Whether or not to HTML escape the contents of the error.
•‘wrap’ mixed Whether or not the error message should be wrapped in a div. If a string, will be used as the HTML tag to use.
•‘class’ string The class name for the error message
FormHelper::isFieldError( string $fieldName)
Returns true if the supplied $fieldName has an active validation error.
if
( $this -> Form -> isFieldError ( 'gender' )) {
echo
$this -> Form -> error ( 'gender' );
}
Note: When using
, errors are rendered by default.
FormHelper::tagIsInvalid()
Returns false if given form field described by the current entity has no errors. Otherwise it returns the validation message.
132 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
Setting Defaults for all fields
New in version 2.2.
You can declare a set of default options for input() using FormHelper::inputDefaults().
Changing the default options allows you to consolidate repeated options into a single method call:
$this -> Form -> inputDefaults (
array
(
'label' =>
false
,
'div' =>
false
,
'class' => 'fancy'
)
);
All inputs created from that point forward will inherit the options declared in inputDefaults. You can override the default options by declaring the option in the input() call:
echo
$this -> Form -> input ( 'password' ); // No div, no label with class 'fancy'
// has a label element same defaults
echo
$this -> Form -> input (
'username' ,
array
( 'label' => 'Username' )
);
Working with 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 CSRF and form tampering features.
As mentioned previously when using SecurityComponent, you should always close your forms using
. This will ensure that the special _Token inputs are generated.
FormHelper::unlockField(
$name)
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 name for the input:
$this -> Form -> unlockField ( 'User.id' );
FormHelper::secure( array $fields = array())
Generates a hidden field with a security hash based on the fields used in the form.
2.0 updates
$selected parameter removed
The $selected parameter was removed from several methods in FormHelper. All methods now support a $attributes[’value’] key now which should be used in place of $selected. This change simplifies the FormHelper methods, reducing the number of arguments, and reduces the duplication that
$selected created. The effected methods are:
More about Views 133
CakePHP Cookbook Documentation, Release 2.x
• FormHelper::select()
• FormHelper::dateTime()
• FormHelper::year()
• FormHelper::month()
• FormHelper::day()
• FormHelper::hour()
• FormHelper::minute()
• FormHelper::meridian()
Default URLs on forms is the current action
The default URL for all forms, is now the current URL including passed, named, and querystring parameters. You can override this default by supplying $options[’url’] in the second parameter of
$this->Form->create()
FormHelper::hidden()
Hidden fields no longer remove the class attribute. This means that if there are validation errors on hidden fields, the error-field class name will be applied.
HtmlHelper
class HtmlHelper(View $view, array $settings = array())
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 $options parameter, that allow you to tack on any extra attributes on your tags. Here are a few examples of how to use the $options parameter:
Desired attributes:
<tag
class="someClass"
/>
Array parameter: array('class' => 'someClass')
Desired attributes:
<tag
name="foo" value="bar"
/>
Array parameter: array('name' => 'foo', 'value' => 'bar')
Note: The HtmlHelper is available in all views by default. If you’re getting an error informing you that it isn’t there, it’s usually due to its name being missing from a manually configured $helpers controller variable.
Inserting Well-Formatted elements
The most important task the HtmlHelper accomplishes is creating well formed markup. Don’t be afraid to use it often - you can cache views in CakePHP in order to save some CPU cycles when views are being
134 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
rendered and delivered. This section will cover some of the methods of the HtmlHelper and how to use them.
HtmlHelper::charset( $charset=null)
Parameters
• $charset (string) – Desired character set. If null, the value of App.encoding
will be used.
Used to create a meta tag specifying the document’s character. Defaults to UTF-8
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"
/>
HtmlHelper::css( mixed $path , array $options = array())
Changed in version 2.4.
Parameters
• $path (mixed) – Either a string of the CSS file to link, or an array with multiple files
• $options (array) – An array of options or
Creates a link(s) to a CSS style-sheet. If key ‘inline’ is set to false in $options parameter, 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 /app/webroot/css directory if path doesn’t start with a ‘/’.
echo
$this -> Html -> css ( 'forms' );
Will output:
<link
rel="stylesheet" type="text/css" href="/css/forms.css"
/>
The first parameter can be an array to include multiple files.
More about Views 135
CakePHP Cookbook Documentation, Release 2.x
echo
$this -> Html -> css (
array
( 'forms' , 'tables' , 'menu' ));
Will output:
<link
rel="stylesheet" type="text/css" href="/css/forms.css"
/>
<link
rel="stylesheet" type="text/css" href="/css/tables.css"
/>
<link
rel="stylesheet" type="text/css" href="/css/menu.css"
/>
You can include CSS files from any loaded plugin using
To include app/Plugin/DebugKit/webroot/css/toolbar.css
you could use the following:
echo
$this -> Html -> css ( 'DebugKit.toolbar.css' );
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 app/webroot/css/Blog.common.css
, you would:
Changed in version 2.4.
echo $this->Html->css('Blog.common.css', array('plugin' => false));
Changed in version 2.1: The block option was added. Support for
was added.
HtmlHelper::meta( string $type , string $url = null, array $options = array())
Parameters
• $type (string) – The type meta tag you want.
• $url (mixed) – The URL for the meta tag, either a string or a
• $options (array) – An array of
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 ‘inline’ key in the $options parameter to false, ie - array(’inline’ => false).
If you set the “type” attribute using the $options parameter, CakePHP contains a few shortcuts: type translated value html text/html rss application/rss+xml atom application/atom+xml icon image/x-icon
<?php
echo
$this -> Html -> meta (
'favicon.ico' ,
'/favicon.ico' ,
array
( 'type' => 'icon' )
);
?>
// Output (line breaks added)
<link href="http://example.com/favicon.ico" title="favicon.ico" type="image/x-icon"
136 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
rel="alternate"
/>
<?php
echo
$this -> Html -> meta (
'Comments' ,
'/comments/index.rss' ,
array
( 'type' => 'rss' )
);
?>
// 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:
<?php
echo
$this -> Html -> meta (
'keywords' ,
'enter any meta keyword here'
);
?>
// Output
<meta name="keywords" content="enter any meta keyword here" />
<?php
echo
$this -> Html -> meta (
'description' ,
'enter any meta description here'
);
?>
// Output
<meta name="description" content="enter any meta description here" />
If you want to add a custom meta tag then the first parameter should be set to an array. To output a robots noindex tag use the following code:
echo
$this -> Html -> meta (
array
( 'name' => 'robots' , 'content' => 'noindex' ));
Changed in version 2.1: The block option was added.
HtmlHelper::docType( string $type = ‘xhtml-strict’)
Parameters
• $type (string) – The type of doctype being made.
Returns a (X)HTML doctype tag. Supply the doctype according to the following table:
More about Views 137
CakePHP Cookbook Documentation, Release 2.x
type translated value html4-strict HTML4 Strict html4-trans HTML4 Transitional html4-frame HTML4 Frameset html5 HTML5 xhtml-strict XHTML1 Strict xhtml-trans XHTML1 Transitional xhtml-frame XHTML1 Frameset xhtml11 XHTML1.1
echo
$this -> Html -> docType ();
// Outputs:
// <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
// "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
echo
$this -> Html -> docType ( 'html5' );
// 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">
Changed in version 2.1: The default doctype is html5 in 2.1.
HtmlHelper::style( array $data , boolean $oneline = true)
Parameters
• $data (array) – A set of key => values with CSS properties.
• $oneline (boolean) – Should the contents be on one line.
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 (
array
(
'background' => '#633' ,
'border-bottom' => '1px solid #000' ,
'padding' => '10px'
));
Will output: background : #633; border-bottom:1px solid #000; padding:10px;
HtmlHelper::image( string $path , array $options = array())
Parameters
• $path (string) – Path to the image.
• $options (array) – An array of
Creates a formatted image tag. The path supplied should be relative to /app/webroot/img/.
138 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
echo
$this -> Html -> image ( 'cake_logo.png' ,
array
( '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 $options.
echo
$this -> Html -> image ( "recipes/6.jpg" ,
array
(
"alt" => "Brownies" ,
'url' =>
array
( '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" ,
array
( 'fullBase' =>
true
));
Will output:
<img
src="http://example.com/img/logo.jpg" alt=""
/>
You can include image files from any loaded plugin using
To include app/Plugin/DebugKit/webroot/img/icon.png
You could use the following:
echo
$this -> Html -> image ( 'DebugKit.icon.png' );
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 app/webroot/img/Blog.icon.png
, you would:
echo
$this -> Html -> image ( 'Blog.icon.png' ,
array
( 'plugin' =>
false
));
Changed in version 2.1: The fullBase option was added. Support for
was added.
HtmlHelper::link( string $title , mixed $url = null, array $options = array())
Parameters
• $title (string) – The text to display as the body of the link.
• $url (mixed) – Either the string location, or a
• $options (array) – An array of
General purpose method for creating HTML links. Use $options to specify attributes for the element and whether or not the $title should be escaped.
More about Views 139
CakePHP Cookbook Documentation, Release 2.x
echo
$this -> Html -> link (
'Enter' ,
'/pages/home' ,
array
( 'class' => 'button' , 'target' => '_blank' )
);
Will output:
<a
href="/pages/home" class="button" target="_blank"
>
Enter
</a>
Use ’full_base’ => true option for absolute URLs:
echo
$this -> Html -> link (
'Dashboard' ,
array
(
'controller' => 'dashboards' ,
'action' => 'index' ,
'full_base' =>
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' ,
array
( 'controller' => 'recipes' , 'action' => 'delete' , 6 ),
array
( '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' ,
array
(
'controller' => 'images' ,
'action' => 'view' ,
1 ,
'?' =>
array
( 'height' => 400 , 'width' => 500 ))
);
Will output:
140 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
<a
href="/images/view/1?height=400&width=500"
>
View image
</a>
When using named parameters, use the array syntax and include names for ALL parameters in the
URL. Using the string syntax for paramters (i.e. “recipes/view/6/comments:false”) will result in the colon characters being HTML escaped and the link will not work as desired.
<?
php
echo
$this -> Html -> link (
$this -> Html -> image ( "recipes/6.jpg" ,
array
( "alt" => "Brownies" )),
array
(
'controller' => 'recipes' ,
'action' => 'view' ,
'id' => 6 ,
'comments' =>
false
)
);
Will output:
<a
href="/recipes/view/id:6/comments:false"
>
<img
src="/img/recipes/6.jpg" alt="Brownies"
/>
</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.
<?
php
echo
$this -> Html -> link (
$this -> Html -> image ( "recipes/6.jpg" ,
array
( "alt" => "Brownies" )),
"recipes/view/6" ,
array
( '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. As of 2.4 you can use the option escapeTitle to disable just escaping of title and not the attributes.
<?
php
echo
$this -> Html -> link (
$this -> Html -> image ( 'recipes/6.jpg' ,
array
( 'alt' => 'Brownies' )),
'recipes/view/6' ,
array
( 'escapeTitle' =>
false
, 'title' => 'hi "howdy"' )
);
Will output:
<a
href="/recipes/view/6" title="hi "howdy""
>
</a>
<img
src="/img/recipes/6.jpg" alt="Brownies"
/>
More about Views 141
CakePHP Cookbook Documentation, Release 2.x
Changed in version 2.4: The escapeTitle option was added.
Changed in version 2.6: The argument $confirmMessage was deprecated. Use confirm key in
$options instead.
Also check
method for more examples of different types of URLs.
HtmlHelper::media( string|array $path , array $options)
Parameters
• $path (string|array) – Path to the media file, relative to the webroot/{$options[’pathPrefix’]} directory. Or an array where each item itself can be a path string or an associate array containing keys src and type.
• $options (array) – Array of HTML attributes, and special 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 audio/video tag
– pathPrefix Path prefix to use for relative URLs, defaults to ‘files/’
– fullBase If set to true, the src attribute will get a full address including domain name
New in version 2.1.
Returns a formatted audio/video tag:
<?php echo $this -> Html -> media ( 'audio.mp3' ); ?>
// Output
<audio src="/files/audio.mp3"></audio>
<?php echo $this -> Html -> media ( 'video.mp4' ,
array
(
'fullBase' =>
true
,
'text' => 'Fallback text'
)); ?>
// Output
<video src="http://www.somehost.com/files/video.mp4">Fallback text</video>
<?php echo $this -> Html -> media (
array
(
'video.mp4' ,
array
(
'src' => 'video.ogg' ,
'type' => "video/ogg; codecs='theora, vorbis'"
)
),
array
( 'autoplay' )
); ?>
142 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
// Output
<video autoplay="autoplay">
<source src="/files/video.mp4" type="video/mp4"/>
<source src="/files/video.ogg" type="video/ogg;
</video> codecs='theora, vorbis'"/>
HtmlHelper::tag( string $tag , string $text, array $options)
Parameters
• $tag (string) – The tag name being generated.
• $text (string) – The contents for the tag.
• $options (array) – An array of
Returns text wrapped in a specified tag. If no text is specified then only the opening <tag> is returned.:
<?php
echo
$this -> Html -> tag ( 'span' , 'Hello World.' ,
array
( 'class' => 'welcome' ));
?>
// Output
<span class="welcome">Hello World</span>
// No text specified.
<?php
echo
$this -> Html -> tag ( 'span' ,
null
,
array
( 'class' => 'welcome' ));
?>
// Output
<span class="welcome">
Note: Text is not escaped by default but you may use $options[’escape’] = true to escape your text. This replaces a fourth parameter boolean $escape = false that was available in previous versions.
HtmlHelper::div( string $class , string $text, array $options)
Parameters
• $class (string) – The class name for the div.
• $text (string) – The content inside the div.
• $options (array) – An array of
Used for creating div-wrapped sections of markup. The first parameter specifies a CSS class, and the second is used to supply the text to be wrapped by div tags. If the ‘escape’ key has been set to true in the last parameter, $text will be printed HTML-escaped.
If no text is specified, only an opening div tag is returned.:
More about Views 143
CakePHP Cookbook Documentation, Release 2.x
<?php
echo
$this -> Html -> div ( 'error' , 'Please enter your credit card number.' );
?>
// Output
<div class="error">Please enter your credit card number.</div>
HtmlHelper::para( string $class , string $text, array $options)
Parameters
• $class (string) – The class name for the paragraph.
• $text (string) – The content inside the paragraph.
• $options (array) – An array of
Returns a text wrapped in a CSS-classed <p> tag. If no text is supplied, only a starting <p> tag is returned.:
<?php
echo
$this -> Html -> para (
null
, 'Hello World.' );
?>
// Output
<p>Hello World.</p>
HtmlHelper::script( mixed $url , mixed $options)
Parameters
• $url (mixed) – Either a string to a single JavaScript file, or an array of strings for multiple files.
• $options (array) – An array of
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[’inline’] to false, 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
/app/webroot/js directory:
echo
$this -> Html -> script ( 'scripts' );
Will output:
144 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
<script
type="text/javascript" href="/js/scripts.js"
></script>
You can link to files with absolute paths as well to link files that are not in app/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
type="text/javascript" href="http://code.jquery.com/jquery.min.js"
>
</script>
The first parameter can be an array to include multiple files.
echo
$this -> Html -> script (
array
( 'jquery' , 'wysiwyg' , 'scripts' ));
Will output:
<script
type="text/javascript" href="/js/jquery.js"
></script>
<script
type="text/javascript" href="/js/wysiwyg.js"
></script>
<script
type="text/javascript" href="/js/scripts.js"
></script>
You can append the script tag to a specific block using the block option:
echo
$this -> Html -> script ( 'wysiwyg' ,
array
( '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
To include app/Plugin/DebugKit/webroot/js/toolbar.js
you could use the following:
echo
$this -> Html -> script ( 'DebugKit.toolbar.js' );
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 app/webroot/js/Blog.plugins.js
, you would:
echo
$this -> Html -> script ( 'Blog.plugins.js' ,
array
( 'plugin' =>
false
));
Changed in version 2.1: The block option was added. Support for
was added.
HtmlHelper::scriptBlock(
$code , $options = array())
Parameters
• $code (string) – The code to go in the script tag.
• $options (array) – An array of
Generate a code block containing $code.
Set $options[’inline’] to false to have the script block appear in the script view block. Other options defined will be added as attributes
More about Views 145
CakePHP Cookbook Documentation, Release 2.x
to script tags. $this->Html->scriptBlock(’stuff’, array(’defer’ => true)); will create a script tag with defer="defer" attribute.
HtmlHelper::scriptStart( $options = array())
Parameters
• $options (array) – An array of
to be used when scriptEnd is called.
Begin a buffering code block. This code block will capture all output between scriptStart() and scriptEnd() and create an script tag. Options are the same as scriptBlock()
HtmlHelper::scriptEnd()
End a buffering script block, returns the generated script element or null if the script block was opened with inline = false.
An example of using scriptStart() and scriptEnd() would be:
$this -> Html -> scriptStart (
array
( 'inline' =>
false
));
echo
$this -> Js -> alert ( 'I am in the javascript' );
$this -> Html -> scriptEnd ();
HtmlHelper::nestedList( array $list , array $options = array(), array $itemOptions = array() , string $tag = ‘ul’)
Parameters
• $list (array) – Set of elements to list.
• $options (array) – Additional HTML attributes of the list (ol/ul) tag or if ul/ol use that as tag.
• $itemOptions (array) – Additional HTML attributes of the list item (LI) tag.
• $tag (string) – Type of list tag to use (ol/ul).
Build a nested list (UL/OL) out of an associative array:
$list =
array
(
'Languages' =>
array
(
'English' =>
array
(
'American' ,
'Canadian' ,
'British' ,
),
'Spanish' ,
'German' ,
)
);
echo
$this -> Html -> nestedList ( $list );
Output:
// Output (minus the whitespace)
<ul>
146 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
<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>
HtmlHelper::tableHeaders( array $names , array $trOptions = null, array $thOptions = null)
Parameters
• $names (array) – An array of strings to create table headings.
• $trOptions (array) – An array of
for the <tr>
• $thOptions (array) – An array of
for the <th> elements
Creates a row of table header cells to be placed inside of <table> tags.
echo
$this -> Html -> tableHeaders (
array
( 'Date' , 'Title' , 'Active' ));
Output:
<tr>
<th>
Date
</th>
<th>
Title
</th>
<th>
Active
</th>
</tr> echo
$this -> Html -> tableHeaders (
array
( 'Date' , 'Title' , 'Active' ),
array
( 'class' => 'status' ),
array
( 'class' => 'product_table' )
);
Output:
<tr
class="status"
>
<th
class="product_table"
>
Date
</th>
</tr>
<th
class="product_table"
>
Title
</th>
<th
class="product_table"
>
Active
</th>
Changed in version 2.2: tableHeaders() now accepts attributes per cell, see below.
As of 2.2 you can set attributes per column, these are used instead of the defaults provided in the
$thOptions
:
More about Views 147
CakePHP Cookbook Documentation, Release 2.x
echo
$this -> Html -> tableHeaders (
array
(
'id' ,
array
( 'Name' =>
array
( 'class' => 'highlight' )),
array
( 'Date' =>
array
( 'class' => 'sortable' ))
));
Output:
<tr>
<th>
id
</th>
<th
class="highlight"
>
Name
</th>
<th
class="sortable"
>
Date
</th>
</tr>
HtmlHelper::tableCells( array $data , array $oddTrOptions = null, array $evenTrOptions = null , $useCount = false, $continueOddEven = true)
Parameters
• $data (array) – A two dimensional array with data for the rows.
• $oddTrOptions (array) – An array of
for the odd <tr>’s.
• $evenTrOptions (array) – An array of
for the even <tr>’s.
• $useCount (boolean) – Adds class “column-$i”.
• $continueOddEven (boolean) – If false, will use a non-static $count variable, so that the odd/even count is reset to zero just for that call.
Creates table cells, in rows, assigning <tr> attributes differently for odd- and even-numbered rows.
Wrap a single table cell within an array() for specific <td>-attributes.
echo
$this -> Html -> tableCells (
array
(
array
( 'Jul 7th, 2007' , 'Best Brownies' , 'Yes' ),
array
( 'Jun 21st, 2007' , 'Smart Cookies' , 'Yes' ),
array
( '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 (
array
(
array
(
'Jul 7th, 2007' ,
array
(
'Best Brownies' ,
array
( 'class' => 'highlight' )
),
'Yes' ),
array
( 'Jun 21st, 2007' , 'Smart Cookies' , 'Yes' ),
array
(
'Aug 1st, 2006' ,
148 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
'Anti-Java Cake' ,
array
( 'No' ,
array
( 'id' => 'special' ))
));
),
Output:
<tr>
<td>
Jul 7th, 2007
</td>
<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 (
array
(
array
( 'Red' , 'Apple' ),
array
( 'Orange' , 'Orange' ),
array
( 'Yellow' , 'Banana' ),
),
array
( 'class' => 'darker' )
);
Output:
More about Views 149
CakePHP Cookbook Documentation, Release 2.x
<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>
HtmlHelper::url( mixed $url = NULL , boolean $full = false)
Parameters
• $url (mixed) – A
• $full (mixed) – Either a boolean to indicate whether or not the base path should be included or an array of options for
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 -> Html -> url (
array
(
"controller" => "posts" ,
"action" => "view" ,
"bar"
));
// Output
/ posts / view / bar
Here are a few more usage examples:
URL with named parameters:
echo
$this -> Html -> url (
array
(
"controller" => "posts" ,
"action" => "view" ,
"foo" => "bar"
));
// Output
/ posts / view / foo : bar
URL with extension:
echo
$this -> Html -> url (
array
(
"controller" => "posts" ,
"action" => "list" ,
"ext" => "rss"
));
// Output
/ posts /
list
.
rss
URL (starting with ‘/’) with the full base URL prepended:
echo
$this -> Html -> url ( '/posts' ,
true
);
150 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
// Output http :// somedomain .
com / posts
URL with GET params and named anchor:
echo
$this -> Html -> url (
array
(
"controller" => "posts" ,
"action" => "search" ,
"?" =>
array
( "foo" => "bar" ),
"#" => "first"
));
// Output
/ posts / search ?
foo = bar #first
For further information check Router::url
3 in the API.
HtmlHelper::useTag( string $tag)
Returns a formatted existent block of $tag:
$this -> Html -> useTag (
'form' ,
'http://example.com' ,
array
( 'method' => 'post' , 'class' => 'myform' )
);
Output:
<form
action="http://example.com" method="post" class="myform"
>
Changing the tags output by HtmlHelper
HtmlHelper::loadConfig( mixed $configFile , string $path = null)
The built-in tag sets for
are XHTML compliant, however if you need to generate
HTML for HTML5 you will need to create and load a new tags config file containing the tags you’d like to use. To change the tags used create app/Config/html5_tags.php containing:
$config =
array
( 'tags' =>
array
(
'css' => '<link rel="%s" href="%s" %s>' ,
'style' => '<style%s>%s</style>' ,
'charset' => '<meta charset="%s">' ,
'javascriptblock' => '<script%s>%s</script>' ,
'javascriptstart' => '<script>' ,
'javascriptlink' => '<script src="%s"%s></script>' ,
// ...
));
You can then load this tag set by calling $this->Html->loadConfig(’html5_tags’);
3 http://api.cakephp.org/2.8/class-Router.html#_url
More about Views 151
CakePHP Cookbook Documentation, Release 2.x
Creating breadcrumb trails with HtmlHelper
HtmlHelper::getCrumbs( string $separator = ‘»’
, string|array|bool $startText = false)
CakePHP has the built-in ability to automatically create a breadcrumb trail in your app. To set this up, first add something similar to 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 ( ' > ' ,
array
(
'text' => $this -> Html -> image ( 'home.png' ),
'url' =>
array
( 'controller' => 'pages' , 'action' => 'display' , 'home' ),
'escape' =>
false
));
Any keys that are not text or url will be passed to
as the $options parameter.
Changed in version 2.1: The $startText parameter now accepts an array.
HtmlHelper::addCrumb( string $name , string $link = null, mixed $options = null)
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' ,
array
( 'controller' => 'users' , 'action' => 'add' ));
This will add the output of “Home > Users > Add User” in your layout where getCrumbs was added.
HtmlHelper::getCrumbList( array $options = array() , mixed $startText)
Parameters
• $options (array) – An array of
for the containing <ul> element.
Can also contain the ‘separator’, ‘firstClass’, ‘lastClass’ and ‘escape’ options.
• $startText (string|array) – The text or element that precedes the ul.
Returns breadcrumbs as a (x)html list.
This method uses
to generate list and its elements.
Works similar to
, 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
Changed in version 2.1: The $startText parameter was added.
Changed in version 2.3: The ‘separator’, ‘firstClass’ and ‘lastClass’ options were added.
Changed in version 2.5: The ‘escape’ option was added.
JsHelper
class JsHelper(View $view, array $settings = array())
152 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
Warning: The JsHelper is currently deprecated and completely removed in 3.x. We recommend using regular JavaScript and directly interacting with JavaScript libraries where possible.
Since the beginning CakePHP’s support for JavaScript has been with Prototype/Scriptaculous. While we still think these are excellent JavaScript libraries, the community has been asking for support for other libraries. Rather than drop Prototype in favour of another JavaScript library. We created an Adapter based helper, and included 3 of the most requested libraries. Prototype/Scriptaculous, Mootools/Mootools-more, and jQuery/jQuery UI. While the API is not as expansive as the previous AjaxHelper we feel that the adapter based solution allows for a more extensible solution giving developers the power and flexibility they need to address their specific application needs.
JavaScript Engines form the backbone of the new JsHelper. A JavaScript engine translates an abstract
JavaScript element into concrete JavaScript code specific to the JavaScript library being used. In addition they create an extensible system for others to use.
Using a specific JavaScript engine
First of all download your preferred JavaScript library and place it in app/webroot/js
Then you must include the library in your page. To include it in all pages, add this line to the <head> section of app/View/Layouts/default.ctp:
echo
$this -> Html -> script ( 'jquery' ); // Include jQuery library
Replace jquery with the name of your library file (.js will be added to the name).
By default scripts are cached, and you must explicitly print out the cache. To do this at the end of each page, include this line just before the ending </body> tag:
echo
$this -> Js -> writeBuffer (); // Write cached scripts
Warning: You must include the library in your page and print the cache for the helper to function.
JavaScript engine selection is declared when you include the helper in your controller:
public
$helpers =
array
( 'Js' =>
array
( 'Jquery' ));
The above would use the Jquery Engine in the instances of JsHelper in your views. If you do not declare a specific engine, the jQuery engine will be used as the default. As mentioned before, there are three engines implemented in the core, but we encourage the community to expand the library compatibility.
Using jQuery with other libraries The jQuery library, and virtually all of its plugins are constrained within the jQuery namespace. As a general rule, “global” objects are stored inside the jQuery namespace as well, so you shouldn’t get a clash between jQuery and any other library (like Prototype, MooTools, or YUI).
That said, there is one caveat: By default, jQuery uses “$” as a shortcut for “jQuery”
To override the “$” shortcut, use the jQueryObject variable:
More about Views 153
CakePHP Cookbook Documentation, Release 2.x
$this -> Js -> JqueryEngine -> jQueryObject = '$j' ;
echo
$this -> Html -> scriptBlock (
'var $j = jQuery.noConflict();' ,
array
( 'inline' =>
false
)
);
// Tell jQuery to go into noconflict mode
Using the JsHelper inside customHelpers Declare the JsHelper in the $helpers array in your customHelper:
public
$helpers =
array
( 'Js' );
Note: It is not possible to declare a JavaScript engine inside a custom helper. Doing that will have no effect.
If you are willing to use an other JavaScript engine than the default, do the helper setup in your controller as follows:
public
$helpers =
array
(
'Js' =>
array
( 'Prototype' ),
'CustomHelper'
);
Warning: Be sure to declare the JsHelper and its engine on top of the $helpers array in your controller.
The selected JavaScript engine may disappear (replaced by the default) from the JsHelper object in your helper, if you miss to do so and you will get code that does not fit your JavaScript library.
Creating a JavaScript Engine
JavaScript engine helpers follow normal helper conventions, with a few additional restrictions. They must have the Engine suffix. DojoHelper is not good, DojoEngineHelper is correct. Furthermore, they should extend JsBaseEngineHelper in order to leverage the most of the new API.
JavaScript engine usage
The JsHelper provides a few methods, and acts as a facade for the the Engine helper. You should not directly access the Engine helper except in rare occasions. Using the facade features of the JsHelper allows you to leverage the buffering and method chaining features built-in; (method chaining only works in
PHP5).
The JsHelper by default buffers almost all script code generated, allowing you to collect scripts throughout the view, elements and layout, and output it in one place. Outputting buffered scripts is done with
$this->Js->writeBuffer(); this will return the buffer contents in a script tag. You can disable buffering wholesale with the $bufferScripts property or setting buffer => false in methods taking $options.
154 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
Since most methods in JavaScript begin with a selection of elements in the DOM, $this->Js->get() returns a $this, allowing you to chain the methods using the selection. Method chaining allows you to write shorter, more expressive code:
$this -> Js -> get ( '#foo' ) -> event ( 'click' , $eventCode );
Is an example of method chaining. Method chaining is not possible in PHP4 and the above sample would be written like:
$this -> Js -> get ( '#foo' );
$this -> Js -> event ( 'click' , $eventCode );
Common options In attempts to simplify development where JavaScript libraries can change, a common set of options is supported by JsHelper, these common options will be mapped out to the library specific options internally. If you are not planning on switching JavaScript libraries, each library also supports all of its native callbacks and options.
Callback wrapping By default all callback options are wrapped with the an anonymous function with the correct arguments. You can disable this behavior by supplying the wrapCallbacks = false in your options array.
Working with buffered scripts One drawback to previous implementation of ‘Ajax’ type features was the scattering of script tags throughout your document, and the inability to buffer scripts added by elements in the layout. The new JsHelper if used correctly avoids both of those issues. It is recommended that you place $this->Js->writeBuffer() at the bottom of your layout file above the </body> tag. This will allow all scripts generated in layout elements to be output in one place. It should be noted that buffered scripts are handled separately from included script files.
JsHelper::writeBuffer(
$options = array())
Writes all JavaScript generated so far to a code block or caches them to a file and returns a linked script.
Options
• inline - Set to true to have scripts output as a script block inline if cache is also true, a script link tag will be generated. (default true)
• cache - Set to true to have scripts cached to a file and linked in (default false)
• clear - Set to false to prevent script cache from being cleared (default true)
• onDomReady - wrap cached scripts in domready event (default true)
• safe - if an inline block is generated should it be wrapped in <![CDATA[ ... ]]> (default true)
Creating a cache file with writeBuffer() requires that webroot/js be world writable and allows a browser to cache generated script resources for any page.
JsHelper::buffer(
$content)
Add $content to the internal script buffer.
JsHelper::getBuffer(
$clear = true)
More about Views 155
CakePHP Cookbook Documentation, Release 2.x
Get the contents of the current buffer. Pass in false to not clear the buffer at the same time.
Buffering methods that are not normally buffered
Some methods in the helpers are buffered by default. The engines buffer the following methods by default:
• event
• sortable
• drag
• drop
• slider
Additionally you can force any other method in JsHelper to use the buffering. By appending an boolean to the end of the arguments you can force other methods to go into the buffer. For example the each() method does not normally buffer:
$this -> Js -> each ( 'alert("whoa!");' ,
true
);
The above would force the each() method to use the buffer. Conversely if you want a method that does buffer to not buffer, you can pass a false in as the last argument:
$this -> Js -> event ( 'click' , 'alert("whoa!");' ,
false
);
This would force the event function which normally buffers to return its result.
Other Methods
The core JavaScript Engines provide the same feature set across all libraries, there is also a subset of common options that are translated into library specific options. This is done to provide end developers with as unified an API as possible. The following list of methods are supported by all the Engines included in the CakePHP core. Whenever you see separate lists for Options and Event Options both sets of parameters are supplied in the $options array for the method.
JsHelper::object(
$data , $options = array())
Serializes $data into JSON. This method is a proxy for json_encode() with a few extra features added via the $options parameter.
Options:
•prefix - String prepended to the returned data.
•postfix - String appended to the returned data.
Example Use:
$json = $this -> Js -> object ( $data );
JsHelper::sortable(
$options = array())
Sortable generates a JavaScript snippet to make a set of elements (usually a list) drag and drop sortable.
The normalized options are:
156 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
Options
•containment - Container for move action
•handle - Selector to handle element. Only this element will start sort action.
•revert - Whether or not to use an effect to move sortable into final position.
•opacity - Opacity of the placeholder
•distance - Distance a sortable must be dragged before sorting starts.
Event Options
•start - Event fired when sorting starts
•sort - Event fired during sorting
•complete - Event fired when sorting completes.
Other options are supported by each JavaScript library, and you should check the documentation for your JavaScript library for more detailed information on its options and parameters.
Example Use:
$this -> Js -> get ( '#my-list' );
$this -> Js -> sortable (
array
(
'distance' => 5 ,
'containment' => 'parent' ,
'start' => 'onStart' ,
'complete' => 'onStop' ,
'sort' => 'onSort' ,
'wrapCallbacks' =>
false
));
Assuming you were using the jQuery engine, you would get the following code in your generated
JavaScript block
$( "#myList" ).sortable({ containment : "parent" , distance : 5 , sort : onSort, start : onStart, stop : onStop
});
JsHelper::request(
$url , $options = array())
Generate a JavaScript snippet to create an XmlHttpRequest or ‘AJAX’ request.
Event Options
•complete - Callback to fire on complete.
•success - Callback to fire on success.
•before - Callback to fire on request initialization.
•error - Callback to fire on request failure.
More about Views 157
CakePHP Cookbook Documentation, Release 2.x
Options
•method - The method to make the request with defaults to GET in more libraries
•async - Whether or not you want an asynchronous request.
•data - Additional data to send.
•update - Dom id to update with the content of the response.
•type - Data type for response. ‘json’ and ‘html’ are supported. Default is html for most libraries.
•evalScripts - Whether or not <script> tags should be eval’ed.
•dataExpression - Should the data key be treated as a callback. Useful for supplying
$options[’data’] as another JavaScript expression.
Example use:
$this -> Js -> event (
'click' ,
$this -> Js -> request (
array
( 'action' => 'foo' , 'param1' ),
array
( 'async' =>
true
, 'update' => '#element' )
)
);
JsHelper::get(
$selector)
Set the internal ‘selection’ to a CSS selector. The active selection is used in subsequent operations until a new selection is made:
$this -> Js -> get ( '#element' );
The JsHelper now will reference all other element based methods on the selection of #element.
To change the active selection, call get() again with a new element.
JsHelper::set( mixed $one
, mixed $two = null)
Pass variables into JavaScript. Allows you to set variables that will be output when the buffer is fetched with
or
variable used to output set variables can be controlled with JsHelper::$setVariable.
JsHelper::drag(
$options = array())
Make an element draggable.
Options
•handle - selector to the handle element.
•snapGrid - The pixel grid that movement snaps to, an array(x, y)
•container - The element that acts as a bounding box for the draggable element.
Event Options
•start - Event fired when the drag starts
•drag - Event fired on every step of the drag
158 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
•stop - Event fired when dragging stops (mouse release)
Example use:
$this -> Js -> get ( '#element' );
$this -> Js -> drag (
array
(
'container' => '#content' ,
'start' => 'onStart' ,
'drag' => 'onDrag' ,
'stop' => 'onStop' ,
'snapGrid' =>
array
( 10 , 10 ),
'wrapCallbacks' =>
false
));
If you were using the jQuery engine the following code would be added to the buffer
$( "#element" ).draggable({ containment : "#content" , drag : onDrag, grid : [ 10 , 10 ], start : onStart, stop : onStop
});
JsHelper::drop(
$options = array())
Make an element accept draggable elements and act as a dropzone for dragged elements.
Options
•accept - Selector for elements this droppable will accept.
•hoverclass - Class to add to droppable when a draggable is over.
Event Options
•drop - Event fired when an element is dropped into the drop zone.
•hover - Event fired when a drag enters a drop zone.
•leave - Event fired when a drag is removed from a drop zone without being dropped.
Example use:
$this -> Js -> get ( '#element' );
$this -> Js -> drop (
array
(
'accept' => '.items' ,
'hover' => 'onHover' ,
'leave' => 'onExit' ,
'drop' => 'onDrop' ,
'wrapCallbacks' =>
false
));
If you were using the jQuery engine the following code would be added to the buffer
$( "#element" ).droppable({ accept : ".items" , drop : onDrop,
More about Views 159
CakePHP Cookbook Documentation, Release 2.x
}); out : onExit, over : onHover
Note: Droppables in Mootools function differently from other libraries. Droppables are implemented as an extension of Drag. So in addition to making a get() selection for the droppable element. You must also provide a selector rule to the draggable element. Furthermore, Mootools droppables inherit all options from Drag.
JsHelper::slider(
$options = array())
Create snippet of JavaScript that converts an element into a slider ui widget. See your libraries implementation for additional usage and features.
Options
•handle - The id of the element used in sliding.
•direction - The direction of the slider either ‘vertical’ or ‘horizontal’
•min - The min value for the slider.
•max - The max value for the slider.
•step - The number of steps or ticks the slider will have.
•value - The initial offset of the slider.
Events
•change - Fired when the slider’s value is updated
•complete - Fired when the user stops sliding the handle
Example use:
$this -> Js -> get ( '#element' );
$this -> Js -> slider (
array
(
'complete' => 'onComplete' ,
'change' => 'onChange' ,
'min' => 0 ,
'max' => 10 ,
'value' => 2 ,
'direction' => 'vertical' ,
'wrapCallbacks' =>
false
));
If you were using the jQuery engine the following code would be added to the buffer
$( "#element" ).slider({ change : onChange, max : 10 , min : 0 , orientation : "vertical" , stop : onComplete,
160 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
}); value : 2
JsHelper::effect( $name , $options = array())
Creates a basic effect. By default this method is not buffered and returns its result.
Supported effect names
The following effects are supported by all JsEngines
•show - reveal an element.
•hide - hide an element.
•fadeIn - Fade in an element.
•fadeOut - Fade out an element.
•slideIn - Slide an element in.
•slideOut - Slide an element out.
Options
•speed - Speed at which the animation should occur. Accepted values are ‘slow’, ‘fast’. Not all effects use the speed option.
Example use
If you were using the jQuery engine:
$this -> Js -> get ( '#element' );
$result = $this -> Js -> effect ( 'fadeIn' );
// $result contains $("#foo").fadeIn();
JsHelper::event( $type
, $content, $options = array())
Bind an event to the current selection. $type can be any of the normal DOM events or a custom event type if your library supports them. $content should contain the function body for the callback. Callbacks will be wrapped with function (event) { ...
} unless disabled with the
$options
.
Options
•wrap - Whether you want the callback wrapped in an anonymous function. (defaults to true)
•stop - Whether you want the event to stop. (defaults to true)
Example use:
$this -> Js -> get ( '#some-link' );
$this -> Js -> event ( 'click' , $this -> Js -> alert ( 'hey you!' ));
If you were using the jQuery library you would get the following JavaScript code:
$( '#some-link' ).bind( 'click' ,
function
(event) { alert( 'hey you!' );
More about Views 161
CakePHP Cookbook Documentation, Release 2.x
});
return false
;
You can remove the return false; by passing setting the stop option to false:
$this -> Js -> get ( '#some-link' );
$this -> Js -> event (
'click' ,
$this -> Js -> alert ( 'hey you!' ),
array
( 'stop' =>
false
)
);
If you were using the jQuery library you would the following JavaScript code would be added to the buffer. Note that the default browser event is not cancelled:
$( '#some-link' ).bind( 'click' ,
function
(event) { alert( 'hey you!' );
});
JsHelper::domReady(
$callback)
Creates the special ‘DOM ready’ event.
automatically wraps the buffered scripts in a domReady method.
JsHelper::each(
$callback)
Create a snippet that iterates over the currently selected elements, and inserts $callback.
Example:
$this -> Js -> get ( 'div.message' );
$this -> Js -> each ( '$(this).css({color: "red"});' );
Using the jQuery engine would create the following JavaScript:
$( 'div.message' ).each(
function
() { $(
this
).css({color : "red" }); });
JsHelper::alert(
$message)
Create a JavaScript snippet containing an alert() snippet. By default, alert does not buffer, and returns the script snippet.
$alert = $this -> Js -> alert ( 'Hey there' );
JsHelper::confirm( $message)
Create a JavaScript snippet containing a confirm() snippet. By default, confirm does not buffer, and returns the script snippet.
$alert = $this -> Js -> confirm ( 'Are you sure?' );
JsHelper::prompt(
$message , $default)
Create a JavaScript snippet containing a prompt() snippet. By default, prompt does not buffer, and returns the script snippet.
$prompt = $this -> Js -> prompt ( 'What is your favorite color?' , 'blue' );
162 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
JsHelper::submit(
$caption = null , $options = array())
Create a submit input button that enables XmlHttpRequest submitted forms. Options can include both those for
and JsBaseEngine::request(), JsBaseEngine::event();
Forms submitting with this method, cannot send files. Files do not transfer over XmlHttpRequest and require an iframe, or other more specialized setups that are beyond the scope of this helper.
Options
•url - The URL you wish the XHR request to submit to.
•confirm - Confirm message displayed before sending the request. Using confirm, does not replace any before callback methods in the generated XmlHttpRequest.
•buffer - Disable the buffering and return a script tag in addition to the link.
•wrapCallbacks - Set to false to disable automatic callback wrapping.
Example use:
echo
$this -> Js -> submit ( 'Save' ,
array
( 'update' => '#content' ));
Will create a submit button with an attached onclick event. The click event will be buffered by default.
echo
$this -> Js -> submit ( 'Save' ,
array
(
'update' => '#content' ,
'div' =>
false
,
'type' => 'json' ,
'async' =>
false
));
Shows how you can combine options that both
and
when using submit.
JsHelper::link(
$title , $url = null, $options = array())
Create an HTML anchor element that has a click event bound to it. Options can include both those for
and
is a
array that are appended to the generated anchor element. If an option is not part of the standard attributes or $htmlAttributes it will be passed to
as an option. If an id is not supplied, a randomly generated one will be created for each link generated.
Options
•confirm - Generate a confirm() dialog before sending the event.
•id - use a custom id.
•htmlAttributes - additional non-standard htmlAttributes. Standard attributes are class, id, rel, title, escape, onblur and onfocus.
•buffer - Disable the buffering and return a script tag in addition to the link.
Example use:
echo
$this -> Js -> link (
'Page 2' ,
array
( 'page' => 2 ),
More about Views 163
CakePHP Cookbook Documentation, Release 2.x
);
array
( 'update' => '#content' )
Will create a link pointing to /page:2 and updating #content with the response.
You can use the htmlAttributes option to add in additional custom attributes.
echo
$this -> Js -> link ( 'Page 2' ,
array
( 'page' => 2 ),
array
(
'update' => '#content' ,
'htmlAttributes' =>
array
( 'other' => 'value' )
));
Outputs the following HTML:
<a
href="/posts/index/page:2" other="value"
>
Page 2
</a>
JsHelper::serializeForm( $options = array())
Serialize the form attached to $selector. Pass true for $isForm if the current selection is a form element. Converts the form or the form element attached to the current selection into a string/json object (depending on the library implementation) for use with XHR operations.
Options
•isForm - is the current selection a form, or an input? (defaults to false)
•inline - is the rendered statement going to be used inside another JS statement? (defaults to false)
Setting inline == false allows you to remove the trailing ;. This is useful when you need to serialize a form element as part of another JavaScript operation, or use the serialize method in an Object literal.
JsHelper::redirect( $url)
Redirect the page to $url using window.location.
JsHelper::value(
$value)
Converts a PHP-native variable of any type to a JSON-equivalent representation. Escapes any string values into JSON compatible strings. UTF-8 characters will be escaped.
AJAX Pagination
Much like AJAX Pagination in 1.2, you can use the JsHelper to handle the creation of AJAX pagination links instead of plain HTML links.
Making AJAX Links Before you can create AJAX links you must include the JavaScript library that matches the adapter you are using with JsHelper.
By default the JsHelper uses jQuery.
So in your layout include jQuery (or whichever library you are using).
Also make sure to include
RequestHandlerComponent in your components. Add the following to your controller:
public
$components =
array
( 'RequestHandler' );
public
$helpers =
array
( 'Js' );
Next link in the JavaScript library you want to use. For this example we’ll be using jQuery:
164 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
echo
$this -> Html -> script ( 'jquery' );
Similar to 1.2 you need to tell the PaginatorHelper that you want to make JavaScript enhanced links instead of plain HTML ones. To do so, call the options() at the top of your view:
$this -> Paginator -> options (
array
(
'update' => '#content' ,
'evalScripts' =>
true
));
The
now knows to make JavaScript enhanced links, and that those links should update the #content element. Of course this element must exist, and often times you want to wrap
$content_for_layout with a div matching the id used for the update option. You also should set evalScripts to true if you are using the Mootools or Prototype adapters, without evalScripts these libraries will not be able to chain requests together. The indicator option is not supported by JsHelper and will be ignored.
You then create all the links as needed for your pagination features. Since the JsHelper automatically buffers all generated script content to reduce the number of <script> tags in your source code you must write the buffer out. At the bottom of your view file. Be sure to include:
echo
$this -> Js -> writeBuffer ();
If you omit this you will not be able to chain AJAX pagination links. When you write the buffer, it is also cleared, so you don’t have worry about the same JavaScript being output twice.
Adding effects and transitions Since indicator is no longer supported, you must add any indicator effects yourself:
<!DOCTYPE html>
<html>
<head>
<?php echo $this -> Html -> script ( 'jquery' ); ?>
//more stuff here.
</head>
<body>
<div id="content">
<?php echo $this -> fetch ( 'content' ); ?>
</div>
<?php
echo
$this -> Html -> image (
'indicator.gif' ,
array
( 'id' => 'busy-indicator' )
);
?>
</body>
</html>
Remember to place the indicator.gif file inside app/webroot/img folder. You may see a situation where the indicator.gif displays immediately upon the page load. You need to put in this CSS #busy-indicator
{ display:none; } in your main CSS file.
More about Views 165
CakePHP Cookbook Documentation, Release 2.x
With the above layout, we’ve included an indicator image file, that will display a busy indicator animation that we will show and hide with the JsHelper. To do that we need to update our options() function:
$this -> Paginator -> options (
array
(
'update' => '#content' ,
'evalScripts' =>
true
,
'before' => $this -> Js -> get ( '#busy-indicator' ) -> effect (
'fadeIn' ,
array
( 'buffer' =>
false
)
),
'complete' => $this -> Js -> get ( '#busy-indicator' ) -> effect (
'fadeOut' ,
array
( 'buffer' =>
false
)
),
));
This will show/hide the busy-indicator element before and after the #content div is updated. Although indicator has been removed, the new features offered by JsHelper allow for more control and more complex effects to be created.
NumberHelper
class NumberHelper(View $view, array $settings = array())
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.
Changed in version 2.1: NumberHelper have been refactored into
class to allow easier use outside of the View layer. Within a view, these methods are accessible via the NumberHelper class and you can call it as you would call a normal helper method: $this->Number->method($args);.
All of these functions return the formatted number; They do not automatically echo the output into the view.
NumberHelper::currency( float $number , string $currency = ‘USD’, array $options = array())
Parameters
• $number (float) – The value to covert.
• $currency (string) – The known currency format to use.
• $options (array) – Options, see below.
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 ( $number , $currency );
// called as CakeNumber
App :: uses ( 'CakeNumber' , 'Utility' );
echo
CakeNumber :: currency ( $number , $currency );
166 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
The first parameter, $number, should be a floating point number that represents the amount of money you are expressing. The second parameter is used to choose a predefined currency formatting scheme:
$currency 1234.56, formatted by currency type
EUR
GBP
USD
C1.234,56
£1,234.56
$1,234.56
The third parameter is an array of options for further defining the output. The following options are available:
Option Description before after
The currency symbol to place before whole numbers ie. ‘$’
The currency symbol to place after decimal numbers ie. ‘c’. Set to boolean false to use no decimal symbol. eg. 0.35 => $0.35.
zero places
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 thousands Thousands separator ie. ‘,’ decimals negative
Decimal separator symbol ie. ‘.’
Symbol for negative numbers. If equal to ‘()’, the number will be wrapped with ( and ) escape wholeSymbol wholePosition fraction-
Should the output be htmlentity escaped? Defaults to true
String to use for whole numbers ie. ‘ dollars’
Either ‘before’ or ‘after’ to place the whole symbol
String to use for fraction numbers ie. ‘ cents’
Symbol fractionPosition fractionExponent
Either ‘before’ or ‘after’ to place the fraction symbol
Fraction exponent of this specific currency. Defaults to 2.
If a non-recognized $currency value is supplied, it is prepended to a USD formatted number. For example:
// called as NumberHelper
echo
$this -> Number -> currency ( '1234.56' , 'FOO' );
// Outputs
FOO 1 , 234.56
// called as CakeNumber
App :: uses ( 'CakeNumber' , 'Utility' );
echo
CakeNumber :: currency ( '1234.56' , 'FOO' );
Changed in version 2.4: The fractionExponent option was added.
NumberHelper::defaultCurrency( string $currency)
Parameters
More about Views 167
CakePHP Cookbook Documentation, Release 2.x
• $currency (string) – Set a known currency for
Setter/getter for default currency.
This removes the need always passing the currency to
and change all currency outputs by setting other default.
New in version 2.3: This method was added in 2.3
NumberHelper::addFormat( string $formatName , array $options)
Parameters
• $formatName (string) – The format name to be used in the future
• $options (array) – The array of options for this format.
Uses the same
$options keys as
Add a currency format to the Number helper. Makes reusing currency formats easier:
// called as NumberHelper
$this -> Number -> addFormat ( 'BRL' ,
array
( 'before' => 'R$' , 'thousands' => '.' , 'decimals' => ',' ));
// called as CakeNumber
App :: uses ( 'CakeNumber' , 'Utility' );
CakeNumber :: addFormat ( 'BRL' ,
array
( 'before' => 'R$' , 'thousands' => '.' , 'decimals' => ',' ));
You can now use BRL as a short form when formatting currency amounts:
// called as NumberHelper
echo
$this -> Number -> currency ( $value , 'BRL' );
// called as CakeNumber
App :: uses ( 'CakeNumber' , 'Utility' );
echo
CakeNumber :: currency ( $value , 'BRL' );
Added formats are merged with the following defaults:
array
(
'wholeSymbol'
'wholePosition'
=> '' ,
=> 'before'
'fractionSymbol' =>
false
,
'fractionPosition' => 'after' ,
,
'zero'
'places'
'thousands'
'decimals'
=>
=>
=>
=>
0
2
,
,
','
'.'
,
,
'negative'
'escape'
=>
=>
'()'
true
'fractionExponent' => 2
,
,
)
NumberHelper::precision( mixed $number
, int $precision = 3)
Parameters
• $number (float) – The value to covert
• $precision (integer) – The number of decimal places to display
168 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
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 CakeNumber
App :: uses ( 'CakeNumber' , 'Utility' );
echo
CakeNumber :: precision ( 456.91873645
, 2 );
NumberHelper::toPercentage( mixed $number , int $precision = 2, array $options = array())
Parameters
• $number (float) – The value to covert.
• $precision (integer) – The number of decimal places to display.
• $options (array) – Options, see below.
Option Description multiply
Boolean to indicate whether the value has to be multiplied by 100. Useful for decimal percentages.
Like 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 prepends the output with a percent sign.
// Called as NumberHelper. Output: 45.69%
echo
$this -> Number -> toPercentage ( 45.691873645
);
// Called as CakeNumber. Output: 45.69%
App :: uses ( 'CakeNumber' , 'Utility' );
echo
CakeNumber :: toPercentage ( 45.691873645
);
// Called with multiply. Output: 45.69%
echo
CakeNumber :: toPercentage ( 0.45691
, 2 ,
array
(
'multiply' =>
true
));
New in version 2.4: The $options argument with the multiply option was added.
NumberHelper::fromReadableSize( string $size , $default)
Parameters
• $size (string) – The formatted human readable value.
This method unformats a number from a human readable byte size to an integer number of bytes.
New in version 2.3: This method was added in 2.3
NumberHelper::toReadableSize( string $dataSize)
More about Views 169
CakePHP Cookbook Documentation, Release 2.x
Parameters
• $dataSize (string) – The number of bytes to make readable.
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 Bytes
echo
$this -> Number -> toReadableSize ( 1024 ); // 1 KB
echo
$this -> Number -> toReadableSize ( 1321205.76
); // 1.26 MB
echo
$this -> Number -> toReadableSize ( 5368709120 ); // 5.00 GB
// called as CakeNumber
App :: uses ( 'CakeNumber' , 'Utility' );
echo
CakeNumber :: toReadableSize ( 0 ); // 0 Bytes
echo
CakeNumber :: toReadableSize ( 1024 ); // 1 KB
echo
CakeNumber :: toReadableSize ( 1321205.76
); // 1.26 MB
echo
CakeNumber :: toReadableSize ( 5368709120 ); // 5.00 GB
NumberHelper::format( mixed $number , mixed $options=false)
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 ( $number , $options );
// called as CakeNumber
CakeNumber :: format ( $number , $options );
The $number 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:
–places (integer): the amount of desired precision
–before (string): to be put before the outputted number
–escape (boolean): if you want the value in before to be escaped
Example:
–decimals (string): used to delimit the decimal places in a number
–thousands (string): used to mark off thousand, millions, . . . places
// called as NumberHelper
echo
$this -> Number -> format ( '123456.7890' ,
array
(
'places' => 2 ,
170 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
'before' => '¥ ' ,
'escape' =>
false
,
'decimals' => '.' ,
'thousands' => ','
));
// output '¥ 123,456.79'
// called as CakeNumber
App :: uses ( 'CakeNumber' , 'Utility' );
echo
CakeNumber :: format ( '123456.7890' ,
array
(
'places' => 2 ,
'before' => '¥ ' ,
'escape' =>
false
,
'decimals' => '.' ,
'thousands' => ','
));
// output '¥ 123,456.79'
NumberHelper::formatDelta( mixed $number , mixed $options=array())
This method displays differences in value as a signed number:
// called as NumberHelper
$this -> Number -> formatDelta ( $number , $options );
// called as CakeNumber
CakeNumber :: formatDelta ( $number , $options );
The $number 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
itself:
•places (integer): the amount of desired precision
•before (string): to be put before the outputted number
•after (string): to be put after the outputted number
•decimals (string): used to delimit the decimal places in a number
•thousands (string): used to mark off thousand, millions, . . . places
Example:
// called as NumberHelper
echo
$this -> Number -> formatDelta ( '123456.7890' ,
array
(
'places' => 2 ,
'decimals' => '.' ,
'thousands' => ','
));
// output '+123,456.79'
// called as CakeNumber
App :: uses ( 'CakeNumber' , 'Utility' );
More about Views 171
CakePHP Cookbook Documentation, Release 2.x
echo
CakeNumber :: formatDelta ( '123456.7890' ,
array
(
'places' => 2 ,
'decimals' => '.' ,
'thousands' => ','
));
// output '+123,456.79'
New in version 2.3: This method was added in 2.3
Warning: Since 2.4 the symbols are now UTF-8. Please see the migration guide for details if you run a non-UTF-8 app.
PaginatorHelper
class PaginatorHelper(View $view, array $settings = array())
The Pagination helper is used to output pagination controls such as page numbers and next/previous links.
It works in tandem with
See also
for information on how to create paginated datasets and do paginated queries.
Creating sort links
PaginatorHelper::sort(
$key , $title = null, $options = array())
Parameters
• $key (string) – The name of the key that the recordset should be sorted.
• $title (string) – Title for the link. If $title is null $key will be used for the title and will be generated by inflection.
• $options (array) – Options for sorting link.
Generates a sorting link. Sets named or 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. Link sorting default by ‘asc’. 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.
New in version 2.5: You can now set the lock option to true in order to lock the sorting direction into the specified direction.
Assuming you are paginating some posts, and are on page one:
172 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
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>' ,
);
array
( '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
,
array
( '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
,
array
( 'direction' => 'asc' , 'lock' =>
true
));
PaginatorHelper::sortDir( string $model = null , mixed $options = array())
Gets the current direction the recordset is sorted.
PaginatorHelper::sortKey( string $model = null
, mixed $options = array())
Gets the current key by which the recordset is sorted.
Creating page number links
PaginatorHelper::numbers(
$options = array())
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.
More about Views 173
CakePHP Cookbook Documentation, Release 2.x
Supported options are:
• 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.
• separator Separator content defaults to ‘‘ | ‘‘
• tag The tag to wrap links in, defaults to ‘span’.
• 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 (
array
( '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.
• ellipsis Ellipsis content, defaults to ‘...’
• class The class name used on the wrapping tag.
• currentClass The class name to use on the current/active link. Defaults to current.
• currentTag Tag to use for current page number, defaults to null. This allows you to generate for example Twitter Bootstrap like links with the current page number wrapped in extra ‘a’ or ‘span’ tag.
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 (
array
( 'first' => 2 , 'last' => 2 ));
New in version 2.1: The currentClass option was added in 2.1.
New in version 2.3: The currentTag option was added in 2.3.
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.
PaginatorHelper::prev( $title = ‘<< Previous’
, $options = array(), $disabledTitle = null,
$disabledOptions = array())
Parameters
174 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
• $title (string) – Title for the link.
• $options (mixed) – Options for pagination link.
• $disabledTitle (string) – Title when the link is disabled, as when you’re already on the first page, no previous page to go.
• $disabledOptions (mixed) – Options for the disabled pagination link.
Generates a link to the previous page in a set of paged records.
$options and $disabledOptions supports the following keys:
•tag The tag wrapping tag you want to use, defaults to ‘span’. Set this to false to disable this option.
•escape Whether you want the contents HTML entity encoded, defaults to true.
•model The model to use, defaults to
PaginatorHelper::defaultModel()
•disabledTag Tag to use instead of A tag when there is no previous page
A simple example would be:
echo
$this -> Paginator -> prev (
' << ' .
__( 'previous' ),
array
(),
null
,
);
array
( 'class' => 'prev disabled' )
If you were currently on the second page of posts, you would get the following:
<span class="prev">
<a rel="prev" href="/posts/index/page:1/sort:title/order:desc">
<< previous
</a>
</span>
If there were no previous pages you would get:
<span class="prev disabled"><< previous</span>
You can change the wrapping tag using the tag option:
echo
$this -> Paginator -> prev (__( 'previous' ),
array
( 'tag' => 'li' ));
Output:
<li
class="prev"
>
<a
rel="prev" href="/posts/index/page:1/sort:title/order:desc"
>
previous
</a>
</li>
You can also disable the wrapping tag:
More about Views 175
CakePHP Cookbook Documentation, Release 2.x
echo
$this -> Paginator -> prev (__( 'previous' ),
array
( 'tag' =>
false
));
Output:
<a
class="prev" rel="prev" href="/posts/index/page:1/sort:title/order:desc"
>
previous
</a>
Changed in version 2.3: For methods:
and
it is now possible to set the tag option to false to disable the wrapper. New options disabledTag has been added.
If you leave the $disabledOptions empty the $options parameter will be used. This can save some additional typing if both sets of options are the same.
PaginatorHelper::next(
$title = ‘Next >>’ , $options = array(), $disabledTitle = null, $disabledOptions = array())
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
PaginatorHelper::first(
$first = ‘<< first’ , $options = array())
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:
•tag The tag wrapping tag you want to use, defaults to ‘span’
•after Content to insert after the link/tag
•model The model to use defaults to
PaginatorHelper::defaultModel()
•separator Content between the generated links, defaults to ‘ | ‘
•ellipsis Content for ellipsis, defaults to ‘...’
PaginatorHelper::last(
$last = ‘last >>’ , $options = array())
This method works very much like the
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.
PaginatorHelper::current( string $model = null)
Gets the current page of the recordset for the given model:
176 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
// Our URL is: http://example.com/comments/view/page:3
echo
$this -> Paginator -> current ( 'Comment' );
// Output is 3
PaginatorHelper::hasNext( string $model = null)
Returns true if the given result set is not at the last page.
PaginatorHelper::hasPrev( string $model = null)
Returns true if the given result set is not at the first page.
PaginatorHelper::hasPage( string $model = null , integer $page = 1)
Returns true if the given result set has the page number given by $page.
Creating a page counter
PaginatorHelper::counter(
$options = array())
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’. This option was added in 2.0.
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 (
array
(
'format' => 'range'
));
More about Views 177
CakePHP Cookbook Documentation, Release 2.x
• separator The separator between the actual page and the number of pages. Defaults to ‘ of ‘. This is used in conjunction with ‘format’ = ‘pages’ which is ‘format’ default value:
echo
$this -> Paginator -> counter (
array
(
'separator' => ' of a total of '
));
• model The name of the model being paginated, defaults to
PaginatorHelper::defaultModel()
This is used in conjunction with the custom string on ‘format’ option.
Modifying the options PaginatorHelper uses
PaginatorHelper::options( $options = array())
Parameters
• $options (mixed) – Default options for pagination links. If a string is supplied - it is used as the DOM id element to update.
Sets all the options for the Paginator Helper. 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 (
array
(
'url' =>
array
(
'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 pass and named parameters. So you don’t have to do that in each view file.
• escape Defines if the title field for links should be HTML escaped. Defaults to true.
• update The CSS selector of the element to update with the results of AJAX pagination calls. If not specified, regular links will be created:
$this -> Paginator -> options (
array
( 'update' => '#content' ));
This is useful when doing
AJAX Pagination . Keep in mind that the value of update can be any valid
CSS selector, but most often is simpler to use an id selector.
178 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
• model The name of the
PaginatorHelper::defaultModel()
model being paginated, defaults to
Using GET parameters for pagination Normally Pagination in CakePHP uses
are times you want to use GET parameters instead. While the main configuration option for this feature is in
, you have some additional control in the view. You can use options() to
indicate that you want other named parameters to be converted:
$this -> Paginator -> options (
array
(
'convertKeys' =>
array
( 'your' , 'keys' , 'here' )
));
Configuring the PaginatorHelper to use a JavaScript helper By default the PaginatorHelper uses
to do AJAX features. However, if you don’t want that and want to use a custom helper for AJAX links, you can do so by changing the $helpers array in your controller. After running paginate() do the following:
// In your controller action.
$this -> set ( 'posts' , $this -> paginate ());
$this -> helpers [ 'Paginator' ] =
array
( 'ajax' => 'CustomJs' );
Will change the PaginatorHelper to use the CustomJs for AJAX operations. You could also set the ‘ajax’ key to be any helper, as long as that class implements a link() method that behaves like
Pagination in Views
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
4 in the API. As mentioned, the PaginatorHelper also offers sorting features which can be easily integrated into your table column headers:
// app/View/Posts/index.ctp
<table>
<tr>
<th> <?php echo $this -> Paginator -> sort ( 'id' , 'ID' ); ?> </th>
<th> <?php echo $this -> Paginator -> sort ( 'title' , 'Title' ); ?> </th>
</tr>
<?php foreach ( $data
as
$recipe ) : ?>
<tr>
</tr>
<?php endforeach ; ?>
</table>
<td> <?php echo $recipe [ 'Recipe' ][ 'id' ]; ?> </td>
<td> <?php echo h( $recipe [ 'Recipe' ][ 'title' ]); ?> </td>
4 http://api.cakephp.org/2.8/class-PaginatorHelper.html
More about Views 179
CakePHP Cookbook Documentation, Release 2.x
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>
<?php echo $this->Paginator->sort('title', 'Title'); ?>
</th>
<th>
<?php echo $this->Paginator->sort('Author.name', 'Author'); ?>
</th>
</tr>
<?php foreach ($data as $recipe): ?>
<tr>
<td>
<?php echo h($recipe['Recipe']['title']); ?>
</td>
<td>
<?php echo h($recipe['Author']['name']); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
The final ingredient to pagination display in views is the addition of page navigation, also supplied by the
PaginationHelper:
// Shows the page numbers
echo
$this -> Paginator -> numbers ();
// Shows the next and previous links
echo
$this -> Paginator -> prev (
'« Previous' ,
null
,
null
,
array
( 'class' => 'disabled' )
);
echo
$this -> Paginator -> next (
'Next »' ,
null
,
);
null
,
array
( 'class' => 'disabled' )
// prints X of Y, where X is current page and Y is number of pages
echo
$this -> Paginator -> counter ();
The wording output by the counter() method can also be customized using special markers:
echo
$this -> Paginator -> counter (
array
(
'format' => 'Page {:page} of {:pages}, showing {:current} records out of
{:count} total, starting on record {:start}, ending on {:end}'
));
Other Methods
PaginatorHelper::link( $title , $url = array(), $options = array())
Parameters
180 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
• $title (string) – Title for the link.
• $url (mixed) – Url for the action. See Router::url()
• $options (array) – Options for the link. See options() for list of keys.
Accepted keys for $options:
•update The Id of the DOM element you wish to update. Creates AJAX enabled links.
•escape Whether you want the contents HTML entity encoded, defaults to true.
•model The model to use, defaults to
PaginatorHelper::defaultModel()
Creates a regular or AJAX link with pagination parameters:
echo
$this -> Paginator -> link ( 'Sort by title on page 5' ,
array
( 'sort' => 'title' , 'page' => 5 , 'direction' => 'desc' ));
If created in the view for
/posts/index
Would create a link pointing at
‘/posts/index/page:5/sort:title/direction:desc’
PaginatorHelper::url(
$options = array() , $asArray = false, $model = null)
Parameters
• $options (array) – Pagination/URL options array. As used on options() or link() method.
• $asArray (boolean) – Return the URL as an array, or a URI string. Defaults to false.
• $model (string) – Which model to paginate on
By default returns a full pagination URL string for use in non-standard contexts (i.e. JavaScript).
echo
$this -> Paginator -> url (
array
( 'sort' => 'title' ),
true
);
PaginatorHelper::defaultModel()
Gets the default model of the paged sets or null if pagination is not initialized.
PaginatorHelper::params( string $model = null)
Gets the current paging parameters from the resultset for the given model: debug( $this -> Paginator -> params ());
/*
Array
(
[page] => 2
[current] => 2
[count] => 43
[prevPage] => 1
[nextPage] => 3
[pageCount] => 3
[order] =>
[limit] => 20
[options] => Array
(
More about Views 181
CakePHP Cookbook Documentation, Release 2.x
[page] => 2
[conditions] => Array
(
)
)
[paramType] => named
)
*/
PaginatorHelper::param( string $key , string $model = null)
Gets the specific paging parameter from the resultset for the given model: debug( $this -> Paginator -> param ( 'count' ));
/*
(int)43
*/
New in version 2.4: The param() method was added in 2.4.
PaginatorHelper::meta( array $options = array())
Outputs the meta-links for a paginated result set:
echo
$this -> Paginator -> meta (); // Example output for page 5
/*
<link href="/?page=4" rel="prev" /><link href="/?page=6" rel="next" />
*/
You can also append the output of the meta function to the named block:
$this -> Paginator -> meta (
array
( 'block' =>
true
));
If true is passed, the “meta” block is used.
New in version 2.6: The meta() method was added in 2.6.
RssHelper
class RssHelper(View $view, array $settings = array())
The RSS helper makes generating XML for RSS feeds easy.
Creating an RSS feed with the RssHelper
This example assumes you have a Posts Controller and Post Model already created and want to make an alternative view for RSS.
Creating an xml/rss version of posts/index is a snap with CakePHP. After a few simple steps you can simply append the desired extension .rss to posts/index making your URL posts/index.rss. Before we jump too far ahead trying to get our webservice up and running we need to do a few things. First parseExtensions needs to be activated, this is done in app/Config/routes.php:
182 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
Router :: parseExtensions ( 'rss' );
In the call above we’ve activated the .rss extension. When using
you can pass as many arguments or extensions as you want. This will activate each extension/content-type for use in your application. Now when the address posts/index.rss is requested you will get an xml version of your posts/index. However, first we need to edit the controller to add in the rss-specific code.
Controller Code It is a good idea to add RequestHandler to your PostsController’s $components array.
This will allow a lot of automagic to occur:
public
$components =
array
( 'RequestHandler' );
Our view will also use the
for formatting, so that should be added to the controller as well:
public
$helpers =
array
( 'Text' );
Before we can make an RSS version of our posts/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
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 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 () ) {
$posts = $this -> Post -> find (
'all' ,
array
( 'limit' => 20 , 'order' => 'Post.created DESC' )
);
return
$this -> set ( compact ( 'posts' ));
}
// this is not an Rss request, so deliver
// data used by website's interface
$this -> paginate [ 'Post' ] =
array
(
'order' => 'Post.created DESC' ,
'limit' => 10
);
$posts = $this -> paginate ();
$this -> set ( compact ( 'posts' ));
}
With all the View variables set we need to create an rss layout.
More about Views 183
CakePHP Cookbook Documentation, Release 2.x
Layout An Rss layout is very simple, app/View/Layouts/rss/default.ctp
: put the following contents in
if
( !
isset ( $documentData )) {
$documentData =
array
();
}
if
( !
isset ( $channelData )) {
$channelData =
array
();
}
if
( !
isset ( $channelData [ 'title' ])) {
$channelData [ 'title' ] = $this -> fetch ( 'title' );
}
$channel = $this -> Rss -> channel (
array
(), $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 posts/index.
Much like the layout file we created, we need to create a
View/Posts/rss/ directory and create a new index.ctp inside that folder. The contents of the file are below.
View Our view, located at app/View/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
method which is analogous to the
method. Here though we are passing the channel’s metadata back to the layout:
$this -> set ( 'channelData' ,
array
(
'title' => __( "Most Recent Posts" ),
'link' => $this -> Html -> url ( '/' ,
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
method. The other method you can use,
which takes a callback and an array of items for the feed.
(The method I have seen used for the callback has always been 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
transforms the associative array into an element for each key value pair.
Note: You will need to modify the $postLink variable as appropriate to your application.
foreach
( $posts
as
$post ) {
$postTime = strtotime ( $post [ 'Post' ][ 'created' ]);
184 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
$postLink =
array
(
'controller' => 'posts' ,
'action' => 'view' ,
'year' => date ( 'Y' , $postTime ),
'month' => date ( 'm' , $postTime ),
'day' => date ( 'd' , $postTime ),
$post [ 'Post' ][ 'slug' ]
);
// Remove & escape any HTML to make sure the feed content will validate.
$bodyText = h( strip_tags ( $post [ 'Post' ][ 'body' ]));
$bodyText = $this -> Text -> truncate ( $bodyText , 400 ,
array
(
'ending' => '...' ,
'exact' =>
true
,
'html' =>
true
,
));
echo
$this -> Rss -> item (
array
(),
array
(
'title' => $post [ 'Post' ][ 'title' ],
'link' => $postLink ,
'guid' =>
array
( 'url' => $postLink , 'isPermaLink' => 'true' ),
'description' => $bodyText ,
'pubDate' => $post [ 'Post' ][ '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
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
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 1 or to 0 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.
Rss Helper API
property RssHelper::$action
Current action property RssHelper::$base
Base URL property RssHelper::$data
More about Views 185
CakePHP Cookbook Documentation, Release 2.x
POSTed model data property RssHelper::$field
Name of the current field property RssHelper::$helpers
Helpers used by the RSS Helper property RssHelper::$here
URL to current action property RssHelper::$model
Name of current model property RssHelper::$params
Parameter array property RssHelper::$version
Default spec version of generated RSS.
RssHelper::channel( array $attrib = array () , array $elements = array (), mixed $content = null)
Return type string
Returns an RSS <channel /> element.
RssHelper::document( array $attrib = array () , string $content = null)
Return type string
Returns an RSS document wrapped in <rss /> tags.
RssHelper::elem( string $name , array $attrib = array (), mixed $content = null, boolean $end-
Tag = true)
Return type string
Generates an XML element.
RssHelper::item( array $att = array () , array $elements = array ())
Return type string
Converts an array into an <item /> element and its contents.
RssHelper::items( array $items , mixed $callback = null)
Return type string
Transforms an array of data using an optional callback, and maps it to a set of <item /> tags.
RssHelper::time( mixed $time)
Return type string
Converts a time in any format to an RSS time. See
186 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
SessionHelper
class SessionHelper(View $view, array $settings = array())
As a natural counterpart to the Session Component, the Session Helper replicates most of the component’s functionality and makes it available in your view.
The major difference between the Session Helper and the Session Component is that the helper does not have the ability to write to the session.
As with the Session Component, data is read by using
array structures:
array
( 'User' =>
array
(
'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 Session helper methods wherever a $key is used.
SessionHelper::read( string $key)
Return type mixed
Read from the Session. Returns a string or array depending on the contents of the session.
SessionHelper::consume(
$name)
Return type mixed
Read and delete a value from the Session. This is useful when you want to combine reading and deleting values in a single operation.
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.
SessionHelper::error()
Return type string
Returns last error encountered in a session.
SessionHelper::valid()
Return type boolean
Used to check whether a session is valid in a view.
Displaying notifications or flash messages
SessionHelper::flash( string $key = ‘flash’
, array $params = array())
Deprecated since version 2.7.0: You should use
to render flash messages.
More about Views 187
CakePHP Cookbook Documentation, Release 2.x
As explained in
Creating notification messages , you can create one-time notifications for feedback.
After creating messages with
them. Once a message is displayed, it will be removed and not displayed again:
echo
$this -> Session -> flash ();
The above will output a simple message with the following HTML:
<div
id="flashMessage" class="message"
>
Your stuff has been saved.
</div>
As with the component method, you can set additional properties and customize which element is used. In the controller, you might have code like:
// in a controller
$this -> Session -> setFlash ( 'The user could not be deleted.' );
When outputting this message, you can choose the element used to display the message:
// in a layout.
echo
$this -> Session -> flash ( 'flash' ,
array
( 'element' => 'failure' ));
This would use View/Elements/failure.ctp to render the message. The message text would be available as $message in the element.
The failure element would contain something like this:
<div class="flash flash-failure">
<?php echo h( $message ); ?>
</div>
You can also pass additional parameters into the flash() method, which allows you to generate customized messages:
// In the controller
$this -> Session -> setFlash ( 'Thanks for your payment.' );
// In the layout.
echo
$this -> Session -> flash ( 'flash' ,
array
(
'params' =>
array
( 'name' => $user [ 'User' ][ 'name' ])
'element' => 'payment'
));
// View/Elements/payment.ctp
< div class = "flash payment" >
<?
php printf ( $message , h( $name )); ?>
</div>
Note: By default, CakePHP does not escape the HTML in flash messages. If you are using any request or user data in your flash messages, you should escape it with
when formatting your messages.
188 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
TextHelper
class TextHelper(View $view, array $settings = array())
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.
Changed in version 2.1: Several TextHelper methods have been moved into the String class to allow easier use outside of the View layer. Within a view, these methods are accessible via the TextHelper class.
You can call one as you would call a normal helper method: $this->Text->method($args);.
TextHelper::autoLinkEmails( string $text , array $options=array())
Parameters
• $text (string) – The text to convert.
• $options (array) – An array of
for the generated links.
Adds links to the well-formed email addresses in $text, according to any options defined in
$options
(see
$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 >
Changed in version 2.1: In 2.1 this method automatically escapes its input. Use the escape option to disable this if necessary.
TextHelper::autoLinkUrls( string $text , array $options=array())
Parameters
• $text (string) – The text to convert.
• $options (array) – An array
for the generated links
Same as autoLinkEmails(), only this method searches for strings that start with https, http, ftp, or nntp and links them appropriately.
Changed in version 2.1: In 2.1 this method automatically escapes its input. Use the escape option to disable this if necessary.
TextHelper::autoLink( string $text , array $options=array())
Parameters
• $text (string) – The text to autolink.
• $options (array) – An array
for the generated links
More about Views 189
CakePHP Cookbook Documentation, Release 2.x
Performs the functionality in both autoLinkUrls() and autoLinkEmails() on the supplied
$text
. All URLs and emails are linked appropriately given the supplied $options.
Changed in version 2.1: As of 2.1, this method automatically escapes its input. Use the escape option to disable this if necessary.
TextHelper::autoParagraph( string $text)
Parameters
• $text (string) – The text to convert.
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 );
Output:
< p >
For
more information < br /> regarding our world famous pastries
and
desserts .< p >
< p > contact info @ example .
com </ p >
New in version 2.4.
TextHelper::highlight( string $haystack
, string $needle, array $options = array())
Parameters
• $haystack (string) – The string to search.
• $needle (string) – The string to find.
• $options (array) – An array of options, see below.
Highlights $needle in $haystack using the $options[’format’] string specified or a default string.
Options:
•‘format’ - string The piece of HTML with that the phrase 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' ,
array
( 'format' => '<span class="highlight">\1</span>' )
);
// called as CakeText
190 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
App :: uses ( 'CakeText' , 'Utility' );
echo
CakeText :: highlight (
$lastSentence ,
'using' ,
array
( '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 .
TextHelper::stripLinks(
$text)
Strips the supplied $text of any HTML links.
TextHelper::truncate( string $text , int $length=100, array $options)
Parameters
• $text (string) – The text to truncate.
• $length (int) – The length, in characters, beyond which the text should be truncated.
• $options (array) – An array of options to use.
If $text is longer than $length characters, this method truncates it at $length and adds a prefix 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.
$options is used to pass all extra parameters, and has the following possible keys by default, all of which are optional:
array
(
'ellipsis' => '...' ,
'exact' =>
true
,
'html' =>
false
)
Example:
// called as TextHelper
echo
$this -> Text -> truncate (
'The killer crept forward and tripped on the rug.' ,
22 ,
array
(
'ellipsis' => '...' ,
'exact' =>
false
)
);
// called as CakeText
App :: uses ( 'CakeText' , 'Utility' );
echo
CakeText :: truncate (
More about Views 191
CakePHP Cookbook Documentation, Release 2.x
'The killer crept forward and tripped on the rug.' ,
22 ,
array
(
'ellipsis' => '...' ,
'exact' =>
false
)
);
Output:
The killer crept ...
Changed in version 2.3: ending has been replaced by ellipsis. ending is still used in 2.2.1
TextHelper::tail( string $text , int $length=100, array $options)
Parameters
• $text (string) – The text to truncate.
• $length (int) – The length, in characters, beyond which the text should be truncated.
• $options (array) – An array of options to use.
If $text is longer than $length characters, this method removes an initial substring with length consisting of the difference and prepends a suffix 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:
array
(
'ellipsis' => '...' ,
'exact' =>
true
)
New in version 2.3.
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'
// called as TextHelper
echo
$this -> Text -> tail (
$sampleText ,
70 ,
array
(
'ellipsis' => '...' ,
'exact' =>
false
)
);
// called as CakeText
192 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
App :: uses ( 'CakeText' , 'Utility' );
echo
CakeText :: tail (
$sampleText ,
70 ,
array
(
'ellipsis' => '...' ,
'exact' =>
false
)
);
Output:
...
a TV, a C # program that can divide by zero, death metal t-shirts
TextHelper::excerpt( string $haystack
, string $needle, integer $radius=100, string $ellipsis=”...”)
Parameters
• $haystack (string) – The string to search.
• $needle (string) – The string to excerpt around.
• $radius (int) – The number of characters on either side of $needle you want to include.
• $ellipsis (string) – Text to append/prepend to the beginning or end of the result.
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 CakeText
App :: uses ( 'CakeText' , 'Utility' );
echo
CakeText :: excerpt ( $lastParagraph , 'method' , 50 , '...' );
Output:
...
by $radius ,
and
prefix / suffix with $ellipsis .
This
method is especially handy
for
search results .
The query ...
TextHelper::toList( array $list , $and=’and’)
Parameters
• $list (array) – Array of elements to combine into a list sentence.
• $and (string) – The word used for the last join.
Creates a comma-separated list where the last two items are joined with ‘and’.
// called as TextHelper
echo
$this -> Text -> toList ( $colors );
More about Views 193
CakePHP Cookbook Documentation, Release 2.x
// called as CakeText
App :: uses ( 'CakeText' , 'Utility' );
echo
CakeText :: toList ( $colors );
Output: red, orange, yellow, green, blue, indigo
and
violet
TimeHelper
class TimeHelper(View $view, array $settings = array())
The Time Helper does what it says on the tin: saves you time. It allows for the quick processing of time related information. The Time Helper has two main tasks that it can perform:
1. It can format time strings.
2. It can test time (but cannot bend time, sorry).
Changed in version 2.1: TimeHelper has been refactored into the
class to allow easier use outside of the View layer. Within a view, these methods are accessible via the TimeHelper class and you can call it as you would call a normal helper method: $this->Time->method($args);.
Using the Helper
A common use of the Time Helper 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 app/Config/core.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 Time Helper:
echo
$this -> Time -> format (
'F jS, Y h:i A' ,
$post [ 'Post' ][ 'created' ],
null
,
);
$user [ 'User' ][ 'time_zone' ]
// Will display August 22nd, 2011 11:53 PM for a user in GMT+0
// August 22nd, 2011 03:53 PM for a user in GMT-8
// and August 23rd, 2011 09:53 AM GMT+10
Most of the Time Helper methods have a $timezone parameter. The $timezone parameter accepts a valid timezone identifier string or an instance of DateTimeZone class.
194 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
Formatting
TimeHelper::convert( $serverTime
, $timezone = NULL)
Return type integer
Converts given time (in server’s time zone) to user’s local time, given his/her timezone.
// called via TimeHelper
echo
$this -> Time -> convert ( time (), 'Asia/Jakarta' );
// 1321038036
// called as CakeTime
App :: uses ( 'CakeTime' , 'Utility' );
echo
CakeTime :: convert ( time (),
new
DateTimeZone( 'Asia/Jakarta' ));
Changed in version 2.2: $timezone parameter replaces $userOffset parameter used in 2.1 and below.
TimeHelper::convertSpecifiers( $format , $time = NULL)
Return type string
Converts a string representing the format for the function strftime and returns a Windows safe and i18n aware format.
TimeHelper::dayAsSql( $dateString
, $field_name, $timezone = NULL)
Return type string
Creates a string in the same format as daysAsSql but only needs a single date object:
// called via TimeHelper
echo
$this -> Time -> dayAsSql ( 'Aug 22, 2011' , 'modified' );
// (modified >= '2011-08-22 00:00:00') AND
// (modified <= '2011-08-22 23:59:59')
// called as CakeTime
App :: uses ( 'CakeTime' , 'Utility' );
echo
CakeTime :: dayAsSql ( 'Aug 22, 2011' , 'modified' );
Changed in version 2.2: $timezone parameter replaces $userOffset parameter used in 2.1 and below.
New in version 2.2: $dateString parameter now also accepts a DateTime object.
TimeHelper::daysAsSql( $begin
, $end, $fieldName, $timezone = NULL)
Return type string
Returns a string in the format “($field_name >= ‘2008-01-21 00:00:00’) AND ($field_name <= ‘2008-
01-25 23:59:59’)”. This is handy if you need to search for records between two dates inclusively:
// called via TimeHelper
echo
$this -> Time -> daysAsSql ( 'Aug 22, 2011' , 'Aug 25, 2011' , 'created' );
// (created >= '2011-08-22 00:00:00') AND
// (created <= '2011-08-25 23:59:59')
More about Views 195
CakePHP Cookbook Documentation, Release 2.x
// called as CakeTime
App :: uses ( 'CakeTime' , 'Utility' );
echo
CakeTime :: daysAsSql ( 'Aug 22, 2011' , 'Aug 25, 2011' , 'created' );
Changed in version 2.2: $timezone parameter replaces $userOffset parameter used in 2.1 and below.
New in version 2.2: $dateString parameter now also accepts a DateTime object.
TimeHelper::format(
$date , $format = NULL, $default = false, $timezone = NULL)
Return type string
Will return a string formatted to the given format using the PHP strftime() formatting options
5
// called via TimeHelper
echo
$this -> Time -> format ( '2011-08-22 11:53:00' , '%B %e, %Y %H:%M %p' );
// August 22, 2011 11:53 AM
echo
$this -> Time -> format ( '+2 days' , '%c' );
// 2 days from now formatted as Sun, 13 Nov 2011 03:36:10 AM EET
// called as CakeTime
App :: uses ( 'CakeTime' , 'Utility' );
echo
CakeTime :: format ( '2011-08-22 11:53:00' , '%B %e, %Y %H:%M %p' );
echo
CakeTime :: format ( '+2 days' , '%c' );
You can also provide the date/time as the first argument. When doing this you should use strftime compatible formatting. This call signature allows you to leverage locale aware date formatting which is not possible using date() compatible formatting:
// called via TimeHelper
echo
$this -> Time -> format ( '2012-01-13' , '%d-%m-%Y' , 'invalid' );
// called as CakeTime
App :: uses ( 'CakeTime' , 'Utility' );
echo
CakeTime :: format ( '2011-08-22' , '%d-%m-%Y' );
Changed in version 2.2: $format and $date parameters are in opposite order as used in 2.1 and below. $timezone parameter replaces $userOffset parameter used in 2.1 and below. $default parameter replaces $invalid parameter used in 2.1 and below.
New in version 2.2: $date parameter now also accepts a DateTime object.
TimeHelper::fromString(
$dateString , $timezone = NULL)
Return type string
Takes a string and uses strtotime
6 to convert it into a date integer:
// called via TimeHelper
echo
$this -> Time -> fromString ( 'Aug 22, 2011' );
5 http://www.php.net/manual/en/function.strftime.php
6 http://us.php.net/manual/en/function.date.php
196 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
// 1313971200
echo
$this -> Time -> fromString ( '+1 days' );
// 1321074066 (+1 day from current date)
// called as CakeTime
App :: uses ( 'CakeTime' , 'Utility' );
echo
CakeTime :: fromString ( 'Aug 22, 2011' );
echo
CakeTime :: fromString ( '+1 days' );
Changed in version 2.2: $timezone parameter replaces $userOffset parameter used in 2.1 and below.
New in version 2.2: $dateString parameter now also accepts a DateTime object.
TimeHelper::gmt(
$dateString = NULL)
Return type integer
Will return the date as an integer set to Greenwich Mean Time (GMT).
// called via TimeHelper
echo
$this -> Time -> gmt ( 'Aug 22, 2011' );
// 1313971200
// called as CakeTime
App :: uses ( 'CakeTime' , 'Utility' );
echo
CakeTime :: gmt ( 'Aug 22, 2011' );
TimeHelper::i18nFormat(
$date , $format = NULL, $invalid = false, $timezone = NULL)
Return type string
Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string. It take in account the default date format for the current language if a LC_TIME file is used. For more info about LC_TIME file check
Changed in version 2.2: $timezone parameter replaces $userOffset parameter used in 2.1 and below.
TimeHelper::nice(
$dateString = NULL , $timezone = NULL, $format = null)
Return type string
Takes a date string and outputs it in the format “Tue, Jan 1st 2008, 19:25” or as per optional $format param passed:
// called via TimeHelper
echo
$this -> Time -> nice ( '2011-08-22 11:53:00' );
// Mon, Aug 22nd 2011, 11:53
// called as CakeTime
App :: uses ( 'CakeTime' , 'Utility' );
echo
CakeTime :: nice ( '2011-08-22 11:53:00' );
TimeHelper::niceShort( $dateString = NULL
, $timezone = NULL)
More about Views 197
CakePHP Cookbook Documentation, Release 2.x
Return type string
Takes a date string and outputs it in the format “Jan 1st 2008, 19:25”. If the date object is today, the format will be “Today, 19:25”. If the date object is yesterday, the format will be “Yesterday, 19:25”:
// called via TimeHelper
echo
$this -> Time -> niceShort ( '2011-08-22 11:53:00' );
// Aug 22nd, 11:53
// called as CakeTime
App :: uses ( 'CakeTime' , 'Utility' );
echo
CakeTime :: niceShort ( '2011-08-22 11:53:00' );
Changed in version 2.2: $timezone parameter replaces $userOffset parameter used in 2.1 and below.
New in version 2.2: $dateString parameter now also accepts a DateTime object.
TimeHelper::serverOffset()
Return type integer
Returns server’s offset from GMT in seconds.
TimeHelper::timeAgoInWords( $dateString , $options = array())
Return type string
Will take a datetime string (anything that is parsable by PHP’s strtotime() function or MySQL’s datetime format) and convert it into a friendly word format like, “3 weeks, 3 days ago”:
// called via TimeHelper
echo
$this -> Time -> timeAgoInWords ( 'Aug 22, 2011' );
// on 22/8/11
// on August 22nd, 2011
echo
$this -> Time -> timeAgoInWords (
'Aug 22, 2011' ,
array
( 'format' => 'F jS, Y' )
);
// called as CakeTime
App :: uses ( 'CakeTime' , 'Utility' );
echo
CakeTime :: timeAgoInWords ( 'Aug 22, 2011' );
echo
CakeTime :: timeAgoInWords (
'Aug 22, 2011' ,
array
( 'format' => 'F jS, Y' )
);
Use the ‘end’ option to determine the cutoff point to no longer will use words; default ‘+1 month’:
// called via TimeHelper
echo
$this -> Time -> timeAgoInWords (
'Aug 22, 2011' ,
array
( 'format' => 'F jS, Y' , 'end' => '+1 year' )
);
198 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
// On Nov 10th, 2011 it would display: 2 months, 2 weeks, 6 days ago
// called as CakeTime
App :: uses ( 'CakeTime' , 'Utility' );
echo
CakeTime :: timeAgoInWords (
'Aug 22, 2011' ,
array
( 'format' => 'F jS, Y' , 'end' => '+1 year' )
);
Use the ‘accuracy’ option to determine how precise the output should be. You can use this to limit the output:
// If $timestamp is 1 month, 1 week, 5 days and 6 hours ago
echo
CakeTime :: timeAgoInWords ( $timestamp ,
array
(
'accuracy' =>
array
( 'month' => 'month' ),
'end' => '1 year'
));
// Outputs '1 month ago'
Changed in version 2.2: The accuracy option was added.
New in version 2.2: $dateString parameter now also accepts a DateTime object.
TimeHelper::toAtom(
$dateString , $timezone = NULL)
Return type string
Will return a date string in the Atom format “2008-01-12T00:00:00Z”
Changed in version 2.2: $timezone parameter replaces $userOffset parameter used in 2.1 and below.
New in version 2.2: $dateString parameter now also accepts a DateTime object.
TimeHelper::toQuarter(
$dateString , $range = false)
Return type mixed
Will return 1, 2, 3 or 4 depending on what quarter of the year the date falls in. If range is set to true, a two element array will be returned with start and end dates in the format “2008-03-31”:
// called via TimeHelper
echo
$this -> Time -> toQuarter ( 'Aug 22, 2011' );
// Would print 3
$arr = $this -> Time -> toQuarter ( 'Aug 22, 2011' ,
true
);
/*
Array
(
[0] => 2011-07-01
[1] => 2011-09-30
)
*/
// called as CakeTime
App :: uses ( 'CakeTime' , 'Utility' );
More about Views 199
CakePHP Cookbook Documentation, Release 2.x
echo
CakeTime :: toQuarter ( 'Aug 22, 2011' );
$arr = CakeTime :: toQuarter ( 'Aug 22, 2011' ,
true
);
New in version 2.2: $dateString parameter now also accepts a DateTime object.
New in version 2.4: The new option parameters relativeString (defaults to %s ago) and absoluteString
(defaults to on %s) to allow customization of the resulting output string are now available.
TimeHelper::toRSS(
$dateString , $timezone = NULL)
Return type string
Will return a date string in the RSS format “Sat, 12 Jan 2008 00:00:00 -0500”
Changed in version 2.2: $timezone parameter replaces $userOffset parameter used in 2.1 and below.
New in version 2.2: $dateString parameter now also accepts a DateTime object.
TimeHelper::toUnix( $dateString , $timezone = NULL)
Return type integer
A wrapper for fromString.
Changed in version 2.2: $timezone parameter replaces $userOffset parameter used in 2.1 and below.
New in version 2.2: $dateString parameter now also accepts a DateTime object.
TimeHelper::toServer(
$dateString , $timezone = NULL, $format = ‘Y-m-d H:i:s’)
Return type mixed
New in version 2.2: Returns a formatted date in server’s timezone.
TimeHelper::timezone(
$timezone = NULL)
Return type DateTimeZone
New in version 2.2: Returns a timezone object from a string or the user’s timezone object. If the function is called without a parameter it tries to get timezone from ‘Config.timezone’ configuration variable.
TimeHelper::listTimezones(
$filter = null , $country = null, $options = array())
Return type array
New in version 2.2: Returns a list of timezone identifiers.
Changed in version 2.8: $options now accepts array with group, abbr, before, and after keys. Specify abbr => true will append the timezone abbreviation in the <option> text.
Testing Time
TimeHelper::isToday( $dateString
, $timezone = NULL)
200 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
TimeHelper::isThisWeek(
$dateString , $timezone = NULL)
TimeHelper::isThisMonth(
$dateString , $timezone = NULL)
TimeHelper::isThisYear(
$dateString , $timezone = NULL)
TimeHelper::wasYesterday(
$dateString , $timezone = NULL)
TimeHelper::isTomorrow(
$dateString , $timezone = NULL)
TimeHelper::isFuture(
$dateString , $timezone = NULL)
New in version 2.4.
TimeHelper::isPast(
$dateString , $timezone = NULL)
New in version 2.4.
TimeHelper::wasWithinLast(
$timeInterval , $dateString, $timezone = NULL)
Changed in version 2.2: $timezone parameter replaces $userOffset parameter used in 2.1 and below.
New in version 2.2: $dateString parameter now also accepts a DateTime object.
All of the above functions return true or false when passed a date string. wasWithinLast takes an additional $timeInterval option:
// called via TimeHelper
$this -> Time -> wasWithinLast ( $timeInterval , $dateString );
// called as CakeTime
App :: uses ( 'CakeTime' , 'Utility' );
CakeTime :: wasWithinLast ( $timeInterval , $dateString ); wasWithinLast takes a time interval which is a string in the format “3 months” and accepts a time interval of seconds, minutes, hours, days, weeks, months and years (plural and not). If a time interval is not recognized (for example, if it is mistyped) then it will default to days.
Using and Configuring Helpers
You enable helpers in CakePHP by making a controller aware of them. Each controller has a
property that lists the helpers to be made available in the view. To enable a helper in your view, add the name of the helper to the controller’s $helpers array:
class BakeriesController extends
AppController {
public
$helpers =
array
( 'Form' , 'Html' , 'Js' , 'Time' );
}
Adding helpers from plugins uses the
used elsewhere in CakePHP:
class BakeriesController extends
AppController {
public
$helpers =
array
( 'Blog.Comment' );
}
You can also add helpers from within an action, so they will only be available to that action and not to the other actions in the controller. This saves processing power for the other actions that do not use the helper and helps keep the controller better organized:
More about Views 201
CakePHP Cookbook Documentation, Release 2.x
class BakeriesController extends
AppController {
public function
bake () {
$this -> helpers [] = 'Time' ;
}
public function
mix () {
// The Time helper is not loaded here and thus not available
}
}
If you need to enable a helper for all controllers, add the name of the helper to the $helpers array in
/app/Controller/AppController.php
(or create it if not present). Remember to include the default Html and Form helpers:
class AppController extends
Controller {
public
$helpers =
array
( 'Form' , 'Html' , 'Js' , 'Time' );
}
You can pass options to helpers. These options can be used to set attribute values or modify behavior of a helper:
class AwesomeHelper extends
AppHelper {
public function
__construct (View $view , $settings =
array
()) {
parent
:: __construct ( $view , $settings ); debug( $settings );
}
}
class AwesomeController extends
AppController {
public
$helpers =
array
( 'Awesome' =>
array
( 'option1' => 'value1' ));
}
As of 2.3, the options are merged with the Helper::$settings property of the helper.
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:
// app/Controller/PostsController.php
class PostsController extends
AppController {
public
$helpers =
array
(
'Html' =>
array
(
'className' => 'MyHtml'
)
);
}
// app/View/Helper/MyHtmlHelper.php
App :: uses ( 'HtmlHelper' , 'View/Helper' );
class MyHtmlHelper extends
HtmlHelper {
// Add your code to override the core HtmlHelper
}
The above would alias MyHtmlHelper to $this->Html in your views.
202 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
Note: Aliasing a helper replaces that instance anywhere that helper is used, including inside other Helpers.
Using helper settings 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 () {
parent
:: beforeRender ();
$this -> helpers [ 'CustomStuff' ] = $this -> _getCustomStuffSettings ();
}
}
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
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}
. There may come a time where you need to dynamically load a helper from inside a view. You can use the view’s HelperCollection to do this:
$mediaHelper = $this -> Helpers -> load ( 'Media' , $mediaSettings );
The HelperCollection is a
and supports the collection API used elsewhere in CakePHP.
Callback methods
Helpers feature several callbacks that allow you to augment the view rendering process. See the
and the
documentation for more information.
Creating Helpers
If a core helper (or one showcased on GitHub or in the Bakery) doesn’t fit your needs, helpers are easy to create.
Let’s say we wanted to create a helper that could be used to output a specifically crafted CSS-styled link you needed many different places in your application. In order to fit your logic into CakePHP’s existing helper structure, you’ll need to create a new class in /app/View/Helper. Let’s call our helper LinkHelper. The actual PHP class file would look something like this:
/* /app/View/Helper/LinkHelper.php */
App :: uses ( 'AppHelper' , 'View/Helper' );
class LinkHelper extends
AppHelper {
public function
makeEdit ( $title , $url ) {
More about Views 203
CakePHP Cookbook Documentation, Release 2.x
}
}
// Logic to create specially formatted link goes here...
Note: Helpers must extend either AppHelper or
or implement all the callbacks in the
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:
/* /app/View/Helper/LinkHelper.php (using other helpers) */
App :: uses ( 'AppHelper' , 'View/Helper' );
class LinkHelper extends
AppHelper {
public
$helpers =
array
( 'Html' );
public function
makeEdit ( $title , $url ) {
// Use the HTML helper to output
// formatted data:
$link = $this -> Html -> link ( $title , $url ,
array
( 'class' => 'edit' ));
return
'<div class="editOuter">' .
$link .
'</div>' ;
}
}
Using your Helper
Once you’ve created your helper and placed it in /app/View/Helper/, you’ll be able to include it in your controllers using the special variable
class PostsController extends
AppController {
public
$helpers =
array
( 'Link' );
}
Once your controller has been made aware of this new class, you can use it in your views by accessing an object named after the helper:
<!-make a link using the
new
helper -->
<?
php
echo
$this -> Link -> makeEdit ( 'Change this Recipe' , '/recipes/edit/5' ); ?>
Creating Functionality for All Helpers
All helpers extend a special class, AppHelper (just like models extend AppModel and controllers extend AppController).
To create functionality that would be available to all helpers, create
/app/View/Helper/AppHelper.php
:
204 Chapter 5. Views
CakePHP Cookbook Documentation, Release 2.x
App :: uses ( 'Helper' , 'View' );
class AppHelper extends
Helper {
public function
customMethod () {
}
}
Helper API
class Helper
The base class for Helpers. It provides a number of utility methods and features for loading other helpers.
Helper::webroot( $file)
Resolve a file name to the webroot of the application. If a theme is active and the file exists in the current theme’s webroot, the path to the themed file will be returned.
Helper::url( $url
, $full = false)
Generates an HTML escaped URL, delegates to
Helper::value(
$options = array() , $field = null, $key = ‘value’)
Get the value for a given input name.
Helper::domId(
$options = null , $id = ‘id’)
Generate a CamelCased id value for the currently selected field. Overriding this method in your
AppHelper will allow you to change how CakePHP generates ID attributes.
Callbacks
Helper::beforeRenderFile( $viewFile)
Is called before each view file is rendered. This includes elements, views, parent views and layouts.
Helper::afterRenderFile(
$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(
$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(
$viewFile)
Is called after the view has been rendered but before layout rendering has started.
Helper::beforeLayout(
$layoutFile)
Is called before layout rendering starts. Receives the layout filename as an argument.
Helper::afterLayout( $layoutFile)
Is called after layout rendering is complete. Receives the layout filename as an argument.
More about Views 205
CakePHP Cookbook Documentation, Release 2.x
206 Chapter 5. Views
डाउनलोड
विज्ञापन