Form helper library.
Automatic generation of HTML FORMs from given data.
Cake\View\Helper\FormHelper uses Cake\View\Helper\IdGeneratorTrait, Cake\View\Helper\SecureFieldTokenTrait, Cake\View\StringTemplateTrait __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', ['value' => 'test']);
Will make an input like:
<input type="search" id="UserQuery" name="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 stringCake\Core\Exception\ExceptionCake\View\Helper::__call() __construct( Cake\View\View $View , array $config [] )
Construct the widgets and binds the default context providers
Cake\View\View $View $config optional [] Cake\View\Helper::__construct() _addDefaultContextProviders( )
Add the default suite of context providers provided by CakePHP.
_csrfField( )
Return a CSRF input if the request data is present. Used to secure forms in conjunction with CsrfComponent & SecurityComponent
string_datetimeOptions( array $options )
Helper method for converting from FormHelper options data to widget format.
$options array_extractOption( string $name , array $options , mixed $default null )
Extracts a single option from an options array.
$name $options $default optional null mixed_formUrl( Cake\View\Form\ContextInterface $context , array $options )
Create the URL for a form based on the options.
Cake\View\Form\ContextInterface $context $options string_getContext( mixed $data [] )
Find the matching context provider for the data.
If no type can be matched a NullContext will be returned.
$data optional [] mixedRuntimeException_getInput( string $fieldName , array $options )
Generates an input element
$fieldName $options string_getLabel( string $fieldName , array $options )
Generate label for input
$fieldName $options boolean|string_groupTemplate( array $options )
Generates an group template element
$options string_initInputField( string $field , array $options [] )
Sets field defaults and adds field to form security input hash. Will also add the 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.default - mixed - The value to use if there is no value in the form's context.disabled - mixed - Either a boolean indicating disabled state, or the string in a numerically indexed value.This method will convert a numerically indexed 'disabled' into an associative array value. FormHelper's internals expect associative options.
The output of this function is a more complete set of input attributes that can be passed to a form widget to generate the actual input.
$field $options optional [] array_inputContainerTemplate( array $options )
Generates an input container template
$options string_inputLabel( string $fieldName , string $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_inputType( string $fieldName , array $options )
Returns the input type that was guessed for the provided fieldName, based on the internal type it is associated too, its name and the variables that can be found in the view template
$fieldName $options string_isRequiredField( Cake\Validation\ValidationSet $validationRules )
Returns if a field is required to be filled based on validation properties from the validating object.
Cake\Validation\ValidationSet $validationRules boolean_lastAction( string|array $url )
Correctly store the last created form action URL.
$url _magicOptions( string $fieldName , array $options , boolean $allowOverride )
Magically set option type and corresponding options
$fieldName $options $allowOverride array_optionsOptions( string $fieldName , array $options )
Selects the variable containing the options for a select field if present, and sets the value to the 'options' key in the options array.
$fieldName $options array_parseOptions( string $fieldName , array $options )
Generates input options array
$fieldName $options array_secure( boolean $lock , string|array $field , mixed $value null )
Determine which fields of a form should be used for hash. Populates $this->fields
$lock $field $value optional null _secureFieldName( string $name )
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. If filename is of form Model[field] an array of fieldname parts like ['Model', 'field'] is returned.
$name array_singleDatetime( array $options , string $keep )
Helper method for the various single datetime component methods.
$options $keep arrayaddContextProvider( string $type , callable $check )
Add a new context type.
Form context types allow FormHelper to interact with data providers that come from outside CakePHP. For example if you wanted to use an alternative ORM like Doctrine you could create and connect a new context class to allow FormHelper to read metadata from doctrine.
$type $check addWidget( string $name , array|Cake\View\Widget\WidgetInterface $spec )
Add a new widget to FormHelper.
Allows you to add or replace widget instances with custom code.
$name Cake\View\Widget\WidgetInterface $spec allInputs( array $fields [] , array $options [] )
Generate a set of inputs for $fields. If $fields is empty the fields of current model will be used.
You can customize individual inputs through $fields.
$this->Form->allInputs([ 'name' => ['label' => 'custom label'] ]);
You can exclude fields by specifying them as false:
$this->Form->allInputs(['title' => false]);
In the above example, no field would be generated for the title field.
$fields optional [] $options optional [] fieldset Set to false to disable the fieldset. You can also pass an array of params to be applied as HTML attributes to the fieldset tag. If you pass an empty array, the fieldset will be enabled - legend Set to false to disable the legend for the generated input set. Or supply a string to customize the legend text.stringbutton( string $title , array $options [] )
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 [] stringcheckbox( string $fieldName , array $options [] )
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 [] string|arraycontext( Cake\View\Form\ContextInterface|null $context null )
Get the context instance for the current form set.
If there is no active form null will be returned.
Cake\View\Form\ContextInterface|null $context optional null null|Cake\View\Form\ContextInterfacecreate( mixed $model null , array $options [] )
Returns an HTML FORM element.
type Form method defaults to autodetecting based on the form context. If the form context's isCreate() method returns false, a PUT request will be done.action The controller action the form submits to, (optional). Use this option if you don't need to change the controller from the current request's controller.url The URL the form submits to. Can be a string or a URL array. If you use 'url' you should leave 'action' undefined.encoding Set the accept-charset encoding for the form. Defaults to Configure::read('App.encoding')
templates The templates you want to use for this form. Any templates will be merged on top of the already loaded templates. This option can either be a filename in /config that contains the templates you want to load, or an array of templates to use.context Additional options for the context class. For example the EntityContext accepts a 'table' option that allows you to set the specific Table class the form should be based on.idPrefix Prefix for generated ID attributes.$model optional null $options optional [] stringdate( string $fieldName , array $options [] )
Generate date inputs.
See dateTime() for date options.
$fieldName $options optional [] stringdateTime( string $fieldName , array $options [] )
Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
empty - If true, the empty select option is shown. If a string, that string is displayed as the empty element.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.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 selectorderYear - Order of year values in select options. Possible values 'asc', 'desc'. Default 'desc'.empty - If true, the empty select option is shown. If a string,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.timeFormat The time format to use, either 12 or 24.interval The interval for the minutes select. Defaults to 1round - Set to up or down if you want to force rounding in either direction. Defaults to null.second Set to true to enable seconds drop down.To control the order of inputs, and any elements/content between the inputs you can override the dateWidget template. By default the dateWidget template is:
{{month}}{{day}}{{year}}{{hour}}{{minute}}{{second}}{{meridian}}
$fieldName $options optional [] stringday( string $fieldName null , array $options [] )
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 $options optional [] stringend( array $secureAttributes [] )
Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden input fields where appropriate.
$secureAttributes optional [] stringerror( string $field , string|array $text null , array $options [] )
Returns a formatted error message for given form field, '' if no errors.
Uses the error, errorList and errorItem templates. The errorList and errorItem templates are used to format multiple error messages per field.
escape boolean - Whether or not to html escape the contents of the error.$field $text optional null $options optional [] stringfieldset( string $fields '' , array $options [] )
Wrap a set of inputs in a fieldset
$fields optional '' $options optional [] fieldset Set to false to disable the fieldset. You can also pass an array of params to be applied as HTML attributes to the fieldset tag. If you pass an empty array, the fieldset will be enabled - legend Set to false to disable the legend for the generated input set. Or supply a string to customize the legend text.stringfile( string $fieldName , array $options [] )
Creates file input widget.
$fieldName $options optional [] stringhidden( string $fieldName , array $options [] )
Creates a hidden input field.
$fieldName $options optional [] stringhour( string $fieldName , array $options [] )
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.format Set to 12 or 24 to use 12 or 24 hour formatting. Defaults to 24.$fieldName $options optional [] stringimplementedEvents( )
Event listeners.
arrayCake\View\Helper::implementedEvents() input( string $fieldName , array $options [] )
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(). 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().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).empty - String or boolean to enable empty select box options.nestedInput - Used with checkbox and radio inputs. Set to false to render inputs outside of label elements. Can be set to true on any input to force the input inside the label. If you enable this option for radio buttons you will also need to modify the default radioWrapper template.templates - The templates you want to use for this input. Any templates will be merged on top of the already loaded templates. This option can either be a filename in /config that contains the templates you want to load, or an array of templates to use.$fieldName $options optional [] stringinputs( array $fields , array $options [] )
Generate a set of inputs for $fields wrapped in a fieldset element.
You can customize individual inputs through $fields.
$this->Form->inputs([ 'name' => ['label' => 'custom label'], 'email' ]);
$fields $options optional [] fieldset Set to false to disable the fieldset. You can also pass an array of params to be applied as HTML attributes to the fieldset tag. If you pass an empty array, the fieldset will be enabled - 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 , string $text null , array $options [] )
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('published'); <label for="PostPublished">Published</label>
Custom text:
echo $this->Form->label('published', 'Publish'); <label for="published">Publish</label>
Custom attributes:
echo $this->Form->label('published', 'Publish', [ 'for' => 'post-publish' ]); <label for="post-publish">Publish</label>
Nesting an input tag:
echo $this->Form->label('published', 'Publish', [ 'for' => 'published', 'input' => $this->text('published'), ]); <label for="post-publish">Publish <input type="text" name="published"></label>
If you want to nest inputs in the labels, you will need to modify the default templates.
$fieldName $text optional null $options optional [] stringmeridian( string $fieldName , array $options [] )
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 $options optional [] stringminute( string $fieldName , array $options [] )
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.interval The interval that minute options should be created at.round How you want the value rounded when it does not fit neatly into an interval. Accepts 'up', 'down', and null.$fieldName $options optional [] stringmonth( string $fieldName , array $options [] )
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 $options optional [] stringmultiCheckbox( string $fieldName , array|Traversable $options , array $attributes [] )
Creates a set of checkboxes out of options.
escape - If true contents of options will be HTML entity encoded. Defaults to true.val 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 checkboxes, true will disable all checkboxes. You can also set disabled to a list of values you want to disable when creating checkboxes.hiddenField - Set to false to remove the hidden field that ensures a value is always submitted.Can be used in place of a select box with the multiple attribute.
$fieldName $options $attributes optional [] stringpostButton( string $title , string|array $url , array $options [] )
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 [] stringpostLink( string $title , string|array $url null , array $options [] )
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 block option 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::button() or 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 - Confirm message to show.block - Set to true to append form to view block "postLink" or provide custom block name.onclick will be replaced.$title $url optional null $options optional [] string<a /> element.radio( string $fieldName , array|Traversable $options [] , array $attributes [] )
Creates a set of radio widgets.
value - Indicates the value when this radio button is checked.label - boolean to indicate whether or not labels for widgets should 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 are non-continuous.disabled - 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 [] $attributes optional [] stringresetTemplates( )
Restores the default values built into FormHelper.
This method will not reset any templates set in custom widgets.
secure( array $fields [] , array $secureAttributes [] )
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 [] $secureAttributes optional [] string|nullselect( string $fieldName , array|Traversable $options [] , array $attributes [] )
Returns a formatted SELECT element.
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.val The selected value of the input.disabled - Control the disabled attribute. When creating a select box, set to true to disable the select box. Set to an array to disable specific option elements.A simple array will create normal options:
$options = [1 => 'one', 2 => 'two']; $this->Form->select('Model.field', $options));
While a nested options array will create optgroups with options inside them.
$options = [ 1 => 'bill', 'fred' => [ 2 => 'fred', 3 => 'fred jr.' ] ]; $this->Form->select('Model.field', $options);
If you have multiple options that need to have the same value attribute, you can use an array of arrays to express this:
$options = [ ['text' => 'United states', 'value' => 'USA'], ['text' => 'USA', 'value' => 'USA'], ];
$fieldName $options optional [] $attributes optional [] stringsubmit( string $caption null , array $options [] )
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.
type - Set to 'reset' for reset inputs. Defaults to 'submit'templateVars - Additional template variables for the input element and its container.$caption optional null $options optional [] stringtextarea( string $fieldName , array $options [] )
Creates a textarea widget.
escape - Whether or not the contents of the textarea should be escaped. Defaults to true.$fieldName $options optional [] stringtime( string $fieldName , array $options [] )
Generate time inputs.
See dateTime() for time options.
$fieldName $options optional [] stringunlockField( string|null $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 array|nullwidget( string $name , array $data [] )
Render a named widget.
This is a lower level method. For built-in widgets, you should be using methods like text, hidden, and radio. If you are using additional widgets you should use this method render the widget without the label or wrapping div.
$name $data optional [] stringwidgetRegistry( Cake\View\Widget\WidgetRegistry $instance null , array $widgets [] )
Set the widget registry the helper will use.
Cake\View\Widget\WidgetRegistry $instance optional null $widgets optional [] Cake\View\Widget\WidgetRegistryyear( string $fieldName , array $options [] )
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.maxYear The max year to appear in the select element.minYear The min year to appear in the select element.$fieldName $options optional [] string__debugInfo( )
Returns an array that can be used to describe the internal state of this object.
array__get( string $name )
Lazy loads helpers.
$name Cake\View\Helper|null_confirm( string $message , string $okCode , string $cancelCode '' , array $options [] )
Returns a string to be used as onclick handler for confirm dialogs.
$message $okCode $cancelCode optional '' $options optional [] stringaddClass( array $options [] , string $class null , string $key 'class' )
Adds the given class to the element options
$options optional [] $class optional null $key optional 'class' array_domId( string $value )
Generate an ID suitable for use in an ID attribute.
$value string_id( string $name , string $val )
Generate an ID attribute for an element.
Ensures that id's for a given set of fields are unique.
$name $val string_buildFieldToken( string $url , array $fields , array $unlockedFields [] )
Generate the token data for the provided inputs.
$url $fields $unlockedFields optional [] arrayformatTemplate( string $name , array $data )
Format a template string with $data
$name $data stringtemplater( )
templater
Cake\View\StringTemplatetemplates( string|null|array $templates null )
Get/set templates to use.
$templates optional null mixed_configDelete( string $key )
Delete a single config key
$key Cake\Core\Exception\Exception_configRead( string|null $key )
Read a config variable
$key mixed_configWrite( string|array $key , mixed $value , boolean|string $merge false )
Write a config variable
$key $value $merge optional false Cake\Core\Exception\Exceptionconfig( string|array|null $key null , mixed|null $value null , boolean $merge true )
Reading the whole config:
$this->config();
Reading a specific value:
$this->config('key');
Reading a nested value:
$this->config('some.nested.key');
Setting a specific value:
$this->config('key', $value);
Setting a nested value:
$this->config('some.nested.key', $value);
Updating multiple config settings at the same time:
$this->config(['one' => 'value', 'another' => 'value']);
$key optional null $value optional null $merge optional true mixedCake\Core\Exception\ExceptionconfigShallow( string|array $key , mixed|null $value null )
Merge provided config with existing config. Unlike config() which does a recursive merge for nested keys, this method does a simple merge.
Setting a specific value:
$this->config('key', $value);
Setting a nested value:
$this->config('some.nested.key', $value);
Updating multiple config settings at the same time:
$this->config(['one' => 'value', 'another' => 'value']);
$key $value optional null mixedstring | SECURE_SKIP Constant used internally to skip the securing process, and neither add the field to the hash or to the unlocked fields. | 'skip' |
public array
Holds the fields ['field_name' => ['type' => 'string', 'length' => 100]], primaryKey and validates ['field_name']
[]
protected boolean
Whether the config property has already been configured with defaults
false public Cake\View\Helper\HtmlHelper
public Cake\View\Helper\UrlHelper
© 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/3.1/class-Cake.View.Helper.FormHelper.html