Html Helper class for easy use of HTML widgets.
HtmlHelper encloses all methods needed while working with HTML pages.
__construct( View $View , array $settings array() )
Constructor
configFile
A file containing an array of tags you wish to redefine.Using the configFile
option you can redefine the tag HtmlHelper will use. The file named should be compatible with HtmlHelper::loadConfig().
View
$View
$settings
optional array() Helper::__construct()
_nestedListItem( array $items , array $options , array $itemOptions , string $tag )
Internal function to build a nested list (UL/OL) out of an associative array.
$items
$options
$itemOptions
$tag
string
HtmlHelper::nestedList()
_prepareCrumbs( string $startText , boolean $escape true )
Prepends startText to crumbs array if set
$startText
$escape
optional true array
addCrumb( string $name , string $link null , string|array $options null )
Adds a link to the breadcrumbs array.
$name
$link
optional null $options
optional null self
charset( string $charset null )
Returns a charset META-tag.
$charset
optional null string
css( string|array $path , array $options array() )
Creates a link element for CSS stylesheets.
Include one CSS file:
echo $this->Html->css('styles.css');
Include multiple CSS files:
echo $this->Html->css(array('one.css', 'two.css'));
Add the stylesheet to the $scripts_for_layout
layout var:
$this->Html->css('styles.css', array('inline' => false));
Add the stylesheet to a custom block:
$this->Html->css('styles.css', array('block' => 'layoutCss'));
inline
If set to false, the generated tag will be appended to the 'css' block, and included in the $scripts_for_layout
layout variable. Defaults to true.once
Whether or not the css file should be checked for uniqueness. If true css files will only be included once, use false to allow the same css to be included more than once per request.block
Set the name of the block link/style tag will be appended to. This overrides the inline
option.plugin
False value will prevent parsing path as a pluginrel
Defaults to 'stylesheet'. If equal to 'import' the stylesheet will be imported.fullBase
If true the URL will get a full address for the css file.$path
$path
is prefixed with '/', the path will be relative to the webroot of your application. Otherwise, the path will be relative to your CSS path, usually webroot/css.$options
optional array() string
div( string $class null , string $text null , array $options array() )
Returns a formatted DIV tag for HTML FORMs.
escape
Whether or not the contents should be html_entity escaped.$class
optional null $text
optional null $options
optional array() string
docType( string $type 'html5' )
Returns a doctype string.
Possible doctypes:
- html4-strict: HTML4 Strict. - html4-trans: HTML4 Transitional. - html4-frame: HTML4 Frameset. - html5: HTML5. Default value. - xhtml-strict: XHTML1 Strict. - xhtml-trans: XHTML1 Transitional. - xhtml-frame: XHTML1 Frameset. - xhtml11: XHTML1.1.
$type
optional 'html5' string|null
getCrumbList( array $options array() , string|array|boolean $startText false )
Returns breadcrumbs as a (x)html list
This method uses HtmlHelper::tag() to generate list and its elements. Works similar to HtmlHelper::getCrumbs(), so it uses options which every crumb was added with.
separator
Separator content to insert in between breadcrumbs, defaults to ''firstClass
Class for wrapper tag on the first breadcrumb, defaults to 'first'lastClass
Class for wrapper tag on current active page, defaults to 'last'$options
optional array() $startText
optional false HtmlHelper::getCrumbs
for details.string|null
getCrumbs( string $separator '»' , string|array|boolean $startText false )
Returns the breadcrumb trail as a sequence of »-separated links.
If $startText
is an array, the accepted keys are:
text
Define the text/content for the link.url
Define the target of the created link.All other keys will be passed to HtmlHelper::link() as the $options
parameter.
$separator
optional '»' $startText
optional false string|null
image( string $path , array $options array() )
Creates a formatted IMG element.
This method will set an empty alt attribute if one is not supplied.
Create a regular image:
echo $this->Html->image('cake_icon.png', array('alt' => 'CakePHP'));
Create an image link:
echo $this->Html->image('cake_icon.png', array('alt' => 'CakePHP', 'url' => 'http://cakephp.org'));
url
If provided an image link will be generated and the link will point at $options['url']
.fullBase
If true the src attribute will get a full address for the image file.plugin
False value will prevent parsing path as a plugin$path
$options
optional array() string
link( string $title , string|array $url null , array $options array() , string $confirmMessage false )
Creates an HTML link.
If $url starts with "http://" this is treated as an external link. Else, it is treated as a path to controller/action and parsed with the HtmlHelper::url() method.
If the $url is empty, $title is used instead.
escape
Set to false to disable escaping of title and attributes.escapeTitle
Set to false to disable escaping of title. (Takes precedence over value of escape
)confirm
JavaScript confirmation message.$title
$url
optional null $options
optional array() $confirmMessage
optional false confirm
key in $options instead.string
<a />
element.loadConfig( string|array $configFile , string $path null )
Load Html tag configuration.
Loads a file from APP/Config that contains tag data. By default the file is expected to be compatible with PhpReader:
$this->Html->loadConfig('tags.php');
tags.php could look like:
$tags = array( 'meta' => '<meta%s>' );
If you wish to store tag definitions in another format you can give an array containing the file name, and reader class name:
$this->Html->loadConfig(array('tags.ini', 'ini'));
Its expected that the tags
index will exist from any configuration file that is read. You can also specify the path to read the configuration file from, if APP/Config is not where the file is.
$this->Html->loadConfig('tags.php', APP . 'Lib' . DS);
Configuration files can define the following sections:
tags
The tags to replace.minimizedAttributes
The attributes that are represented like disabled="disabled"
docTypes
Additional doctypes to use.attributeFormat
Format for long attributes e.g. '%s="%s"'
minimizedAttributeFormat
Format for minimized attributes e.g. '%s="%s"'
$configFile
$path
optional null mixed
ConfigureException
media( string|array $path , array $options array() )
Returns an audio/video element
Using an audio file:
echo $this->Html->media('audio.mp3', array('fullBase' => true));
Outputs:
<video src="http://www.somehost.com/files/audio.mp3">Fallback text</video>
Using a video file:
echo $this->Html->media('video.mp4', array('text' => 'Fallback text'));
Outputs:
<video src="/files/video.mp4">Fallback text</video>
Using multiple video files:
echo $this->Html->media( array('video.mp4', array('src' => 'video.ogv', 'type' => "video/ogg; codecs='theora, vorbis'")), array('tag' => 'video', 'autoplay') );
Outputs:
<video autoplay="autoplay"> <source src="/files/video.mp4" type="video/mp4"/> <source src="/files/video.ogv" type="video/ogv; codecs='theora, vorbis'"/> </video>
tag
Type of media element to generate, either "audio" or "video". If tag is not provided it's guessed based on file's mime type.text
Text to include inside the audio/video tagpathPrefix
Path prefix to use for relative URLs, defaults to 'files/'fullBase
If provided the src attribute will get a full address including domain name$path
src
and type
$options
optional array() string
meta( string $type , string|array $url null , array $options array() )
Creates a link to an external resource and handles basic meta tags
Create a meta tag that is output inline:
`$this->Html->meta('icon', 'favicon.ico');
Append the meta tag to $scripts_for_layout
:
$this->Html->meta('description', 'A great page', array('inline' => false));
Append the meta tag to custom view block:
$this->Html->meta('description', 'A great page', array('block' => 'metaTags'));
inline
Whether or not the link element should be output inline. Set to false to have the meta tag included in $scripts_for_layout
, and appended to the 'meta' view block.block
Choose a custom block to append the meta tag to. Using this option will override the inline option.$type
$url
optional null $options
optional array() string
<link />
element.nestedList( array $list , array $options array() , array $itemOptions array() , string $tag 'ul' )
Build a nested list (UL/OL) out of an associative array.
$list
$options
optional array() $itemOptions
optional array() $tag
optional 'ul' string
para( string $class , string $text , array $options array() )
Returns a formatted P tag.
escape
Whether or not the contents should be html_entity escaped.$class
$text
$options
optional array() string
script( string|array $url , array|boolean $options array() )
Returns one or many <script>
tags depending on the number of scripts given.
If the filename is prefixed with "/", the path will be relative to the base path of your application. Otherwise, the path will be relative to your JavaScript path, usually webroot/js.
Include one script file:
echo $this->Html->script('styles.js');
Include multiple script files:
echo $this->Html->script(array('one.js', 'two.js'));
Add the script file to the $scripts_for_layout
layout var:
$this->Html->script('styles.js', array('inline' => false));
Add the script file to a custom block:
$this->Html->script('styles.js', array('block' => 'bodyScript'));
inline
Whether script should be output inline or into $scripts_for_layout
. When set to false, the script tag will be appended to the 'script' view block as well as $scripts_for_layout
.block
The name of the block you want the script appended to. Leave undefined to output inline. Using this option will override the inline option.once
Whether or not the script should be checked for uniqueness. If true scripts will only be included once, use false to allow the same script to be included more than once per request.plugin
False value will prevent parsing path as a pluginfullBase
If true the url will get a full address for the script file.$url
$options
optional array() mixed
<script />
tags or null if $inline is false or if $once is true and the file has been included before.scriptBlock( string $script , array $options array() )
Wrap $script in a script tag.
safe
(boolean) Whether or not the $script should be wrapped in <![CDATA[ ]]>inline
(boolean) Whether or not the $script should be added to $scripts_for_layout
/ script
block, or output inline. (Deprecated, use block
instead)block
Which block you want this script block appended to. Defaults to script
.$script
$options
optional array() mixed
$options['block']
scriptEnd( )
End a Buffered section of JavaScript capturing. Generates a script tag inline or in $scripts_for_layout
depending on the settings used when the scriptBlock was started
mixed
scriptStart( array $options array() )
Begin a script block that captures output until HtmlHelper::scriptEnd() is called. This capturing block will capture all output between the methods and create a scriptBlock from it.
safe
Whether the code block should contain a CDATAinline
Should the generated script tag be output inline or in $scripts_for_layout
$options
optional array() style( array $data , boolean $oneline true )
Builds CSS style data from an array of CSS properties
echo $this->Html->style(array('margin' => '10px', 'padding' => '10px'), true); // creates 'margin:10px;padding:10px;'
$data
$oneline
optional true string
tableCells( array $data , array $oddTrOptions null , array $evenTrOptions null , boolean $useCount false , boolean $continueOddEven true )
Returns a formatted string of table rows (TR's with TD's in them).
$data
$oddTrOptions
optional null $evenTrOptions
optional null $useCount
optional false $continueOddEven
optional true string
tableHeaders( array $names , array $trOptions null , array $thOptions null )
Returns a row of formatted and named TABLE headers.
$names
$trOptions
optional null $thOptions
optional null string
tag( string $name , string $text null , array $options array() )
Returns a formatted block tag, i.e DIV, SPAN, P.
escape
Whether or not the contents should be html_entity escaped.$name
$text
optional null $options
optional array() string
useTag( string $tag )
Returns a formatted existent block of $tags
$tag
string
__call( string $method , array $params )
Provide non fatal errors on missing method calls.
$method
$params
__get( string $name )
Lazy loads helpers. Provides access to deprecated request properties as well.
$name
mixed
__set( string $name , mixed $value )
Provides backwards compatibility access for setting values to the request object.
$name
$value
_confirm( string $message , string $okCode , string $cancelCode '' , array $options array() )
Returns a string to be used as onclick handler for confirm dialogs.
$message
$okCode
$cancelCode
optional '' $options
optional array() string
_encodeUrl( string $url )
Encodes a URL for use in HTML attributes.
$url
string
_formatAttribute( string $key , string $value , boolean $escape true )
Formats an individual attribute, and returns the string value of the composed attribute. Works with minimized attributes that have the same value as their name such as 'disabled' and 'checked'
$key
$value
$escape
optional true string
_initInputField( string $field , array $options array() )
Sets the defaults for an input tag. Will set the name, value, and id attributes for an array of html attributes.
$field
$options
optional array() array
_name( array|string $options array() , string $field null , string $key 'name' )
Gets the input field name for the current tag. Creates input name attributes using CakePHP's data[Model][field] formatting.
$options
optional array() $field
optional null $key
optional 'name' mixed
_parseAttributes( array $options , array $exclude null , string $insertBefore ' ' , string $insertAfter null )
Returns a space-delimited string with items of the $options array. If a key of $options array happens to be one of those listed in Helper::$_minimizedAttributes
And its value is one of:
Then the value will be reset to be identical with key's name. If the value is not one of these 3, the parameter is not output.
'escape' is a special option in that it controls the conversion of attributes to their html-entity encoded equivalents. Set to false to disable html-encoding.
If value for any option key is set to null
or false
, that option will be excluded from output.
$options
$exclude
optional null $insertBefore
optional ' ' $insertAfter
optional null string
_selectedArray( string|array $data , string $key 'id' )
Transforms a recordset from a hasAndBelongsToMany association to a list of selected options for a multiple select element
$data
$key
optional 'id' array
addClass( array $options array() , string $class null , string $key 'class' )
Adds the given class to the element options
$options
optional array() $class
optional null $key
optional 'class' array
afterLayout( string $layoutFile )
After layout callback. afterLayout is called after the layout has rendered.
Overridden in subclasses.
$layoutFile
afterRender( string $viewFile )
After render callback. afterRender is called after the view file is rendered but before the layout has been rendered.
Overridden in subclasses.
$viewFile
afterRenderFile( string $viewFile , string $content )
After render file callback. Called after any view fragment is rendered.
Overridden in subclasses.
$viewFile
$content
assetTimestamp( string $path )
Adds a timestamp to a file based resource based on the value of Asset.timestamp
in Configure. If Asset.timestamp is true and debug > 0, or Asset.timestamp === 'force' a timestamp will be added.
$path
string
assetUrl( string|array $path , array $options array() )
Generate URL for given asset file. Depending on options passed provides full URL with domain name. Also calls Helper::assetTimestamp() to add timestamp to local files
$path
$options
optional array() fullBase
Return full URL with domain name pathPrefix
Path prefix for relative URLs ext
Asset extension to append plugin
False value will prevent parsing path as a pluginstring
beforeLayout( string $layoutFile )
Before layout callback. beforeLayout is called before the layout is rendered.
Overridden in subclasses.
$layoutFile
beforeRender( string $viewFile )
Before render callback. beforeRender is called before the view file is rendered.
Overridden in subclasses.
$viewFile
beforeRenderFile( string $viewFile )
Before render file callback. Called before any view fragment is rendered.
Overridden in subclasses.
$viewFile
clean( string|array $output )
Used to remove harmful tags from content. Removes a number of well known XSS attacks from content. However, is not guaranteed to remove all possibilities. Escaping content is the best way to prevent all possible attacks.
$output
string|array|null
domId( array|string $options null , string $id 'id' )
Generates a DOM ID for the selected element, if one is not set. Uses the current View::entity() settings to generate a CamelCased id attribute.
$options
optional null $id
optional 'id' mixed
entity( )
Returns the entity reference of the current context as an array of identity parts
array
field( )
Gets the currently-used model field of the rendering context. Strips off field suffixes such as year, month, day, hour, min, meridian when the current entity is longer than 2 elements.
string
model( )
Gets the currently-used model of the rendering context.
string
output( string $str )
Returns a string generated by a helper method
This method can be overridden in subclasses to do generalized output post-processing
$str
string
setEntity( string $entity , boolean $setScope false )
Sets this helper's model and field properties to the dot-separated value-pair in $entity.
$entity
$setScope
optional false url( string|array $url null , boolean $full false )
Finds URL for specified action.
Returns a URL pointing at the provided parameters.
$url
optional null /products/view/23
or an array of URL parameters. Using an array for URLs will allow you to leverage the reverse routing features of CakePHP.$full
optional false string
value( array|string $options array() , string $field null , string $key 'value' )
Gets the data for the current tag
$options
optional array() $field
optional null $key
optional 'value' mixed
webroot( string $file )
Checks if a file exists when theme is used, if no file is found default location is returned
$file
string
_mergeVars( array $properties , string $class , boolean $normalize true )
Merges this objects $property with the property in $class' definition. This classes value for the property will be merged on top of $class'
This provides some of the DRY magic CakePHP provides. If you want to shut it off, redefine this method as an empty function.
$properties
$class
$normalize
optional true _set( array $properties array() )
Allows setting of multiple properties of the object in a single line of code. Will only set properties that are part of a class declaration.
$properties
optional array() _stop( integer|string $status 0 )
Stop execution of the current script. Wraps exit() making testing easier.
$status
optional 0 dispatchMethod( string $method , array $params array() )
Calls a method on this object with the given parameters. Provides an OO wrapper for call_user_func_array
$method
$params
optional array() mixed
log( string $msg , integer $type LOG_ERR , null|string|array $scope null )
Convenience method to write a message to CakeLog. See CakeLog::write() for more information on writing to logs.
$msg
$type
optional LOG_ERR $scope
optional null boolean
requestAction( string|array $url , array $extra array() )
Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.
Under the hood this method uses Router::reverse() to convert the $url parameter into a string URL. You should use URL formats that are compatible with Router::reverse()
POST and GET data can be simulated in requestAction. Use $extra['url']
for GET data. The $extra['data']
parameter allows POST data simulation.
$url
$extra
optional array() mixed
toString( )
Object-to-string conversion. Each class can override this method as necessary.
string
protected string
The name of the current model association entities are in scope of.
Helper::setEntity()
protected string
The dot separated list of elements the current field entity is for.
Helper::setEntity()
protected array
A list of strings that should be treated as suffixes, or sub inputs for a parent input. This is used for date/time inputs primarily.
array( 'year', 'month', 'day', 'hour', 'min', 'second', 'meridian' )
protected array
Minimized attributes
array( 'allowfullscreen', 'async', 'autofocus', 'autoplay', 'checked', 'compact', 'controls', 'declare', 'default', 'defaultchecked', 'defaultmuted', 'defaultselected', 'defer', 'disabled', 'enabled', 'formnovalidate', 'hidden', 'indeterminate', 'inert', 'ismap', 'itemscope', 'loop', 'multiple', 'muted', 'nohref', 'noresize', 'noshade', 'novalidate', 'nowrap', 'open', 'pauseonexit', 'readonly', 'required', 'reversed', 'scoped', 'seamless', 'selected', 'sortable', 'spellcheck', 'truespeed', 'typemustmatch', 'visible' )
protected string
The name of the current model entities are in scope of.
Helper::setEntity()
public array
Holds the fields array('field_name' => array('type' => 'string', 'length' => 100), primaryKey and validates array('field_name')
array()
© 2005–2016 The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
http://api.cakephp.org/2.7/class-HtmlHelper.html