Form helper library.
Automatic generation of HTML FORMs from given data.
__call( string $method , array $params )
Missing method handler - implements various simple input types. Is used to create inputs of various types. e.g. $this->Form->text(); will create <input type="text" /> while $this->Form->range(); will create <input type="range" />
$this->Form->search('User.query', array('value' => 'test'));
Will make an input like:
<input type="search" id="UserQuery" name="data[User][query]" value="test" />
The first argument to an input type should always be the fieldname, in Model.field format. The second argument should always be an array of attributes for the input.
$method $params stringCakeExceptionHelper::__call() __construct( View $View , array $settings array() )
Copies the validationErrors variable from the View object into this instance
View $View $settings optional array() Helper::__construct() _csrfField( )
Return a CSRF input if the _Token is present. Used to secure forms in conjunction with SecurityComponent
string_dateTimeSelected( string $select , string $fieldName , array $attributes )
Selects values for dateTime selects.
$select $fieldName $attributes array_divOptions( array $options )
Generate div options for input
$options array_extractOption( string $name , array $options , mixed $default null )
Extracts a single option from an options array.
$name $options $default optional null mixed_generateOptions( string $name , array $options array() )
Generates option lists for common <select /> menus
$name $options optional array() array_getDateTimeValue( string|array $value , integer $timeFormat )
Parse the value for a datetime selected value
$value $timeFormat array_getFormat( array $options )
Generate format options
$options array_getInput( array $args )
Generates an input element
$args string_getLabel( string $fieldName , array $options )
Generate label for input
$fieldName $options boolean|string_getModel( string $model )
Guess the location for a model based on its name and tries to create a new instance or get an already created instance of the model
$model Model|null_initInputField( string $field , array $options array() )
Sets field defaults and adds field to form security input hash. Will also add a 'form-error' class if the field contains validation errors.
secure - boolean whether or not the field should be added to the security fields. Disabling the field using the disabled option, will also omit the field from being part of the hashed key.This method will convert a numerically indexed 'disabled' into an associative value. FormHelper's internals expect associative options.
$field $options optional array() arrayHelper::_initInputField() _inputLabel( string $fieldName , string|array $label , array $options )
Generate a label for an input() call.
$options can contain a hash of id overrides. These overrides will be used instead of the generated values if present.
$fieldName $label $options string_introspectModel( string $model , string $key , string $field null )
Inspects the model properties to extract information from them. Currently it can extract information from the the fields, the primary key and required fields
The $key parameter accepts the following list of values:
If the $field parameter is passed if will return the information for that sole field.
$this->_introspectModel('Post', 'fields', 'title'); will return the schema information for title column
$model $key $field optional null mixed_isRequiredField( CakeValidationSet $validationRules )
Returns if a field is required to be filled based on validation properties from the validating object.
CakeValidationSet $validationRules boolean_lastAction( string|array $url )
Sets the last created form action.
$url _magicOptions( array $options )
Magically set option type and corresponding options
$options array_maxLength( array $options )
Calculates maxlength option
$options array_name( array $options array() , string $field null , string $key 'name' )
Gets the input field name for the current tag
$options optional array() $field optional null $key optional 'name' arrayHelper::_name() _optionsOptions( array $options )
Generates list of options for multiple select
$options array_parseOptions( array $options )
Generates input options array
$options array_secure( boolean $lock , string|array $field null , mixed $value null )
Determine which fields of a form should be used for hash. Populates $this->fields
$lock $field optional null $value optional null _secureFieldName( array $options )
Get the field name for use with _secure().
Parses the name attribute to create a dot separated name value for use in secured field hash.
$options string|null_selectOptions( array $elements array() , array $parents array() , boolean $showParents null , array $attributes array() )
Returns an array of formatted OPTION/OPTGROUP elements
$elements optional array() $parents optional array() $showParents optional null $attributes optional array() arraybutton( string $title , array $options array() )
Creates a <button> tag. The type attribute defaults to type="submit" You can change it to a different value by using $options['type'].
escape - HTML entity encode the $title of the button. Defaults to false.$title $options optional array() stringcheckbox( string $fieldName , array $options array() )
Creates a checkbox input widget.
value - the value of the checkboxchecked - boolean indicate that this checkbox is checked.hiddenField - boolean to indicate if you want the results of checkbox() to include a hidden input with a value of ''.disabled - create a disabled input.default - Set the default value for the checkbox. This allows you to start checkboxes as checked, without having to check the POST data. A matching POST data value, will overwrite the default value.$fieldName $options optional array() stringcreate( mixed $model null , array $options array() )
Returns an HTML FORM element.
type Form method defaults to POSTaction The controller action the form submits to, (optional).url The URL the form submits to. Can be a string or a URL array. If you use 'url' you should leave 'action' undefined.default Allows for the creation of Ajax forms. Set this to false to prevent the default event handler. Will create an onsubmit attribute if it doesn't not exist. If it does, default action suppression will be appended.onsubmit Used in conjunction with 'default' to create ajax forms.inputDefaults set the default $options for FormHelper::input(). Any options that would be set when using FormHelper::input() can be set here. Options set with inputDefaults can be overridden when calling input()encoding Set the accept-charset encoding for the form. Defaults to Configure::read('App.encoding')
$model optional null ContactManager.Contact. If an array is passed and $options argument is empty, the array will be used as options. If false no model is used.$options optional array() stringdateTime( string $fieldName , string $dateFormat 'DMY' , string $timeFormat '12' , array $attributes array() )
Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
monthNames If false, 2 digit numbers will be used instead of text. If an array, the given array will be used.minYear The lowest year to use in the year selectmaxYear The maximum year to use in the year selectinterval The interval for the minutes select. Defaults to 1separator The contents of the string between select elements. Defaults to '-'empty - If true, the empty select option is shown. If a string, that string is displayed as the empty element.round - Set to up or down if you want to force rounding in either direction. Defaults to null.value | default The default value to be used by the input. A value in $this->data matching the field name will override this value. If no default is provided time() will be used.$fieldName $dateFormat optional 'DMY' $timeFormat optional '12' $attributes optional array() stringday( string $fieldName null , array $attributes array() )
Returns a SELECT element for days.
empty - If true, the empty select option is shown. If a string, that string is displayed as the empty element.value The selected value of the input.$fieldName optional null $attributes optional array() stringdomIdSuffix( string $value , string $type 'html4' )
Generates a valid DOM ID suffix from a string. Also avoids collisions when multiple values are coverted to the same suffix by appending a numeric value.
For pre-HTML5 IDs only characters like a-z 0-9 - _ are valid. HTML5 doesn't have that limitation, but to avoid layout issues it still filters out some sensitive chars.
$value $type optional 'html4' stringend( string|array $options null , array $secureAttributes array() )
Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden input fields where appropriate.
If $options is set a form submit button will be created. Options can be either a string or an array.
array usage: array('label' => 'save'); value="save" array('label' => 'save', 'name' => 'Whatever'); value="save" name="Whatever" array('name' => 'Whatever'); value="Submit" name="Whatever" array('label' => 'save', 'name' => 'Whatever', 'div' => 'good') <div class="good"> value="save" name="Whatever" array('label' => 'save', 'name' => 'Whatever', 'div' => array('class' => 'good')); <div class="good"> value="save" name="Whatever"
If $secureAttributes is set, these html attributes will be merged into the hidden input tags generated for the Security Component. This is especially useful to set HTML5 attributes like 'form'
$options optional null $secureAttributes optional array() stringerror( string $field , string|array $text null , array $options array() )
Returns a formatted error message for given FORM field, NULL if no errors.
escape boolean - 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$field $text optional null attributes key it will be used as options for error container$options optional array() string|nullfile( string $fieldName , array $options array() )
Creates file input widget.
$fieldName $options optional array() stringhidden( string $fieldName , array $options array() )
Creates a hidden input field.
$fieldName $options optional array() stringhour( string $fieldName , boolean $format24Hours false , array $attributes array() )
Returns a SELECT element for hours.
empty - If true, the empty select option is shown. If a string, that string is displayed as the empty element.value The selected value of the input.$fieldName $format24Hours optional false $attributes optional array() stringinput( string $fieldName , array $options array() )
Generates a form input element complete with label and wrapper div
See each field type method for more information. Any options that are part of $attributes or $options for the different type methods can be included in $options for input().i Additionally, any unknown keys that are not in the list below, or part of the selected type's options will be treated as a regular html attribute for the generated input.
type - Force the type of widget you want. e.g. type => 'select'
label - Either a string label, or an array of options for the label. See FormHelper::label().div - Either false to disable the div, or an array of options for the div.See HtmlHelper::div() for more options.
options - For widgets that take options e.g. radio, select.error - Control the error message that is produced. Set to false to disable any kind of error reporting (field error and error messages).errorMessage - Boolean to control rendering error messages (field error will still occur).empty - String or boolean to enable empty select box options.before - Content to place before the label + input.after - Content to place after the label + input.between - Content to place between the label + input.format - Format template for element order. Any element that is not in the array, will not be in the output.$fieldName $options optional array() stringinputDefaults( array $defaults null , boolean $merge false )
Set/Get inputDefaults for form elements
$defaults optional null $merge optional false arrayinputs( array $fields null , array $blacklist null , array $options array() )
Generate a set of inputs for $fields. If $fields is null the fields of current model will be used.
You can customize individual inputs through $fields.
$this->Form->inputs(array( 'name' => array('label' => 'custom label') ));
In addition to controller fields output, $fields can be used to control legend and fieldset rendering. $this->Form->inputs('My legend'); Would generate an input set with a custom legend. Passing fieldset and legend key in $fields array has been deprecated since 2.3, for more fine grained control use the fieldset and legend keys in $options param.
$fields optional null $blacklist optional null $options optional array() 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.stringisFieldError( string $field )
Returns true if there is an error for the given field, otherwise false
$field booleanlabel( string $fieldName null , string $text null , array|string $options array() )
Returns a formatted LABEL element for HTML FORMs. Will automatically generate a for attribute if one is not provided.
for - Set the for attribute, if its not defined the for attribute will be generated from the $fieldName parameter using FormHelper::domId().Examples:
The text and for attribute are generated off of the fieldname
echo $this->Form->label('Post.published'); <label for="PostPublished">Published</label>
Custom text:
echo $this->Form->label('Post.published', 'Publish'); <label for="PostPublished">Publish</label>
Custom class name:
echo $this->Form->label('Post.published', 'Publish', 'required'); <label for="PostPublished" class="required">Publish</label>
Custom attributes:
echo $this->Form->label('Post.published', 'Publish', array( 'for' => 'post-publish' )); <label for="post-publish">Publish</label>
Warning Unlike most FormHelper methods, this method does not automatically escape the $text parameter. You must escape the $text parameter yourself if you are using user supplied data.
$fieldName optional null $text optional null $options optional array() stringmeridian( string $fieldName , array $attributes array() )
Returns a SELECT element for AM or PM.
empty - If true, the empty select option is shown. If a string, that string is displayed as the empty element.value The selected value of the input.$fieldName $attributes optional array() stringminute( string $fieldName , array $attributes array() )
Returns a SELECT element for minutes.
empty - If true, the empty select option is shown. If a string, that string is displayed as the empty element.value The selected value of the input.$fieldName $attributes optional array() stringmonth( string $fieldName , array $attributes array() )
Returns a SELECT element for months.
monthNames - If false, 2 digit numbers will be used instead of text. If an array, the given array will be used.empty - If true, the empty select option is shown. If a string, that string is displayed as the empty element.value The selected value of the input.$fieldName $attributes optional array() stringpostButton( string $title , string|array $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 an already opened form. Instead use FormHelper::submit() or FormHelper::button() to create buttons inside opened forms.
data - Array with key/value to pass in input hidden$title $url $options optional array() stringpostLink( string $title , string|array $url null , array $options array() , boolean|string $confirmMessage false )
Creates an HTML link, but access the URL using the method you specify (defaults to 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 is being set to a view block that can be rendered outside of the main form.
If all you are looking for is a button to submit your form, then you should use FormHelper::submit() instead.
data - Array with key/value to pass in input hiddenmethod - Request method to use. Set to 'delete' to simulate HTTP/1.1 DELETE request. Defaults to 'post'.confirm - Can be used instead of $confirmMessage.inline - Whether or not the associated form tag should be output inline. Set to false to have the form tag appended to the 'postLink' view block. Defaults to true.block - Choose a custom block to append the form tag to. Using this option will override the inline option.onclick will be replaced.$title $url optional null $options optional array() $confirmMessage optional false confirm key in $options instead.string<a /> element.radio( string $fieldName , array $options array() , array $attributes array() )
Creates a set of radio widgets. Will create a legend and fieldset by default. Use $options to control this
You can also customize each radio input element using an array of arrays:
$options = array( array('name' => 'United states', 'value' => 'US', 'title' => 'My title'), array('name' => 'Germany', 'value' => 'DE', 'class' => 'de-de', 'title' => 'Another title'), );
separator - define the string in between the radio buttonsbetween - the string between legend and input set or array of strings to insert strings between each input blocklegend - control whether or not the widget set has a fieldset & legendvalue - indicate a value that is should be checkedlabel - boolean to indicate whether or not labels for widgets show be displayedhiddenField - boolean to indicate if you want the results of radio() to include a hidden input with a value of ''. This is useful for creating radio sets that non-continuousdisabled - Set to true or disabled to disable all the radio buttons.empty - Set to true to create an input with the value '' as the first option. When true the radio label will be 'empty'. Set this option to a string to control the label value.$fieldName $options optional array() $attributes optional array() stringsecure( array|null $fields array() , array $secureAttributes array() )
Generates a hidden field with a security hash based on the fields used in the form.
If $secureAttributes is set, these html attributes will be merged into the hidden input tags generated for the Security Component. This is especially useful to set HTML5 attributes like 'form'.
$fields optional array() $secureAttributes optional array() string|nullselect( string $fieldName , array $options array() , array $attributes array() )
Returns a formatted SELECT element.
showParents - If included in the array and set to true, an additional option element will be added for the parent of each option group. You can set an option with the same name and it's key will be used for the value of the option.multiple - show a multiple select box. If set to 'checkbox' multiple checkboxes will be created instead.empty - If true, the empty select option is shown. If a string, that string is displayed as the empty element.escape - If true contents of options will be HTML entity encoded. Defaults to true.value The selected value of the input.class - When using multiple = checkbox the class name to apply to the divs. Defaults to 'checkbox'.disabled - Control the disabled attribute. When creating a select box, set to true to disable the select box. When creating checkboxes, true will disable all checkboxes. You can also set disabled to a list of values you want to disable when creating checkboxes.A simple array will create normal options:
$options = array(1 => 'one', 2 => 'two); $this->Form->select('Model.field', $options));
While a nested options array will create optgroups with options inside them.
$options = array( 1 => 'bill', 'fred' => array( 2 => 'fred', 3 => 'fred jr.' ) ); $this->Form->select('Model.field', $options);
In the above 2 => 'fred' will not generate an option element. You should enable the showParents attribute to show the fred option.
If you have multiple options that need to have the same value attribute, you can use an array of arrays to express this:
$options = array( array('name' => 'United states', 'value' => 'USA'), array('name' => 'USA', 'value' => 'USA'), );
$fieldName $options optional array() $attributes optional array() stringsubmit( string $caption null , array $options array() )
Creates a submit button element. This method will generate <input /> elements that can be used to submit, and reset forms by using $options. image submits can be created by supplying an image path for $caption.
div - Include a wrapping div? Defaults to true. Accepts sub options similar to FormHelper::input().before - Content to include before the input.after - Content to include after the input.type - Set to 'reset' for reset inputs. Defaults to 'submit'div - Include a wrapping div? Defaults to true. Accepts sub options similar to FormHelper::input().$caption optional null $options optional array() stringtagIsInvalid( )
Returns false if given form field described by the current entity has no errors. Otherwise it returns the validation message
mixedtextarea( string $fieldName , array $options array() )
Creates a textarea widget.
escape - Whether or not the contents of the textarea should be escaped. Defaults to true.$fieldName $options optional array() stringunlockField( string $name null )
Add to or get the list of fields that are currently unlocked. Unlocked fields are not included in the field hash used by SecurityComponent unlocking a field once its been added to the list of secured fields will remove it from the list of fields.
$name optional null mixedyear( string $fieldName , integer $minYear null , integer $maxYear null , array $attributes array() )
Returns a SELECT element for years
empty - If true, the empty select option is shown. If a string, that string is displayed as the empty element.orderYear - Ordering of year values in select options. Possible values 'asc', 'desc'. Default 'desc'value The selected value of the input.$fieldName $minYear optional null $maxYear optional null $attributes optional array() string__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_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' arrayaddClass( 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' arrayafterLayout( 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 stringassetUrl( 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 pluginstringbeforeLayout( 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|nulldomId( 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' mixedentity( )
Returns the entity reference of the current context as an array of identity parts
arrayfield( )
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.
stringmodel( )
Gets the currently-used model of the rendering context.
stringoutput( string $str )
Returns a string generated by a helper method
This method can be overridden in subclasses to do generalized output post-processing
$str stringsetEntity( 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 stringvalue( 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' mixedwebroot( 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() mixedlog( 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 booleanrequestAction( 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() mixedtoString( )
Object-to-string conversion. Each class can override this method as necessary.
stringstring | SECURE_SKIP Constant used internally to skip the securing process, and neither add the field to the hash or to the unlocked fields. | 'skip' |
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() 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.7/class-FormHelper.html