\Cake\View\HelperFormHelper

Form helper library.

Automatic generation of HTML FORMs from given data.

Summary

Methods
Properties
Constants
setTemplates()
getTemplates()
templates()
formatTemplate()
templater()
__construct()
__call()
__get()
__set()
getView()
addClass()
implementedEvents()
initialize()
__debugInfo()
setConfig()
getConfig()
config()
configShallow()
widgetRegistry()
getWidgetLocator()
setWidgetLocator()
contextFactory()
create()
end()
secure()
unlockField()
isFieldError()
error()
label()
allControls()
allInputs()
controls()
inputs()
fieldset()
control()
input()
checkbox()
radio()
textarea()
hidden()
file()
button()
postButton()
postLink()
submit()
select()
multiCheckbox()
day()
year()
month()
hour()
minute()
meridian()
dateTime()
time()
date()
addContextProvider()
context()
addWidget()
widget()
resetTemplates()
getValueSources()
setValueSources()
getSourceValue()
text()
number()
email()
password()
search()
$helpers
$fieldset
$tags
$fields
$requestType
$Html
$Url
SECURE_SKIP
_clearIds()
_id()
_domId()
_buildFieldToken()
_confirm()
_cleanConfirmMessage()
_configRead()
_configWrite()
_configDelete()
_formUrl()
_lastAction()
_csrfField()
_secure()
_groupTemplate()
_inputContainerTemplate()
_getInput()
_parseOptions()
_inputType()
_optionsOptions()
_magicOptions()
_getLabel()
_extractOption()
_inputLabel()
_singleDatetime()
_datetimeOptions()
_initInputField()
_isDisabled()
_secureFieldName()
_getContext()
$_idPrefix
$_idSuffixes
$_templater
$_defaultConfig
$_helperMap
$_View
$_config
$_configInitialized
$_datetimeParts
$_datetimeOptions
$_defaultWidgets
$_unlockedFields
$_locator
$_context
$_contextFactory
$_lastAction
$_valueSources
$_groupedInputTypes
N/A
No private methods found
No private properties found
N/A

Constants

SECURE_SKIP

SECURE_SKIP = 'skip' : string

Constant used internally to skip the securing process, and neither add the field to the hash or to the unlocked fields.

Properties

$helpers

$helpers : array

Other helpers used by FormHelper

Type

array

$fieldset

$fieldset : array

Unused.

Type

array

$tags

$tags : array

Unused.

Type

array

$fields

$fields : array

List of fields created, used with secure forms.

Type

array

$requestType

$requestType : string|null

Defines the type of form being created. Set by FormHelper::create().

Type

string|null

$Html

$Html : \Cake\View\Helper\HtmlHelper

Type

\Cake\View\Helper\HtmlHelper

$Url

$Url : \Cake\View\Helper\UrlHelper

Type

\Cake\View\Helper\UrlHelper

$_idPrefix

$_idPrefix : string|null

Prefix for id attribute.

Type

string|null

$_idSuffixes

$_idSuffixes : array

A list of id suffixes used in the current rendering.

Type

array

$_defaultConfig

$_defaultConfig : array

Default config for the helper.

Type

array

$_helperMap

$_helperMap : array

A helper lookup table used to lazy load helper objects.

Type

array

$_View

$_View : \Cake\View\View

The View instance this helper is attached to

Type

\Cake\View\View

$_config

$_config : array

Runtime config

Type

array

$_configInitialized

$_configInitialized : boolean

Whether the config property has already been configured with defaults

Type

boolean

$_datetimeParts

$_datetimeParts : array

The various pickers that make up a datetime picker.

Type

array

$_datetimeOptions

$_datetimeOptions : array

Special options used for datetime inputs.

Type

array

$_defaultWidgets

$_defaultWidgets : array

Default widgets

Type

array

$_unlockedFields

$_unlockedFields : array

An array of field names that have been excluded from the Token hash used by SecurityComponent's validatePost method

Type

array

$_lastAction

$_lastAction : string

The action attribute value of the last created form.

Used to make form/request specific hashes for SecurityComponent.

Type

string

$_valueSources

$_valueSources : array

The sources to be used when retrieving prefilled input values.

Type

array

$_groupedInputTypes

$_groupedInputTypes : array

Grouped input types.

Type

array

Methods

setTemplates()

setTemplates(array  $templates) : $this

Sets templates to use.

Parameters

array $templates

Templates to be added.

Returns

$this

getTemplates()

getTemplates(string|null  $template = null) : string|array

Gets templates to use or a specific template.

Parameters

string|null $template

String for reading a specific template, null for all.

Returns

string|array

templates()

templates(string|null|array  $templates = null) : $this|string|array

Gets/sets templates to use.

Parameters

string|null|array $templates

null or string allow reading templates. An array allows templates to be added.

Returns

$this|string|array

formatTemplate()

formatTemplate(string  $name, array  $data) : string

Formats a template string with $data

Parameters

string $name

The template name.

array $data

The data to insert.

Returns

string

__construct()

__construct(\Cake\View\View  $View, array  $config = array()) 

Construct the widgets and binds the default context providers

Parameters

\Cake\View\View $View

The View this helper is being attached to.

array $config

Configuration settings for the helper.

__call()

__call(string  $method, array  $params) : string

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', ['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.

Parameters

string $method

Method name / input type to make.

array $params

Parameters for the method call

Throws

\Cake\Core\Exception\Exception

When there are no params for the method call.

Returns

string —

Formatted input method.

__get()

__get(string  $name) : \Cake\View\Helper|null

Lazy loads helpers.

Parameters

string $name

Name of the property being accessed.

Returns

\Cake\View\Helper|null —

Helper instance if helper with provided name exists

__set()

__set(string  $name, mixed  $value) : void

Magic setter for removed properties.

Parameters

string $name

Property name.

mixed $value

Value to set.

getView()

getView() : \Cake\View\View

Get the view instance this helper is bound to.

Returns

\Cake\View\View

The bound view instance.

addClass()

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

Adds the given class to the element options

Parameters

array $options

Array options/attributes to add a class to

string|null $class

The class name being added.

string $key

the key to use for class.

Returns

array —

Array of options with $key set.

implementedEvents()

implementedEvents() : array

Event listeners.

By defining one of the callback methods a helper is assumed to be interested in the related event.

Override this method if you need to add non-conventional event listeners. Or if you want helpers to listen to non-standard events.

Returns

array

initialize()

initialize(array  $config) : void

Constructor hook method.

Implement this method to avoid having to overwrite the constructor and call parent.

Parameters

array $config

The configuration settings provided to this helper.

__debugInfo()

__debugInfo() : array

Returns an array that can be used to describe the internal state of this object.

Returns

array

setConfig()

setConfig(string|array  $key, mixed|null  $value = null, boolean  $merge = true) : $this

Sets the config.

Usage

Setting a specific value:

$this->setConfig('key', $value);

Setting a nested value:

$this->setConfig('some.nested.key', $value);

Updating multiple config settings at the same time:

$this->setConfig(['one' => 'value', 'another' => 'value']);

Parameters

string|array $key

The key to set, or a complete array of configs.

mixed|null $value

The value to set.

boolean $merge

Whether to recursively merge or overwrite existing config, defaults to true.

Throws

\Cake\Core\Exception\Exception

When trying to set a key that is invalid.

Returns

$this

getConfig()

getConfig(string|null  $key = null, mixed  $default = null) : mixed

Returns the config.

Usage

Reading the whole config:

$this->getConfig();

Reading a specific value:

$this->getConfig('key');

Reading a nested value:

$this->getConfig('some.nested.key');

Reading with default value:

$this->getConfig('some-key', 'default-value');

Parameters

string|null $key

The key to get or null for the whole config.

mixed $default

The return value when the key does not exist.

Returns

mixed —

Config value being read.

config()

config(string|array|null  $key = null, mixed|null  $value = null, boolean  $merge = true) : mixed

Gets/Sets the config.

Usage

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']);

Parameters

string|array|null $key

The key to get/set, or a complete array of configs.

mixed|null $value

The value to set.

boolean $merge

Whether to recursively merge or overwrite existing config, defaults to true.

Throws

\Cake\Core\Exception\Exception

When trying to set a key that is invalid.

Returns

mixed —

Config value being read, or the object itself on write operations.

configShallow()

configShallow(string|array  $key, mixed|null  $value = null) : $this

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->configShallow('key', $value);

Setting a nested value:

$this->configShallow('some.nested.key', $value);

Updating multiple config settings at the same time:

$this->configShallow(['one' => 'value', 'another' => 'value']);

Parameters

string|array $key

The key to set, or a complete array of configs.

mixed|null $value

The value to set.

Returns

$this

widgetRegistry()

widgetRegistry(\Cake\View\Widget\WidgetRegistry|null  $instance = null, array  $widgets = array()) : \Cake\View\Widget\WidgetRegistry

Set the widget registry the helper will use.

Parameters

\Cake\View\Widget\WidgetRegistry|null $instance

The registry instance to set.

array $widgets

An array of widgets

Returns

\Cake\View\Widget\WidgetRegistry

getWidgetLocator()

getWidgetLocator() : \Cake\View\Widget\WidgetLocator

Get the widget locator currently used by the helper.

Returns

\Cake\View\Widget\WidgetLocator

Current locator instance

setWidgetLocator()

setWidgetLocator(\Cake\View\Widget\WidgetLocator  $instance) : $this

Set the widget locator the helper will use.

Parameters

\Cake\View\Widget\WidgetLocator $instance

The locator instance to set.

Returns

$this

contextFactory()

contextFactory(\Cake\View\Form\ContextFactory|null  $instance = null, array  $contexts = array()) : \Cake\View\Form\ContextFactory

Set the context factory the helper will use.

Parameters

\Cake\View\Form\ContextFactory|null $instance

The context factory instance to set.

array $contexts

An array of context providers.

Returns

\Cake\View\Form\ContextFactory

create()

create(mixed  $context = null, array  $options = array()) : string

Returns an HTML form element.

Options:

  • 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.
  • method Set the form's method attribute explicitly.
  • 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. Deprecated since 3.2, use url.
  • 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')
  • enctype Set the form encoding explicitly. By default type => file will set enctype to multipart/form-data.
  • 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.
  • valueSources The sources that values should be read from. See FormHelper::setValueSources()
  • templateVars Provide template variables for the formStart template.

Parameters

mixed $context

The context for which the form is being defined. Can be a ContextInterface instance, ORM entity, ORM resultset, or an array of meta data. You can use false or null to make a context-less form.

array $options

An array of html attributes and options.

Returns

string —

An formatted opening FORM tag.

end()

end(array  $secureAttributes = array()) : string

Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden input fields where appropriate.

Resets some parts of the state, shared among multiple FormHelper::create() calls, to defaults.

Parameters

array $secureAttributes

Secure attributes which will be passed as HTML attributes into the hidden input elements generated for the Security Component.

Returns

string —

A closing FORM tag.

secure()

secure(array  $fields = array(), array  $secureAttributes = array()) : string

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 $fields

If set specifies the list of fields to use when generating the hash, else $this->fields is being used.

array $secureAttributes

will be passed as HTML attributes into the hidden input elements generated for the Security Component.

Returns

string —

A hidden input field with a security hash, or empty string when secured forms are not in use.

unlockField()

unlockField(string|null  $name = null) : array|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|null $name

The dot separated name for the field.

Returns

array|null —

Either null, or the list of fields.

isFieldError()

isFieldError(string  $field) : boolean

Returns true if there is an error for the given field, otherwise false

Parameters

string $field

This should be "modelname.fieldname"

Returns

boolean —

If there are errors this method returns true, else false.

error()

error(string  $field, string|array|null  $text = null, array  $options = array()) : string

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.

Options:

  • escape boolean - Whether or not to html escape the contents of the error.

Parameters

string $field

A field name, like "modelname.fieldname"

string|array|null $text

Error message as string or array of messages. If an array, it should be a hash of key names => messages.

array $options

See above.

Returns

string —

Formatted errors or ''.

label()

label(string  $fieldName, string|null  $text = null, array  $options = array()) : string

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().
  • escape - Set to false to turn off escaping of label text. Defaults to true.

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.

Parameters

string $fieldName

This should be "modelname.fieldname"

string|null $text

Text that will appear in the label field. If $text is left undefined the text will be inflected from the fieldName.

array $options

An array of HTML attributes.

Returns

string —

The formatted LABEL element

allControls()

allControls(array  $fields = array(), array  $options = array()) : string

Generate a set of controls for `$fields`. If $fields is empty the fields of current model will be used.

You can customize individual controls through $fields.

$this->Form->allControls([
  'name' => ['label' => 'custom label']
]);

You can exclude fields by specifying them as false:

$this->Form->allControls(['title' => false]);

In the above example, no field would be generated for the title field.

Parameters

array $fields

An array of customizations for the fields that will be generated. This array allows you to set custom types, labels, or other options.

array $options

Options array. Valid keys are:

  • 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 control set. Or supply a string to customize the legend text.

Returns

string —

Completed form controls.

allInputs()

allInputs(array  $fields = array(), array  $options = array()) : string

Generate a set of controls for `$fields`. If $fields is empty the fields of current model will be used.

Parameters

array $fields

An array of customizations for the fields that will be generated. This array allows you to set custom types, labels, or other options.

array $options

Options array. Valid keys are:

  • 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 control set. Or supply a string to customize the legend text.

Returns

string —

Completed form controls.

controls()

controls(array  $fields, array  $options = array()) : string

Generate a set of controls for `$fields` wrapped in a fieldset element.

You can customize individual controls through $fields.

$this->Form->controls([
  'name' => ['label' => 'custom label'],
  'email'
]);

Parameters

array $fields

An array of the fields to generate. This array allows you to set custom types, labels, or other options.

array $options

Options array. Valid keys are:

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

Returns

string —

Completed form inputs.

inputs()

inputs(array  $fields, array  $options = array()) : string

Generate a set of controls for `$fields` wrapped in a fieldset element.

Parameters

array $fields

An array of the fields to generate. This array allows you to set custom types, labels, or other options.

array $options

Options array. Valid keys are:

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

Returns

string —

Completed form inputs.

fieldset()

fieldset(string  $fields = '', array  $options = array()) : string

Wrap a set of inputs in a fieldset

Parameters

string $fields

the form inputs to wrap in a fieldset

array $options

Options array. Valid keys are:

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

Returns

string —

Completed form inputs.

control()

control(string  $fieldName, array  $options = array()) : string

Generates a form control 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(). 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.
  • labelOptions - Either false to disable label around nestedWidgets e.g. radio, multicheckbox or an array of attributes for the label tag. selected will be added to any classes e.g. class => 'myclass' where widget is checked

Parameters

string $fieldName

This should be "modelname.fieldname"

array $options

Each type of input takes different options.

Returns

string —

Completed form widget.

input()

input(string  $fieldName, array  $options = array()) : string

Generates a form control element complete with label and wrapper div.

Parameters

string $fieldName

This should be "modelname.fieldname"

array $options

Each type of input takes different options.

Returns

string —

Completed form widget.

checkbox()

checkbox(string  $fieldName, array  $options = array()) : string|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 $options

Array of HTML attributes.

Returns

string|array —

An HTML text input element.

radio()

radio(string  $fieldName, array|\Traversable  $options = array(), array  $attributes = array()) : string

Creates a set of radio widgets.

Attributes:

  • value - Indicates the value when this radio button is checked.
  • label - Either false to disable label around the widget or an array of attributes for the label tag. selected will be added to any classes e.g. 'class' => 'myclass' where widget is checked
  • 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. Use an array of values to disable specific 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.

Parameters

string $fieldName

Name of a field, like this "modelname.fieldname"

array|\Traversable $options

Radio button options array.

array $attributes

Array of attributes.

Returns

string —

Completed radio widget set.

textarea()

textarea(string  $fieldName, array  $options = array()) : string

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 $options

Array of HTML attributes, and special options above.

Returns

string —

A generated HTML text input element

hidden()

hidden(string  $fieldName, array  $options = array()) : string

Creates a hidden input field.

Parameters

string $fieldName

Name of a field, in the form of "modelname.fieldname"

array $options

Array of HTML attributes.

Returns

string —

A generated hidden input

file()

file(string  $fieldName, array  $options = array()) : string

Creates file input widget.

Parameters

string $fieldName

Name of a field, in the form "modelname.fieldname"

array $options

Array of HTML attributes.

Returns

string —

A generated file input.

button()

button(string  $title, array  $options = array()) : string

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.
  • confirm - Confirm message to show. Form execution will only continue if confirmed then.

Parameters

string $title

The button's caption. Not automatically HTML encoded

array $options

Array of options and HTML attributes.

Returns

string —

A HTML button tag.

postButton()

postButton(string  $title, string|array  $url, array  $options = array()) : string

Create a `<button>` tag with a surrounding `<form>` that submits via POST as default.

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
  • method - Request method to use. Set to 'delete' or others to simulate HTTP/1.1 DELETE (or others) request. Defaults to 'post'.
  • form - Array with any option that FormHelper::create() can take
  • Other options is the same of button method.
  • confirm - Confirm message to show. Form execution will only continue if confirmed then.

Parameters

string $title

The button's caption. Not automatically HTML encoded

string|array $url

URL as string or array

array $options

Array of options and HTML attributes.

Returns

string —

A HTML button tag.

postLink()

postLink(string  $title, string|array|null  $url = null, array  $options = array()) : string

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.

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 - Confirm message to show. Form execution will only continue if confirmed then.
  • block - Set to true to append form to view block "postLink" or provide custom block name.
  • Other options are the same of HtmlHelper::link() method.
  • The option onclick will be replaced.

Parameters

string $title

The content to be wrapped by tags.

string|array|null $url

Cake-relative URL or array of URL parameters, or external URL (starts with http://)

array $options

Array of HTML attributes.

Returns

string —

An <a /> element.

submit()

submit(string|null  $caption = null, array  $options = array()) : string

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

  • type - Set to 'reset' for reset inputs. Defaults to 'submit'
  • templateVars - Additional template variables for the input element and its container.
  • Other attributes will be assigned to the input element.

Parameters

string|null $caption

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 $options

Array of options. See above.

Returns

string —

A HTML submit button

select()

select(string  $fieldName, array|\Traversable  $options = array(), array  $attributes = array()) : string

Returns a formatted SELECT element.

Attributes:

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

Using options

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'],
];

Parameters

string $fieldName

Name attribute of the SELECT

array|\Traversable $options

Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the SELECT element

array $attributes

The HTML attributes of the select element.

Returns

string —

Formatted SELECT element

multiCheckbox()

multiCheckbox(string  $fieldName, array|\Traversable  $options, array  $attributes = array()) : string

Creates a set of checkboxes out of options.

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.
  • label - Either false to disable label around the widget or an array of attributes for the label tag. selected will be added to any classes e.g. 'class' => 'myclass' where widget is checked

Can be used in place of a select box with the multiple attribute.

Parameters

string $fieldName

Name attribute of the SELECT

array|\Traversable $options

Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the checkboxes element.

array $attributes

The HTML attributes of the select element.

Returns

string —

Formatted SELECT element

day()

day(string|null  $fieldName = null, array  $options = array()) : string

Returns a SELECT element for days.

Options:

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

Parameters

string|null $fieldName

Prefix name for the SELECT element

array $options

Options & HTML attributes for the select element

Returns

string —

A generated day select box.

year()

year(string  $fieldName, array  $options = array()) : string

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'
  • 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.

Parameters

string $fieldName

Prefix name for the SELECT element

array $options

Options & attributes for the select elements.

Returns

string —

Completed year select input

month()

month(string  $fieldName, array  $options = array()) : string

Returns a SELECT element for months.

Options:

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

Parameters

string $fieldName

Prefix name for the SELECT element

array $options

Attributes for the select element

Returns

string —

A generated month select dropdown.

hour()

hour(string  $fieldName, array  $options = array()) : string

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.
  • value The selected value of the input.
  • format Set to 12 or 24 to use 12 or 24 hour formatting. Defaults to 24.

Parameters

string $fieldName

Prefix name for the SELECT element

array $options

List of HTML attributes

Returns

string —

Completed hour select input

minute()

minute(string  $fieldName, array  $options = array()) : string

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

Parameters

string $fieldName

Prefix name for the SELECT element

array $options

Array of options.

Returns

string —

Completed minute select input.

meridian()

meridian(string  $fieldName, array  $options = array()) : string

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.
  • value The selected value of the input.

Parameters

string $fieldName

Prefix name for the SELECT element

array $options

Array of options

Returns

string —

Completed meridian select input

dateTime()

dateTime(string  $fieldName, array  $options = array()) : string

Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.

Date Options:

  • 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 select
  • maxYear The maximum year to use in the year select
  • orderYear - Order of year values in select options. Possible values 'asc', 'desc'. Default 'desc'.

Time options:

  • 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 1
  • round - 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}}

Parameters

string $fieldName

Prefix name for the SELECT element

array $options

Array of Options

Returns

string —

Generated set of select boxes for the date and time formats chosen.

time()

time(string  $fieldName, array  $options = array()) : string

Generate time inputs.

Options:

See dateTime() for time options.

Parameters

string $fieldName

Prefix name for the SELECT element

array $options

Array of Options

Returns

string —

Generated set of select boxes for time formats chosen.

date()

date(string  $fieldName, array  $options = array()) : string

Generate date inputs.

Options:

See dateTime() for date options.

Parameters

string $fieldName

Prefix name for the SELECT element

array $options

Array of Options

Returns

string —

Generated set of select boxes for time formats chosen.

addContextProvider()

addContextProvider(string  $type, callable  $check) : void

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.

Parameters

string $type

The type of context. This key can be used to overwrite existing providers.

callable $check

A callable that returns an object when the form context is the correct type.

context()

context(\Cake\View\Form\ContextInterface|null  $context = null) : \Cake\View\Form\ContextInterface

Get the context instance for the current form set.

If there is no active form null will be returned.

Parameters

\Cake\View\Form\ContextInterface|null $context

Either the new context when setting, or null to get.

Returns

\Cake\View\Form\ContextInterface

The context for the form.

addWidget()

addWidget(string  $name, array|\Cake\View\Widget\WidgetInterface  $spec) : void

Add a new widget to FormHelper.

Allows you to add or replace widget instances with custom code.

Parameters

string $name

The name of the widget. e.g. 'text'.

array|\Cake\View\Widget\WidgetInterface $spec

Either a string class name or an object implementing the WidgetInterface.

widget()

widget(string  $name, array  $data = array()) : string

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.

Parameters

string $name

The name of the widget. e.g. 'text'.

array $data

The data to render.

Returns

string

resetTemplates()

resetTemplates() : void

Restores the default values built into FormHelper.

This method will not reset any templates set in custom widgets.

getValueSources()

getValueSources() : array

Gets the value sources.

Returns a list, but at least one item, of valid sources, such as: 'context', 'data' and 'query'.

Returns

array —

List of value sources.

setValueSources()

setValueSources(string|array  $sources) : $this

Sets the value sources.

Valid values are 'context', 'data' and 'query'. You need to supply one valid context or multiple, as a list of strings. Order sets priority.

Parameters

string|array $sources

A string or a list of strings identifying a source.

Returns

$this

getSourceValue()

getSourceValue(string  $fieldname, array|null  $options = array()) : string|null

Gets a single field value from the sources available.

Parameters

string $fieldname

The fieldname to fetch the value for.

array|null $options

The options containing default values.

Returns

string|null —

Field value derived from sources or defaults.

text()

text(mixed  $fieldName, array  $options = []) : string

Parameters

mixed $fieldName
array $options

Returns

string

number()

number(mixed  $fieldName, array  $options = []) : string

Parameters

mixed $fieldName
array $options

Returns

string

email()

email(mixed  $fieldName, array  $options = []) : string

Parameters

mixed $fieldName
array $options

Returns

string

password()

password(mixed  $fieldName, array  $options = []) : string

Parameters

mixed $fieldName
array $options

Returns

string

search()

search(mixed  $fieldName, array  $options = []) : string

Parameters

mixed $fieldName
array $options

Returns

string

_clearIds()

_clearIds() : void

Clear the stored ID suffixes.

_id()

_id(string  $name, string  $val) : string

Generate an ID attribute for an element.

Ensures that id's for a given set of fields are unique.

Parameters

string $name

The ID attribute name.

string $val

The ID attribute value.

Returns

string —

Generated id.

_domId()

_domId(string  $value) : string

Generate an ID suitable for use in an ID attribute.

Parameters

string $value

The value to convert into an ID.

Returns

string —

The generated id.

_buildFieldToken()

_buildFieldToken(string  $url, array  $fields, array  $unlockedFields = array()) : array

Generate the token data for the provided inputs.

Parameters

string $url

The URL the form is being submitted to.

array $fields

If set specifies the list of fields to use when generating the hash.

array $unlockedFields

The list of fields that are excluded from field validation.

Returns

array —

The token data.

_confirm()

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

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

Parameters

string $message

Message to be displayed

string $okCode

Code to be executed after user chose 'OK'

string $cancelCode

Code to be executed after user chose 'Cancel'

array $options

Array of options

Returns

string —

onclick JS code

_cleanConfirmMessage()

_cleanConfirmMessage(string  $message) : mixed

Returns a string read to be used in confirm()

Parameters

string $message

The message to clean

Returns

mixed

_configRead()

_configRead(string|null  $key) : mixed

Reads a config key.

Parameters

string|null $key

Key to read.

Returns

mixed

_configWrite()

_configWrite(string|array  $key, mixed  $value, boolean|string  $merge = false) : void

Writes a config key.

Parameters

string|array $key

Key to write to.

mixed $value

Value to write.

boolean|string $merge

True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.

Throws

\Cake\Core\Exception\Exception

if attempting to clobber existing config

_configDelete()

_configDelete(string  $key) : void

Deletes a single config key.

Parameters

string $key

Key to delete.

Throws

\Cake\Core\Exception\Exception

if attempting to clobber existing config

_formUrl()

_formUrl(\Cake\View\Form\ContextInterface  $context, array  $options) : string|array

Create the URL for a form based on the options.

Parameters

\Cake\View\Form\ContextInterface $context

The context object to use.

array $options

An array of options from create()

Returns

string|array —

The action attribute for the form.

_lastAction()

_lastAction(string|array  $url) : void

Correctly store the last created form action URL.

Parameters

string|array $url

The URL of the last form.

_csrfField()

_csrfField() : string

Return a CSRF input if the request data is present.

Used to secure forms in conjunction with CsrfComponent & SecurityComponent

Returns

string

_secure()

_secure(boolean  $lock, string|array  $field, mixed  $value = null) : void

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 $field

Reference to field to be secured. Can be dot separated string to indicate nesting or array of fieldname parts.

mixed $value

Field value, if value should not be tampered with.

_groupTemplate()

_groupTemplate(array  $options) : string

Generates an group template element

Parameters

array $options

The options for group template

Returns

string —

The generated group template

_inputContainerTemplate()

_inputContainerTemplate(array  $options) : string

Generates an input container template

Parameters

array $options

The options for input container template

Returns

string —

The generated input container template

_getInput()

_getInput(string  $fieldName, array  $options) : string

Generates an input element

Parameters

string $fieldName

the field name

array $options

The options for the input element

Returns

string —

The generated input element

_parseOptions()

_parseOptions(string  $fieldName, array  $options) : array

Generates input options array

Parameters

string $fieldName

The name of the field to parse options for.

array $options

Options list.

Returns

array —

Options

_inputType()

_inputType(string  $fieldName, array  $options) : string

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

Parameters

string $fieldName

the name of the field to guess a type for

array $options

the options passed to the input method

Returns

string

_optionsOptions()

_optionsOptions(string  $fieldName, array  $options) : array

Selects the variable containing the options for a select field if present, and sets the value to the 'options' key in the options array.

Parameters

string $fieldName

The name of the field to find options for.

array $options

Options list.

Returns

array

_magicOptions()

_magicOptions(string  $fieldName, array  $options, boolean  $allowOverride) : array

Magically set option type and corresponding options

Parameters

string $fieldName

The name of the field to generate options for.

array $options

Options list.

boolean $allowOverride

Whether or not it is allowed for this method to overwrite the 'type' key in options.

Returns

array

_getLabel()

_getLabel(string  $fieldName, array  $options) : boolean|string

Generate label for input

Parameters

string $fieldName

The name of the field to generate label for.

array $options

Options list.

Returns

boolean|string —

false or Generated label element

_extractOption()

_extractOption(string  $name, array  $options, mixed  $default = null) : mixed

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 $default

The default option value

Returns

mixed —

the contents of the option or default

_inputLabel()

_inputLabel(string  $fieldName, string  $label, array  $options) : string

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

The name of the field to generate label for.

string $label

Label text.

array $options

Options for the label element.

Returns

string —

Generated label element

_singleDatetime()

_singleDatetime(array  $options, string  $keep) : array

Helper method for the various single datetime component methods.

Parameters

array $options

The options array.

string $keep

The option to not disable.

Returns

array

_datetimeOptions()

_datetimeOptions(array  $options) : array

Helper method for converting from FormHelper options data to widget format.

Parameters

array $options

Options to convert.

Returns

array —

Converted options.

_initInputField()

_initInputField(string  $field, array  $options = array()) : array

Sets field defaults and adds field to form security input hash.

Will also add the 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 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.
  • id - mixed - If true it will be auto generated based on field name.

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.

Parameters

string $field

Name of the field to initialize options for.

array $options

Array of options to append options into.

Returns

array —

Array of options for the input.

_isDisabled()

_isDisabled(array  $options) : boolean

Determine if a field is disabled.

Parameters

array $options

The option set.

Returns

boolean —

Whether or not the field is disabled.

_secureFieldName()

_secureFieldName(string  $name) : array

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.

Parameters

string $name

The form inputs name attribute.

Returns

array —

Array of field name params like ['Model.field'] or ['Model', 'field'] for array fields or empty array if $name is empty.

_getContext()

_getContext(mixed  $data = array()) : \Cake\View\Form\ContextInterface

Find the matching context provider for the data.

If no type can be matched a NullContext will be returned.

Parameters

mixed $data

The data to get a context provider for.

Throws

\RuntimeException

when the context class does not implement the ContextInterface.

Returns

\Cake\View\Form\ContextInterface

Context provider.