Class JavascriptHelper
Javascript Helper class for easy use of JavaScript.
JavascriptHelper encloses all methods needed while working with JavaScript.
-
Object
-
Overloadable
-
Helper
-
AppHelper
-
JavascriptHelper
Properties summary
-
string
-
array
Holds options passed to codeBlock(), saved for when block is dumped to output
-
boolean
Indicates whether all generated JavaScript should be cached for later output
-
boolean
Indicates whether generated events should be cached for later output (can be written at the
end of the page, in the
, or to an external file).
boolean
Indicates whether cached events should be written to an external file
array
Caches events written by event() for output at the end of page execution
array
Contains event rules attached with CSS selectors. Used with the event:Selectors JavaScript
library.
boolean
If true, automatically writes events to the end of a script or to an external JavaScript file
at the end of page execution
boolean
Indicates whether blocks should be written 'safely,' i.e. wrapped in CDATA blocks
array
HTML tags used by this helper.
boolean
Determines whether native JSON extension is used for encoding. Set by object constructor.
Method Detail
__construct( $options = array() )
Constructor. Checks for presence of native PHP JSON extension to use for object encoding
Overrides
_utf8ToHex( $string )
Encode a string into JSON. Converts and escapes necessary characters.
afterRender( )
AfterRender callback. Writes any cached events to the view, or to a temp file.
Returns
null
Overrides
blockEnd( )
Ends a block of cached JavaScript code
Returns
mixed
cacheEvents( boolean $file = false , boolean $all = false )
Cache JavaScript events created with event()
Parameters
-
boolean
$file
optional
false
- If true, code will be written to a file
-
boolean
$all
optional
false
- If true, all code written with JavascriptHelper will be sent to a file
Returns
null
codeBlock( string $script = null , array $options = array() )
Returns a JavaScript script tag.
Options:
- allowCache: boolean, designates whether this block is cacheable using the
current cache settings.
- safe: boolean, whether this block should be wrapped in CDATA tags. Defaults
to helper's object configuration.
- inline: whether the block should be printed inline, or written
to cached for later output (i.e. $scripts_for_layout).
Parameters
-
string
$script
optional
null
- The JavaScript to be wrapped in SCRIPT tags.
-
array
$options
optional
array()
- Set of options:
Returns
string
The full SCRIPT element, with the JavaScript inside it, or null,
if 'inline' is set to false.
escapeScript( string $script )
Escape carriage returns and single and double quotes for JavaScript segments.
Parameters
-
string
$script
- string that might have javascript elements
Returns
string
escaped string
escapeString( string $string )
Escape a string to be JavaScript friendly.
List of escaped ellements:
+ "\r\n" => '\n'
+ "\r" => '\n'
+ "\n" => '\n'
+ '"' => '\"'
+ "'" => "\'"
Parameters
-
string
$string
- $script String that needs to get escaped.
Returns
string
Escaped string.
event( string $object , string $event , string $observer = null , array $options = array() )
Attach an event to an element. Used with the Prototype library.
Parameters
-
string
$object
- Object to be observed
-
string
$event
- event to observe
-
string
$observer
optional
null
- function to call
-
array
$options
optional
array()
- Set options: useCapture, allowCache, safe
Returns
boolean
true on success
getCache( boolean $clear = true )
Gets (and clears) the current JavaScript event cache
Parameters
-
boolean
$clear
optional
true
Returns
string
includeScript( string $script = "" , array $options = array() )
Includes the Prototype Javascript library (and anything else) inside a single script tag.
Note: The recommended approach is to copy the contents of
javascripts into your application's
public/javascripts/ directory, and use @see javascriptIncludeTag() to
create remote script links.
Parameters
-
string
$script
optional
""
- Script file to include
-
array
$options
optional
array()
- Set options for codeBlock
Returns
string
script with all javascript in/javascripts folder
link( mixed $url , boolean $inline = true )
Returns a JavaScript include tag (SCRIPT element). 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.
Parameters
-
mixed
$url
- String URL to JavaScript file, or an array of URLs.
-
boolean
$inline
optional
true
If true, the tag will be printed inline,
otherwise it will be printed in the
, using $scripts_for_layout
Returns
string
See
JS_URL
object( array $data = array() , array $options = array() )
Generates a JavaScript object in JavaScript Object Notation (JSON)
from an array
Options
- block - Wraps the return value in a script tag if true. Default is false
- prefix - Prepends the string to the returned data. Default is ''
- postfix - Appends the string to the returned data. Default is ''
- stringKeys - A list of array keys to be treated as a string.
- quoteKeys - If false treats $stringKeys as a list of keys not to be quoted. Default is true.
- q - The type of quote to use. Default is '"'. This option only affects the keys, not the values.
Parameters
-
array
$data
optional
array()
- Data to be converted
-
array
$options
optional
array()
- Set of options: block, prefix, postfix, stringKeys, quoteKeys, q
Returns
string
A JSON code block
value( mixed $val , boolean $quoteStrings = true )
Converts a PHP-native variable of any type to a JSON-equivalent representation
Parameters
-
mixed
$val
- A PHP variable to be converted to JSON
-
boolean
$quoteStrings
optional
true
- If false, leaves string values unquoted
Returns
string
a JavaScript-safe/JSON representation of $val
Overrides
writeEvents( boolean $inline = true , array $options = array() )
Write cached JavaScript events
Parameters
-
boolean
$inline
optional
true
If true, returns JavaScript event code. Otherwise it is added to the
output of $scripts_for_layout in the layout.
-
array
$options
optional
array()
- Set options for codeBlock
Returns
string
Methods inherited from Helper
__clean( )
Removes harmful content from output
__formatAttribute( string $key , string $value , $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'
Parameters
-
string
$key
- The name of the attribute to create
-
string
$value
- The value of the attribute to create.
-
$escape
optional
true
Returns
string
The composed attribute.
__reset( )
Resets the vars used by Helper::clean() to null
__selectedArray( mixed $data , string $key = 'id' )
Transforms a recordset from a hasAndBelongsToMany association to a list of selected
options for a multiple select element
Parameters
-
mixed
$data
-
string
$key
optional
'id'
Returns
array
_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. Will also
add a 'form-error' class if the field contains validation errors.
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( mixed $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
-
mixed
$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
-
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( 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:
- 'compact'
- 'checked'
- 'declare'
- 'readonly'
- 'disabled'
- 'selected'
- 'defer'
- 'ismap'
- 'nohref'
- 'noshade'
- 'nowrap'
- 'multiple'
- 'noresize'
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.
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.
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 classname being added.
-
string
$key
optional
'class'
- the key to use for class.
Returns
array
Array of options with $key set.
afterLayout( )
After layout callback. afterLayout is called after the layout has rendered.
Overridden in subclasses.
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.
beforeLayout( )
Before layout callback. beforeLayout is called before the layout is rendered.
Overridden in subclasses.
beforeRender( )
Before render callback. beforeRender is called before the view file is rendered.
Overridden in subclasses.
call__( $method , $params )
clean( mixed $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 possiblities. Escaping
content is the best way to prevent all possible attacks.
Parameters
-
mixed
$output
- Either an array of strings to clean or a single string to clean.
Returns
cleaned
content for output
domId( mixed $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
-
mixed
$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.
field( )
Gets the currently-used model field of the rendering context.
Returns
string
loadConfig( $name = 'tags' )
Parses tag templates into $this->tags.
Parameters
-
$name
optional
'tags'
- name inside app/config to load.
Returns
array
merged tags from config/$name.php
model( )
Gets the currently-used model of the rendering context.
Returns
string
modelID( )
Gets the ID of the currently-used model of the rendering context.
Returns
mixed
output()
public
deprecated
¶
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
This method will be removed in future versions.
Parameters
-
string
$str
- String to be output.
Returns
string
setEntity( mixed $entity , boolean $setScope = false )
Sets this helper's model and field properties to the dot-separated value-pair in $entity.
Parameters
-
mixed
$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
tagIsInvalid( string $model = null , string $field = null , integer $modelID = null )
Returns null if given FORM field has no errors. Otherwise it returns the constant set in
the array Model->validationErrors.
Parameters
-
string
$model
optional
null
- Model name as a string
-
string
$field
optional
null
- Fieldname as a string
-
integer
$modelID
optional
null
- Unique index identifying this record within the form
Returns
mixed
Null if no errors, string with error otherwhise.
url( mixed $url = null , boolean $full = false )
Finds URL for specified action.
Returns a URL pointing at the provided parameters.
Parameters
-
mixed
$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
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
Object( )
A hack to support __construct() on PHP 4
Hint: descendant classes have no PHP4 class_name() constructors,
so this constructor gets called first and calls the top-layer __construct()
which (if present) should call parent::__construct()
Returns
__openPersistent( string $name , string $type = null )
Open the persistent class file for reading
Used by Object::_persist()
Parameters
-
string
$name
- Name of persisted class
-
string
$type
optional
null
- Type of persistance (e.g: registry)
_persist( string $name , string $return , $object , $type = null )
Checks for a persistent class file, if found file is opened and true returned
If file is not found a file is created and false returned
If used in other locations of the model you should choose a unique name for the persistent file
There are many uses for this method, see manual for examples
Parameters
-
string
$name
- name of the class to persist
-
string
$return
- $object the object to persist
-
$object
-
$type
optional
null
Returns
boolean
Success
_savePersistent( string $name , object $object )
You should choose a unique name for the persistent file
There are many uses for this method, see manual for examples
Parameters
-
string
$name
- name used for object to cache
-
object
$object
- the object to persist
Returns
boolean
true on save, throws error if file can not be created
_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( $status = 0 )
Stop execution of the current script. Wraps exit() making
testing easier.
Parameters
-
$status
optional
0
- http://php.net/exit for values
cakeError( string $method , array $messages = array() )
Used to report user friendly errors.
If there is a file app/error.php or app/app_error.php this file will be loaded
error.php is the AppError class it should extend ErrorHandler class.
Parameters
-
string
$method
- Method to be called in the error class (AppError or ErrorHandler classes)
-
array
$messages
optional
array()
- Message that is to be displayed by the error class
Returns
error
message
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( string $msg , integer $type = LOG_ERROR )
Convience 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_ERROR
- Error type constant. Defined in app/config/core.php.
Returns
boolean
Success of log write
requestAction( mixed $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.
Parameters
-
mixed
$url
- String or array-based url.
-
array
$extra
optional
array()
- if array includes the key "return" it sets the AutoRender to true.
Returns
mixed
Boolean true or false on success/failure, or contents
of rendered action if 'return' is set in $extra.
toString( )
Object-to-string conversion.
Each class can override this method as necessary.
Returns
string
The name of this class