Class FormHelper
Form helper library.
Automatic generation of HTML FORMs from given data.
- AppHelper
-
FormHelper
Link: http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html
Copyright: Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
License: MIT License
Location: Cake/View/Helper/FormHelper.php
Constants summary
-
string'skip'
Properties summary
-
$_domIdSuffixesprotectedHolds already used DOM ID suffixes to avoid collisions with multiple form field elements.array -
$_inputDefaultsprotectedPersistent default options used by input(). Set by FormHelper::create().array -
$_lastActionprotectedstringThe action attribute value of the last created form. Used to make form/request specific hashes for SecurityComponent.
-
$_modelsprotectedarrayHolds the model references already loaded by this helper product of trying to inspect them out of field names
-
$_optionsprotectedOptions used by DateTime fieldsarray -
$_unlockedFieldsprotectedarrayAn array of field names that have been excluded from the Token hash used by SecurityComponent's validatePost method
-
$defaultModelpublicThe default model being used for the current form.string -
$fieldspublicList of fields created, used with secure forms.array -
$helperspublicOther helpers used by FormHelperarray -
$requestTypepublicDefines the type of form being created. Set by FormHelper::create().string -
$validationErrorspublicarrayHolds all the validation errors for models loaded and inspected it can also be set manually to be able to display custom error messages in the any of the input fields generated by this helper
Magic properties summary
-
$Htmlpublic
Method Summary
- __call() public
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" /> - __construct() publicCopies the validationErrors variable from the View object into this instance
- _csrfField() protected
Return a CSRF input if the _Token is present. Used to secure forms in conjunction with SecurityComponent
- _dateTimeSelected() protectedSelects values for dateTime selects.
- _divOptions() protectedGenerate div options for input
- _extractOption() protectedExtracts a single option from an options array.
- _generateOptions() protectedGenerates option lists for common menus
- _getDateTimeValue() protectedParse the value for a datetime selected value
- _getFormat() protectedGenerate format options
- _getInput() protectedGenerates an input element
- _getLabel() protectedGenerate label for input
- _getModel() protected
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
- _initInputField() protected
Sets field defaults and adds field to form security input hash. Will also add a 'form-error' class if the field contains validation errors.
- _inputLabel() protectedGenerate a label for an input() call.
- _introspectModel() protected
Inspects the model properties to extract information from them. Currently it can extract information from the the fields, the primary key and required fields
- _isRequiredField() protectedReturns if a field is required to be filled based on validation properties from the validating object.
- _lastAction() protectedSets the last created form action.
- _magicOptions() protectedMagically set option type and corresponding options
- _maxLength() protectedCalculates maxlength option
- _name() protectedGets the input field name for the current tag
- _optionsOptions() protectedGenerates list of options for multiple select
- _parseOptions() protectedGenerates input options array
- _secure() protected
Determine which fields of a form should be used for hash. Populates $this->fields
- _secureFieldName() protectedGet the field name for use with _secure().
- _selectOptions() protectedReturns an array of formatted OPTION/OPTGROUP elements
- button() public
Creates a
<button>tag. The type attribute defaults totype="submit"You can change it to a different value by using$options['type']. - checkbox() publicCreates a checkbox input widget.
- create() publicReturns an HTML FORM element.
- dateTime() publicReturns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
- day() publicReturns a SELECT element for days.
- domIdSuffix() public
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.
- end() public
Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden input fields where appropriate.
- error() publicReturns a formatted error message for given FORM field, NULL if no errors.
- file() publicCreates file input widget.
- hidden() publicCreates a hidden input field.
- hour() publicReturns a SELECT element for hours.
- input() publicGenerates a form input element complete with label and wrapper div
- inputDefaults() publicSet/Get inputDefaults for form elements
- inputs() public
Generate a set of inputs for
$fields. If $fields is null the fields of current model will be used. - isFieldError() publicReturns true if there is an error for the given field, otherwise false
- label() public
Returns a formatted LABEL element for HTML FORMs. Will automatically generate a
forattribute if one is not provided. - meridian() publicReturns a SELECT element for AM or PM.
- minute() publicReturns a SELECT element for minutes.
- month() publicReturns a SELECT element for months.
- postButton() publicCreate a
<button>tag with a surrounding<form>that submits via POST. - postLink() public
Creates an HTML link, but access the URL using the method you specify (defaults to POST). Requires javascript to be enabled in browser.
- radio() public
Creates a set of radio widgets. Will create a legend and fieldset by default. Use $options to control this
- secure() public
Generates a hidden field with a security hash based on the fields used in the form.
- select() publicReturns a formatted SELECT element.
- submit() public
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. - tagIsInvalid() public
Returns false if given form field described by the current entity has no errors. Otherwise it returns the validation message
- textarea() publicCreates a textarea widget.
- unlockField() public
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.
- year() publicReturns a SELECT element for years
Method Detail
__call()source public
__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" />
Usage
$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.
Parameters
- string
$method - Method name / input type to make.
- array
$params - Parameters for the method call
Returns
stringFormatted input method.
Throws
CakeExceptionWhen there are no params for the method call.
__construct()source public
__construct( View $View , array $settings array() )
Copies the validationErrors variable from the View object into this instance
Parameters
-
View$View - The View this helper is being attached to.
- array
$settingsoptional array() - Configuration settings for the helper.
_csrfField()source protected
_csrfField( )
Return a CSRF input if the _Token is present. Used to secure forms in conjunction with SecurityComponent
Returns
string_dateTimeSelected()source protected
_dateTimeSelected( string $select , string $fieldName , array $attributes )
Selects values for dateTime selects.
Parameters
- string
$select - Name of element field. ex. 'day'
- string
$fieldName - Name of fieldName being generated ex. Model.created
- array
$attributes - Array of attributes, must contain 'empty' key.
Returns
arrayAttributes array with currently selected value.
_divOptions()source protected
_divOptions( array $options )
Generate div options for input
Parameters
- array
$options - Options list.
Returns
array_extractOption()source protected
_extractOption( string $name , array $options , mixed $default null )
Extracts a single option from an options array.
Parameters
- string
$name - The name of the option to pull out.
- array
$options - The array of options you want to extract.
- mixed
$defaultoptional null - The default option value
Returns
mixedthe contents of the option or default
_generateOptions()source protected
_generateOptions( string $name , array $options array() )
Generates option lists for common menus
Parameters
- string
$name - List type name.
- array
$optionsoptional array() - Options list.
Returns
array_getDateTimeValue()source protected
_getDateTimeValue( string|array $value , integer $timeFormat )
Parse the value for a datetime selected value
Parameters
- string|array
$value - The selected value.
- integer
$timeFormat - The time format
Returns
arrayArray of selected value.
_getFormat()source protected
_getFormat( array $options )
Generate format options
Parameters
- array
$options - Options list.
Returns
array_getInput()source protected
_getInput( array $args )
Generates an input element
Parameters
- array
$args - The options for the input element
Returns
stringThe generated input element
_getLabel()source protected
_getLabel( string $fieldName , array $options )
Generate label for input
Parameters
- string
$fieldName - Field name.
- array
$options - Options list.
Returns
boolean|stringfalse or Generated label element
_getModel()source protected
_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
Parameters
- string
$model - Model name.
Returns
Model|nullModel instance
_initInputField()source protected
_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.
Options
-
secure- boolean whether or not the field should be added to the security fields. Disabling the field using thedisabledoption, 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.
Parameters
- string
$field - Name of the field to initialize options for.
- array
$optionsoptional array() - Array of options to append options into.
Returns
arrayArray of options for the input.
_inputLabel()source protected
_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.
Parameters
- string
$fieldName - Field name.
- string|array
$label - Label text or array with text and options.
- array
$options Options for the label element. 'NONE' option is deprecated and will be removed in 3.0
Returns
stringGenerated label element
_introspectModel()source protected
_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:
- key: Returns the name of the primary key for the model
- fields: Returns the model schema
- validates: returns the list of fields that are required
- errors: returns the list of validation errors
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
Parameters
- string
$model - name of the model to extract information from
- string
$key - name of the special information key to obtain (key, fields, validates, errors)
- string
$fieldoptional null - name of the model field to get information from
Returns
mixedinformation extracted for the special key and field in a model
_isRequiredField()source protected
_isRequiredField( CakeValidationSet $validationRules )
Returns if a field is required to be filled based on validation properties from the validating object.
Parameters
-
CakeValidationSet$validationRules - Validation rules set.
Returns
booleantrue if field is required to be filled, false otherwise
_lastAction()source protected
_lastAction( string|array $url )
Sets the last created form action.
Parameters
- string|array
$url - URL.
_magicOptions()source protected
_magicOptions( array $options )
Magically set option type and corresponding options
Parameters
- array
$options - Options list.
Returns
array_maxLength()source protected
_maxLength( array $options )
Calculates maxlength option
Parameters
- array
$options - Options list.
Returns
array_name()source protected
_name( array $options array() , string $field null , string $key 'name' )
Gets the input field name for the current tag
Parameters
- array
$optionsoptional array() - Options list.
- string
$fieldoptional null - Field name.
- string
$keyoptional 'name' - Key name.
Returns
array_optionsOptions()source protected
_optionsOptions( array $options )
Generates list of options for multiple select
Parameters
- array
$options - Options list.
Returns
array_parseOptions()source protected
_parseOptions( array $options )
Generates input options array
Parameters
- array
$options - Options list.
Returns
arrayOptions
_secure()source protected
_secure( boolean $lock , string|array $field null , mixed $value null )
Determine which fields of a form should be used for hash. Populates $this->fields
Parameters
- boolean
$lock Whether this field should be part of the validation or excluded as part of the unlockedFields.
- string|array
$fieldoptional null - Reference to field to be secured. Should be dot separated to indicate nesting.
- mixed
$valueoptional null - Field value, if value should not be tampered with.
_secureFieldName()source protected
_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.
Parameters
- array
$options - An array of options possibly containing a name key.
Returns
string|null_selectOptions()source protected
_selectOptions( array $elements array() , array $parents array() , boolean $showParents null , array $attributes array() )
Returns an array of formatted OPTION/OPTGROUP elements
Parameters
- array
$elementsoptional array() - Elements to format.
- array
$parentsoptional array() - Parents for OPTGROUP.
- boolean
$showParentsoptional null - Whether to show parents.
- array
$attributesoptional array() - HTML attributes.
Returns
arraybutton()source public
button( 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'].
Options:
-
escape- HTML entity encode the $title of the button. Defaults to false.
Parameters
- string
$title - The button's caption. Not automatically HTML encoded
- array
$optionsoptional array() - Array of options and HTML attributes.
Returns
stringA HTML button tag.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::buttoncheckbox()source public
checkbox( string $fieldName , array $options array() )
Creates a checkbox input widget.
Options:
-
value- the value of the checkbox -
checked- 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.
Parameters
- string
$fieldName - Name of a field, like this "Modelname.fieldname"
- array
$optionsoptional array() - Array of HTML attributes.
Returns
stringAn HTML text input element.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputscreate()source public
create( mixed|null $model null , array $options array() )
Returns an HTML FORM element.
Options:
-
typeForm method defaults to POST -
actionThe controller action the form submits to, (optional). Deprecated since 2.8, useurl. -
urlThe URL the form submits to. Can be a string or a URL array. If you use 'url' you should leave 'action' undefined. -
defaultAllows 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. -
onsubmitUsed in conjunction with 'default' to create AJAX forms. -
inputDefaultsset the default $options for FormHelper::input(). Any options that would be set when using FormHelper::input() can be set here. Options set withinputDefaultscan be overridden when calling input() -
encodingSet the accept-charset encoding for the form. Defaults toConfigure::read('App.encoding')
Parameters
- mixed|null
$modeloptional null The model name for which the form is being defined. Should include the plugin name for plugin models. e.g.
ContactManager.Contact. If an array is passed and $options argument is empty, the array will be used as options. Iffalseno model is used.- array
$optionsoptional array() - An array of html attributes and options.
Returns
stringA formatted opening FORM tag.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-createdateTime()source public
dateTime( 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.
Attributes:
-
monthNamesIf false, 2 digit numbers will be used instead of text. If an array, the given array will be used. -
minYearThe lowest year to use in the year select -
maxYearThe maximum year to use in the year select -
intervalThe interval for the minutes select. Defaults to 1 -
separatorThe 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 toupordownif you want to force rounding in either direction. Defaults to null. -
value|defaultThe default value to be used by the input. A value in$this->datamatching the field name will override this value. If no default is providedtime()will be used.
Parameters
- string
$fieldName - Prefix name for the SELECT element
- string
$dateFormatoptional 'DMY' - DMY, MDY, YMD, or null to not generate date inputs.
- string
$timeFormatoptional '12' - 12, 24, or null to not generate time inputs.
- array
$attributesoptional array() - Array of Attributes
Returns
stringGenerated set of select boxes for the date and time formats chosen.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::dateTimeday()source public
day( string $fieldName null , array $attributes array() )
Returns a SELECT element for days.
Attributes:
-
empty- If true, the empty select option is shown. If a string, that string is displayed as the empty element. -
valueThe selected value of the input.
Parameters
- string
$fieldNameoptional null - Prefix name for the SELECT element
- array
$attributesoptional array() - HTML attributes for the select element
Returns
stringA generated day select box.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::daydomIdSuffix()source public
domIdSuffix( 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.
Parameters
- string
$value - The value that should be transferred into a DOM ID suffix.
- string
$typeoptional 'html4' - Doctype to use. Defaults to html4.
Returns
stringDOM ID
end()source public
end( 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'
Parameters
- string|array
$optionsoptional null - as a string will use $options as the value of button,
- array
$secureAttributesoptional array() will be passed as html attributes into the hidden input elements generated for the Security Component.
Returns
stringa closing FORM tag optional submit button.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#closing-the-formerror()source public
error( string $field , string|array $text null , array $options array() )
Returns a formatted error message for given FORM field, NULL if no errors.
Options:
-
escapeboolean - Whether or not to html escape the contents of the error. -
wrapmixed - Whether or not the error message should be wrapped in a div. If a string, will be used as the HTML tag to use. -
classstring - The class name for the error message
Parameters
- string
$field - A field name, like "Modelname.fieldname"
- string|array
$textoptional null Error message as string or array of messages. If array contains
attributeskey it will be used as options for error container- array
$optionsoptional array() -
Rendering options for
wrapper tag
Returns
string|nullIf there are errors this method returns an error message, otherwise null.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::errorfile()source public
file( string $fieldName , array $options array() )
Creates file input widget.
Parameters
- string
$fieldName - Name of a field, in the form "Modelname.fieldname"
- array
$optionsoptional array() - Array of HTML attributes.
Returns
stringA generated file input.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::filehidden()source public
hidden( string $fieldName , array $options array() )
Creates a hidden input field.
Parameters
- string
$fieldName - Name of a field, in the form of "Modelname.fieldname"
- array
$optionsoptional array() - Array of HTML attributes.
Returns
stringA generated hidden input
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hiddenhour()source public
hour( string $fieldName , boolean $format24Hours false , array $attributes array() )
Returns a SELECT element for hours.
Attributes:
-
empty- If true, the empty select option is shown. If a string, that string is displayed as the empty element. -
valueThe selected value of the input.
Parameters
- string
$fieldName - Prefix name for the SELECT element
- boolean
$format24Hoursoptional false - True for 24 hours format
- array
$attributesoptional array() - List of HTML attributes
Returns
stringCompleted hour select input
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hourinput()source public
input( string $fieldName , array $options array() )
Generates a form input element complete with label and wrapper div
Options
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- Eitherfalseto 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 tofalseto 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. - Default input format order: array('before', 'label', 'between', 'input', 'after', 'error')
- Default checkbox format order: array('before', 'input', 'between', 'label', 'after', 'error')
- Hidden input will not be formatted
- Radio buttons cannot have the order of input and label elements controlled with these settings.
Parameters
- string
$fieldName - This should be "Modelname.fieldname"
- array
$optionsoptional array() - Each type of input takes different options.
Returns
stringCompleted form widget.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#creating-form-elementsinputDefaults()source public
inputDefaults( array $defaults null , boolean $merge false )
Set/Get inputDefaults for form elements
Parameters
- array
$defaultsoptional null - New default values
- boolean
$mergeoptional false - Merge with current defaults
Returns
arrayinputDefaults
inputs()source public
inputs( 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.
Parameters
- array
$fieldsoptional null - An array of fields to generate inputs for, or null.
- array
$blacklistoptional null - A simple array of fields to not create inputs for.
- array
$optionsoptional array() Options array. Valid keys are: -
fieldsetSet to false to disable the fieldset. If a string is supplied it will be used as the class name for the fieldset element. -legendSet to false to disable the legend for the generated input set. Or supply a string to customize the legend text.
Returns
stringCompleted form inputs.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::inputsisFieldError()source public
isFieldError( string $field )
Returns true if there is an error for the given field, otherwise false
Parameters
- string
$field - This should be "Modelname.fieldname"
Returns
booleanIf there are errors this method returns true, else false.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::isFieldErrorlabel()source public
label( 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.
Options
-
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.
Parameters
- string
$fieldNameoptional null - This should be "Modelname.fieldname"
- string
$textoptional null Text that will appear in the label field. If $text is left undefined the text will be inflected from the fieldName.
- array|string
$optionsoptional array() - An array of HTML attributes, or a string, to be used as a class name.
Returns
stringThe formatted LABEL element
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::labelmeridian()source public
meridian( string $fieldName , array $attributes array() )
Returns a SELECT element for AM or PM.
Attributes:
-
empty- If true, the empty select option is shown. If a string, that string is displayed as the empty element. -
valueThe selected value of the input.
Parameters
- string
$fieldName - Prefix name for the SELECT element
- array
$attributesoptional array() - Array of Attributes
Returns
stringCompleted meridian select input
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::meridianminute()source public
minute( string $fieldName , array $attributes array() )
Returns a SELECT element for minutes.
Attributes:
-
empty- If true, the empty select option is shown. If a string, that string is displayed as the empty element. -
valueThe selected value of the input.
Parameters
- string
$fieldName - Prefix name for the SELECT element
- array
$attributesoptional array() - Array of Attributes
Returns
stringCompleted minute select input.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::minutemonth()source public
month( string $fieldName , array $attributes array() )
Returns a SELECT element for months.
Attributes:
-
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. -
valueThe selected value of the input.
Parameters
- string
$fieldName - Prefix name for the SELECT element
- array
$attributesoptional array() - Attributes for the select element
Returns
stringA generated month select dropdown.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::monthpostButton()source public
postButton( 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.
Options:
-
data- Array with key/value to pass in input hidden - Other options is the same of button method.
Parameters
- string
$title - The button's caption. Not automatically HTML encoded
- string|array
$url - URL as string or array
- array
$optionsoptional array() - Array of options and HTML attributes.
Returns
stringA HTML button tag.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postButtonpostLink()source public
postLink( 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.
Options:
-
data- Array with key/value to pass in input hidden -
method- 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. - Other options are the same of HtmlHelper::link() method.
- The option
onclickwill be replaced.
Parameters
- string
$title - The content to be wrapped by tags.
- string|array
$urloptional null - Cake-relative URL or array of URL parameters, or external URL (starts with http://)
- array
$optionsoptional array() - Array of HTML attributes.
- boolean|string
$confirmMessageoptional false JavaScript confirmation message. This argument is deprecated as of 2.6. Use
confirmkey in $options instead.
Returns
stringAn
<a /> element.Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postLinkradio()source public
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'),
); Attributes:
-
separator- define the string in between the radio buttons -
between- the string between legend and input set or array of strings to insert strings between each input block -
legend- control whether or not the widget set has a fieldset & legend -
fieldset- sets the class of the fieldset. Fieldset is only generated if legend attribute is provided -
value- indicate a value that is should be checked -
label- boolean to indicate whether or not labels for widgets show be displayed -
hiddenField- 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-continuous -
disabled- Set totrueordisabledto disable all the radio buttons. -
empty- Set totrueto create an input with the value '' as the first option. Whentruethe radio label will be 'empty'. Set this option to a string to control the label value.
Parameters
- string
$fieldName - Name of a field, like this "Modelname.fieldname"
- array
$optionsoptional array() - Radio button options array.
- array
$attributesoptional array() - Array of HTML attributes, and special attributes above.
Returns
stringCompleted radio widget set.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputssecure()source public
secure( 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'.
Parameters
- array|null
$fieldsoptional array() If set specifies the list of fields to use when generating the hash, else $this->fields is being used.
- array
$secureAttributesoptional array() will be passed as html attributes into the hidden input elements generated for the Security Component.
Returns
string|nullA hidden input field with a security hash, otherwise null.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::secureselect()source public
select( string $fieldName , array $options array() , array $attributes array() )
Returns a formatted SELECT element.
Attributes:
-
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. -
valueThe 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,truewill disable all checkboxes. You can also set disabled to a list of values you want to disable when creating checkboxes.
Using options
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'),
); Parameters
- string
$fieldName - Name attribute of the SELECT
- array
$optionsoptional array() Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the SELECT element
- array
$attributesoptional array() - The HTML attributes of the select element.
Returns
stringFormatted SELECT element
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputssubmit()source public
submit( 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.
Options
-
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' -
confirm- JavaScript confirmation message. - Other attributes will be assigned to the input element.
Options
-
div- Include a wrapping div? Defaults to true. Accepts sub options similar to FormHelper::input(). - Other attributes will be assigned to the input element.
Parameters
- string
$captionoptional null The label appearing on the button OR if string contains :// or the extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension exists, AND the first character is /, image is relative to webroot, OR if the first character is not /, image is relative to webroot/img.
- array
$optionsoptional array() - Array of options. See above.
Returns
stringA HTML submit button
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::submittagIsInvalid()source public
tagIsInvalid( )
Returns false if given form field described by the current entity has no errors. Otherwise it returns the validation message
Returns
mixedEither false when there are no errors, or an array of error strings. An error string could be ''.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::tagIsInvalidtextarea()source public
textarea( string $fieldName , array $options array() )
Creates a textarea widget.
Options:
-
escape- Whether or not the contents of the textarea should be escaped. Defaults to true.
Parameters
- string
$fieldName - Name of a field, in the form "Modelname.fieldname"
- array
$optionsoptional array() - Array of HTML attributes, and special options above.
Returns
stringA generated HTML text input element
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::textareaunlockField()source public
unlockField( 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.
Parameters
- string
$nameoptional null - The dot separated name for the field.
Returns
mixedEither null, or the list of fields.
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::unlockFieldyear()source public
year( string $fieldName , integer $minYear null , integer $maxYear null , array $attributes array() )
Returns a SELECT element for years
Attributes:
-
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' -
valueThe selected value of the input.
Parameters
- string
$fieldName - Prefix name for the SELECT element
- integer
$minYearoptional null - First year in sequence
- integer
$maxYearoptional null - Last year in sequence
- array
$attributesoptional array() - Attribute array for the select elements.
Returns
stringCompleted year select input
Link
http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::yearProperties detail
$_domIdSuffixessource
protected array
Holds already used DOM ID suffixes to avoid collisions with multiple form field elements.
array()
$_inputDefaultssource
protected array
Persistent default options used by input(). Set by FormHelper::create().
array()
$_lastActionsource
protected string
The action attribute value of the last created form. Used to make form/request specific hashes for SecurityComponent.
''
$_modelssource
protected array
Holds the model references already loaded by this helper product of trying to inspect them out of field names
array()
$_optionssource
protected array
Options used by DateTime fields
array(
'day' => array(), 'minute' => array(), 'hour' => array(),
'month' => array(), 'year' => array(), 'meridian' => array()
) $_unlockedFieldssource
protected array
An array of field names that have been excluded from the Token hash used by SecurityComponent's validatePost method
See
FormHelper::_secure()SecurityComponent::validatePost()
array()
$requestTypesource
public string
Defines the type of form being created. Set by FormHelper::create().
null
$validationErrorssource
public array
Holds all the validation errors for models loaded and inspected it can also be set manually to be able to display custom error messages in the any of the input fields generated by this helper
array()
Magic properties detail
$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.
https://api.cakephp.org/2.9/class-FormHelper.html