Class JsHelper

Javascript Generator helper class for easy use of JavaScript.

JsHelper provides an abstract interface for authoring JavaScript with a given client-side library.

Object
Extended by Helper
Extended by AppHelper
Extended by JsHelper
Package: Cake\View\Helper
Copyright: Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
License: MIT License
Location: Cake/View/Helper/JsHelper.php

Properties summary

  • $_bufferedScripts protected
    array
    Scripts that are queued for output
  • $_engineName protected
    string
    Current Javascript Engine that is being used
  • $_jsVars protected
    array
    Variables to pass to Javascript.
  • boolean
    Whether or not you want scripts to be buffered or output.
  • $helpers public
    array
    Helper dependencies
  • $setVariable public
    string
    The javascript variable created by set() variables.

Magic properties summary

Inherited Properties

Method Summary

  • __call() public

    call__ Allows for dispatching of methods to the Engine Helper. methods in the Engines bufferedMethods list will be automatically buffered. You can control buffering with the buffer param as well. By setting the last parameter to any engine method to a boolean you can force or disable buffering.

  • __construct() public
    Constructor - determines engine helper
  • _createVars() protected
    Generates the object string for variables passed to javascript and adds to buffer
  • _getHtmlOptions() protected

    Parse a set of Options and extract the Html options. Extracted Html Options are removed from the $options param.

  • buffer() public
    Write a script to the buffered scripts.
  • getBuffer() public
    Get all the buffered scripts
  • link() public

    Generate an 'Ajax' link. Uses the selected JS engine to create a link element that is enhanced with Javascript. Options can include both those for HtmlHelper::link() and JsBaseEngine::request(), JsBaseEngine::event();

  • set() public

    Pass variables into Javascript. Allows you to set variables that will be output when the buffer is fetched with JsHelper::getBuffer() or JsHelper::writeBuffer() The Javascript variable used to output set variables can be controlled with JsHelper::$setVariable

  • submit() public

    Uses the selected JS engine to create a submit input element that is enhanced with Javascript. Options can include both those for FormHelper::submit() and JsBaseEngine::request(), JsBaseEngine::event();

  • value() public

    Overwrite inherited Helper::value() See JsBaseEngineHelper::value() for more information on this method.

  • writeBuffer() public

    Writes all Javascript generated so far to a code block or caches them to a file and returns a linked script. If no scripts have been buffered this method will return null. If the request is an XHR(ajax) request onDomReady will be set to false. As the dom is already 'ready'.

Method Detail

__call()source public

__call( string $method , array $params )

call__ Allows for dispatching of methods to the Engine Helper. methods in the Engines bufferedMethods list will be automatically buffered. You can control buffering with the buffer param as well. By setting the last parameter to any engine method to a boolean you can force or disable buffering.

e.g. $js->get('#foo')->effect('fadeIn', array('speed' => 'slow'), true);

Will force buffering for the effect method. If the method takes an options array you may also add a 'buffer' param to the options array and control buffering there as well.

e.g. $js->get('#foo')->event('click', $functionContents, array('buffer' => true));

The buffer parameter will not be passed onto the EngineHelper.

Parameters

string $method
Method to be called
array $params
Parameters for the method being called.

Returns

mixed
Depends on the return of the dispatched method, or it could be an instance of the EngineHelper

Overrides

Helper::__call()

__construct()source public

__construct( View $View , string|array $settings array() )

Constructor - determines engine helper

Parameters

View $View
the view object the helper is attached to.
string|array $settings optional array()
Settings array contains name of engine helper.

Overrides

Helper::__construct()

_createVars()source protected

_createVars( )

Generates the object string for variables passed to javascript and adds to buffer

_getHtmlOptions()source protected

_getHtmlOptions( array $options , array $additional array() )

Parse a set of Options and extract the Html options. Extracted Html Options are removed from the $options param.

Parameters

array $options
Options to filter.
array $additional optional array()
Array of additional keys to extract and include in the return options array.

Returns

array
Array of js options and Htmloptions

buffer()source public

buffer( string $script , boolean $top false )

Write a script to the buffered scripts.

Parameters

string $script
Script string to add to the buffer.
boolean $top optional false

If true the script will be added to the top of the buffered scripts array. If false the bottom.

Link

http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::buffer

getBuffer()source public

getBuffer( boolean $clear true )

Get all the buffered scripts

Parameters

boolean $clear optional true
Whether or not to clear the script caches (default true)

Returns

array
Array of scripts added to the request.

Link

http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::getBuffer
link( string $title , string|array $url null , array $options array() )

Generate an 'Ajax' link. Uses the selected JS engine to create a link element that is enhanced with Javascript. Options can include both those for HtmlHelper::link() and JsBaseEngine::request(), JsBaseEngine::event();

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.

Parameters

string $title
Title for the link.
string|array $url optional null
Mixed either a string URL or a CakePHP URL array.
array $options optional array()
Options for both the HTML element and Js::request()

Returns

string
Completed link. If buffering is disabled a script tag will be returned as well.

Link

http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::link

set()source public

set( string|array $one , string|array $two null )

Pass variables into Javascript. Allows you to set variables that will be output when the buffer is fetched with JsHelper::getBuffer() or JsHelper::writeBuffer() The Javascript variable used to output set variables can be controlled with JsHelper::$setVariable

Parameters

string|array $one
Either an array of variables to set, or the name of the variable to set.
string|array $two optional null
If $one is a string, $two is the value for that key.

Link

http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::set

submit()source public

submit( string $caption null , array $options array() )

Uses the selected JS engine to create a submit input element that is enhanced with Javascript. Options can include both those for FormHelper::submit() and JsBaseEngine::request(), JsBaseEngine::event();

Forms submitting with this method, cannot send files. Files do not transfer over XmlHttpRequest and require an iframe or flash.

Options

  • url The url you wish the XHR request to submit to.
  • confirm A string to use for a confirm() message prior to submitting the request.
  • method The method you wish the form to send by, defaults to POST
  • buffer Whether or not you wish the script code to be buffered, defaults to true.
  • Also see options for JsHelper::request() and JsHelper::event()

Parameters

string $caption optional null
The display text of the submit button.
array $options optional array()
Array of options to use. See the options for the above mentioned methods.

Returns

string
Completed submit button.

Link

http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::submit

value()source public

value( mixed $val array() , boolean $quoteString null , string $key 'value' )

Overwrite inherited Helper::value() See JsBaseEngineHelper::value() for more information on this method.

Parameters

mixed $val optional array()
A PHP variable to be converted to JSON
boolean $quoteString optional null
If false, leaves string values unquoted
string $key optional 'value'
Key name.

Returns

string
a JavaScript-safe/JSON representation of $val

Link

http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::value

Overrides

Helper::value()

writeBuffer()source public

writeBuffer( array $options array() )

Writes all Javascript generated so far to a code block or caches them to a file and returns a linked script. If no scripts have been buffered this method will return null. If the request is an XHR(ajax) request onDomReady will be set to false. As the dom is already 'ready'.

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 (default true)

Parameters

array $options optional array()
options for the code block

Returns

mixed

Completed javascript tag if there are scripts, if there are no buffered scripts null will be returned.


Link

http://book.cakephp.org/2.0/en/core-libraries/helpers/js.html#JsHelper::writeBuffer

Methods inherited from Helper

__get()source public

__get( string $name )

Lazy loads helpers. Provides access to deprecated request properties as well.

Deprecated

3.0.0 Accessing request properties through this method is deprecated and will be removed in 3.0.

Parameters

string $name
Name of the property being accessed.

Returns

mixed
Helper or property found at $name

__set()source public

__set( string $name , mixed $value )

Provides backwards compatibility access for setting values to the request object.

Deprecated

3.0.0 This method will be removed in 3.0

Parameters

string $name
Name of the property being accessed.
mixed $value
Value to set.

_clean()source protected

_clean( )

Removes harmful content from output

_confirm()source protected

_confirm( string $message , string $okCode , string $cancelCode '' , array $options array() )

Returns a string to be used as onclick handler for confirm dialogs.

Parameters

string $message
Message to be displayed
string $okCode
Code to be executed after user chose 'OK'
string $cancelCode optional ''
Code to be executed after user chose 'Cancel', also executed when okCode doesn't return
array $options optional array()
Array of options

Returns

string
onclick JS code

_encodeUrl()source protected

_encodeUrl( string $url )

Encodes a URL for use in HTML attributes.

Parameters

string $url
The URL to encode.

Returns

string
The URL encoded for both URL & HTML contexts.

_formatAttribute()source protected

_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'

Deprecated

3.0.0 This method will be moved to HtmlHelper in 3.0

Parameters

string $key
The name of the attribute to create
string $value
The value of the attribute to create.
boolean $escape optional true
Define if the value must be escaped

Returns

string
The composed attribute.

_initInputField()source protected

_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.

Parameters

string $field
The field name to initialize.
array $options optional array()
Array of options to use while initializing an input field.

Returns

array
Array options for the form input.

_name()source protected

_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.

Parameters

array|string $options optional array()

If an array, should be an array of attributes that $key needs to be added to. If a string or null, will be used as the View entity.

string $field optional null
Field name.
string $key optional 'name'
The name of the attribute to be set, defaults to 'name'

Returns

mixed

If an array was given for $options, an array with $key set will be returned. If a string was supplied a string will be returned.


_parseAttributes()source protected

_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:

  • '1' (string)
  • 1 (integer)
  • true (boolean)
  • 'true' (string)

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.

Deprecated

3.0.0 This method will be moved to HtmlHelper in 3.0

Parameters

array $options
Array of options.
array $exclude optional null
Array of options to be excluded, the options here will not be part of the return.
string $insertBefore optional ' '
String to be inserted before options.
string $insertAfter optional null
String to be inserted after options.

Returns

string
Composed attributes.

_reset()source protected

_reset( )

Resets the vars used by Helper::clean() to null

_selectedArray()source protected

_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

Parameters

string|array $data
Data array or model name.
string $key optional 'id'
Field name.

Returns

array

addClass()source public

addClass( array $options array() , string $class null , string $key 'class' )

Adds the given class to the element options

Parameters

array $options optional array()
Array options/attributes to add a class to
string $class optional null
The class name being added.
string $key optional 'class'
the key to use for class.

Returns

array
Array of options with $key set.

afterLayout()source public

afterLayout( string $layoutFile )

After layout callback. afterLayout is called after the layout has rendered.

Overridden in subclasses.

Parameters

string $layoutFile
The layout file that was rendered.

afterRender()source public

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.

Parameters

string $viewFile
The view file that was rendered.

afterRenderFile()source public

afterRenderFile( string $viewFile , string $content )

After render file callback. Called after any view fragment is rendered.

Overridden in subclasses.

Parameters

string $viewFile
The file just be rendered.
string $content
The content that was rendered.

assetTimestamp()source public

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.

Parameters

string $path
The file path to timestamp, the path must be inside WWW_ROOT

Returns

string
Path with a timestamp added, or not.

assetUrl()source public

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

Parameters

string|array $path
Path string or URL array
array $options optional array()

Options array. Possible keys: 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 plugin

Returns

string
Generated URL

beforeLayout()source public

beforeLayout( string $layoutFile )

Before layout callback. beforeLayout is called before the layout is rendered.

Overridden in subclasses.

Parameters

string $layoutFile
The layout about to be rendered.

beforeRender()source public

beforeRender( string $viewFile )

Before render callback. beforeRender is called before the view file is rendered.

Overridden in subclasses.

Parameters

string $viewFile
The view file that is going to be rendered

beforeRenderFile()source public

beforeRenderFile( string $viewFile )

Before render file callback. Called before any view fragment is rendered.

Overridden in subclasses.

Parameters

string $viewFile
The file about to be rendered.

clean()source public

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.

Deprecated

3.0.0 This method will be removed in 3.0

Parameters

string|array $output
Either an array of strings to clean or a single string to clean.

Returns

string|array|null
Cleaned content for output

domId()source public

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.

Parameters

array|string $options optional null

Either an array of html attributes to add $id into, or a string with a view entity path to get a domId for.

string $id optional 'id'
The name of the 'id' attribute.

Returns

mixed

If $options was an array, an array will be returned with $id set. If a string was supplied, a string will be returned.


entity()source public

entity( )

Returns the entity reference of the current context as an array of identity parts

Returns

array
An array containing the identity elements of an entity

field()source public

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.

Returns

string

model()source public

model( )

Gets the currently-used model of the rendering context.

Returns

string

output()source public

output( string $str )

Returns a string generated by a helper method

This method can be overridden in subclasses to do generalized output post-processing

Deprecated

3.0.0 This method will be removed in future versions.

Parameters

string $str
String to be output.

Returns

string

setEntity()source public

setEntity( string $entity , boolean $setScope false )

Sets this helper's model and field properties to the dot-separated value-pair in $entity.

Parameters

string $entity
A field name, like "ModelName.fieldName" or "ModelName.ID.fieldName"
boolean $setScope optional false
Sets the view scope to the model specified in $tagValue

url()source public

url( string|array $url null , boolean $full false )

Finds URL for specified action.

Returns a URL pointing at the provided parameters.

Parameters

string|array $url optional null

Either a relative string url like /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.

boolean $full optional false
If true, the full base URL will be prepended to the result

Returns

string
Full translated URL with base path.

Link

http://book.cakephp.org/2.0/en/views/helpers.html

webroot()source public

webroot( string $file )

Checks if a file exists when theme is used, if no file is found default location is returned

Parameters

string $file
The file to create a webroot path to.

Returns

string
Web accessible path to file.

Methods inherited from Object

_mergeVars()source protected

_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.

Parameters

array $properties
The name of the properties to merge.
string $class
The class to merge the property with.
boolean $normalize optional true
Set to true to run the properties through Hash::normalize() before merging.

_set()source protected

_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.

Parameters

array $properties optional array()
An associative array containing properties and corresponding values.

_stop()source protected

_stop( integer|string $status 0 )

Stop execution of the current script. Wraps exit() making testing easier.

Parameters

integer|string $status optional 0
see http://php.net/exit for values

dispatchMethod()source public

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

Parameters

string $method
Name of the method to call
array $params optional array()
Parameter list to use when calling $method

Returns

mixed
Returns the result of the method call

log()source public

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.

Parameters

string $msg
Log message
integer $type optional LOG_ERR
Error type constant. Defined in app/Config/core.php.
null|string|array $scope optional null

The scope(s) a log message is being created in. See CakeLog::config() for more information on logging scopes.

Returns

boolean
Success of log write

requestAction()source public

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()

Passing POST and GET data

POST and GET data can be simulated in requestAction. Use $extra['url'] for GET data. The $extra['data'] parameter allows POST data simulation.

Parameters

string|array $url

String or array-based URL. Unlike other URL arrays in CakePHP, this URL will not automatically handle passed and named arguments in the $url parameter.

array $extra optional array()

if array includes the key "return" it sets the AutoRender to true. Can also be used to submit GET/POST data, and named/passed arguments.

Returns

mixed

Boolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.


toString()source public

toString( )

Object-to-string conversion. Each class can override this method as necessary.

Returns

string
The name of this class

Properties detail

$_bufferedScriptssource

protected array

Scripts that are queued for output

See

JsHelper::buffer()
array()

$_engineNamesource

protected string

Current Javascript Engine that is being used

$_jsVarssource

protected array

Variables to pass to Javascript.

See

JsHelper::set()
array()

$bufferScriptssource

public boolean

Whether or not you want scripts to be buffered or output.

true

$helperssource

public array

Helper dependencies

array('Html', 'Form')

$setVariablesource

public string

The javascript variable created by set() variables.

'app'

Magic properties detail

$Formsource

public FormHelper

$Htmlsource

public HtmlHelper

© 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.8/class-JsHelper.html