Fr3nch13/CakePHP Utilities

FormHelper extends Helper
in package
uses IdGeneratorTrait, StringTemplateTrait

Form helper library.

Automatic generation of HTML FORMs from given data.

Tags
link
https://book.cakephp.org/4/en/views/helpers/form.html

Table of Contents

Constants

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

Properties

$Html  : HtmlHelper
$requestType  : string|null
Defines the type of form being created. Set by FormHelper::create().
$Url  : UrlHelper
$_config  : array<string, mixed>
Runtime config
$_configInitialized  : bool
Whether the config property has already been configured with defaults
$_context  : ContextInterface|null
Context for the current form.
$_contextFactory  : ContextFactory|null
Context factory.
$_defaultConfig  : array<string, mixed>
Default config for the helper.
$_defaultWidgets  : array<string, array<string|int, string>>
Default widgets
$_groupedInputTypes  : array<string|int, string>
Grouped input types.
$_helperMap  : array<string, array<string|int, mixed>>
A helper lookup table used to lazy load helper objects.
$_idPrefix  : string|null
Prefix for id attribute.
$_idSuffixes  : array<string|int, string>
A list of id suffixes used in the current rendering.
$_lastAction  : string
The action attribute value of the last created form.
$_locator  : WidgetLocator
Locator for input widgets.
$_templater  : StringTemplate|null
StringTemplate instance.
$_valueSources  : array<string|int, string>
The default sources.
$_View  : View
The View instance this helper is attached to
$formProtector  : FormProtector|null
Form protector
$helpers  : array<string|int, mixed>
Other helpers used by FormHelper
$supportedValueSources  : array<string|int, string>
The supported sources that can be used to populate input values.

Methods

__call()  : 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"/>`
__construct()  : mixed
Construct the widgets and binds the default context providers
__debugInfo()  : array<string, mixed>
Returns an array that can be used to describe the internal state of this object.
__get()  : Helper|null|void
Lazy loads helpers.
addClass()  : array<string, mixed>
Adds the given class to the element options
addContextProvider()  : void
Add a new context type.
addWidget()  : void
Add a new widget to FormHelper.
allControls()  : string
Generate a set of controls for `$fields`. If $fields is empty the fields of current model will be used.
button()  : string
Creates a `<button>` tag.
checkbox()  : array<string|int, string>|string
Creates a checkbox input widget.
configShallow()  : $this
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
context()  : ContextInterface
Get the context instance for the current form set.
contextFactory()  : ContextFactory
Set the context factory the helper will use.
control()  : string
Generates a form control element complete with label and wrapper div.
controls()  : string
Generate a set of controls for `$fields` wrapped in a fieldset element.
create()  : string
Returns an HTML form element.
date()  : string
Generate an input tag with type "date".
dateTime()  : string
Generate an input tag with type "datetime-local".
email()  : string
end()  : string
Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden input fields where appropriate.
error()  : string
Returns a formatted error message for given form field, '' if no errors.
fieldset()  : string
Wrap a set of inputs in a fieldset
file()  : string
Creates file input widget.
formatTemplate()  : string
Formats a template string with $data
getConfig()  : mixed
Returns the config.
getConfigOrFail()  : mixed
Returns the config for this specific key.
getFormProtector()  : FormProtector
Get form protector instance.
getSourceValue()  : mixed
Gets a single field value from the sources available.
getTemplates()  : array<string|int, mixed>|string
Gets templates to use or a specific template.
getValueSources()  : array<string|int, string>
Gets the value sources.
getView()  : View
Get the view instance this helper is bound to.
getWidgetLocator()  : WidgetLocator
Get the widget locator currently used by the helper.
hidden()  : string
Creates a hidden input field.
implementedEvents()  : array<string, mixed>
Event listeners.
initialize()  : void
Constructor hook method.
isFieldError()  : bool
Returns true if there is an error for the given field, otherwise false
label()  : string
Returns a formatted LABEL element for HTML forms.
month()  : string
Generate an input tag with type "month".
multiCheckbox()  : string
Creates a set of checkboxes out of options.
number()  : string
password()  : string
postButton()  : string
Create a `<button>` tag with a surrounding `<form>` that submits via POST as default.
postLink()  : string
Creates an HTML link, but access the URL using the method you specify (defaults to POST). Requires javascript to be enabled in browser.
radio()  : string
Creates a set of radio widgets.
resetTemplates()  : void
Restores the default values built into FormHelper.
search()  : string
secure()  : string
Generates a hidden field with a security hash based on the fields used in the form.
select()  : string
Returns a formatted SELECT element.
setConfig()  : $this
Sets the config.
setTemplates()  : $this
Sets templates to use.
setValueSources()  : $this
Sets the value sources.
setWidgetLocator()  : $this
Set the widget locator the helper will use.
submit()  : 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.
templater()  : StringTemplate
Returns the templater instance.
text()  : string
textarea()  : string
Creates a textarea widget.
time()  : string
Generate an input tag with type "time".
unlockField()  : $this
Add to the list of fields that are currently unlocked.
widget()  : string
Render a named widget.
year()  : string
Returns a SELECT element for years
_clearIds()  : void
Clear the stored ID suffixes.
_configDelete()  : void
Deletes a single config key.
_configRead()  : mixed
Reads a config key.
_configWrite()  : void
Writes a config key.
_confirm()  : string
Returns a string to be used as onclick handler for confirm dialogs.
_csrfField()  : string
Return a CSRF input if the request data is present.
_domId()  : string
Generate an ID suitable for use in an ID attribute.
_extractOption()  : mixed
Extracts a single option from an options array.
_formUrl()  : array<string|int, mixed>|string
Create the URL for a form based on the options.
_getContext()  : ContextInterface
Find the matching context provider for the data.
_getInput()  : array<string|int, mixed>|string
Generates an input element
_getLabel()  : string|false
Generate label for input
_groupTemplate()  : string
Generates an group template element
_id()  : string
Generate an ID attribute for an element.
_idSuffix()  : string
Generate an ID suffix.
_initInputField()  : array<string, mixed>
Sets field defaults and adds field to form security input hash.
_inputContainerTemplate()  : string
Generates an input container template
_inputLabel()  : string
Generate a label for an input() call.
_inputType()  : 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
_isDisabled()  : bool
Determine if a field is disabled.
_lastAction()  : void
Correctly store the last created form action URL.
_magicOptions()  : array<string, mixed>
Magically set option type and corresponding options
_optionsOptions()  : array<string, mixed>
Selects the variable containing the options for a select field if present, and sets the value to the 'options' key in the options array.
_parseOptions()  : array<string, mixed>
Generates input options array
createFormProtector()  : FormProtector
Create FormProtector instance.
setRequiredAndCustomValidity()  : array<string, mixed>
Set required attribute and custom validity JS.
validateValueSources()  : void
Validate value sources.

Constants

SECURE_SKIP

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

public string SECURE_SKIP = 'skip'

Properties

$requestType

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

public string|null $requestType

$_configInitialized

Whether the config property has already been configured with defaults

protected bool $_configInitialized = false

$_defaultConfig

Default config for the helper.

protected array<string, mixed> $_defaultConfig = [ 'idPrefix' => null, 'errorClass' => 'form-error', 'typeMap' => ['string' => 'text', 'text' => 'textarea', 'uuid' => 'string', 'datetime' => 'datetime', 'datetimefractional' => 'datetime', 'timestamp' => 'datetime', 'timestampfractional' => 'datetime', 'timestamptimezone' => 'datetime', 'date' => 'date', 'time' => 'time', 'year' => 'year', 'boolean' => 'checkbox', 'float' => 'number', 'integer' => 'number', 'tinyinteger' => 'number', 'smallinteger' => 'number', 'decimal' => 'number', 'binary' => 'file'], 'templates' => [ // Used for button elements in button(). 'button' => '<button{{attrs}}>{{text}}</button>', // Used for checkboxes in checkbox() and multiCheckbox(). 'checkbox' => '<input type="checkbox" name="{{name}}" value="{{value}}"{{attrs}}>', // Input group wrapper for checkboxes created via control(). 'checkboxFormGroup' => '{{label}}', // Wrapper container for checkboxes. 'checkboxWrapper' => '<div class="checkbox">{{label}}</div>', // Error message wrapper elements. 'error' => '<div class="error-message" id="{{id}}">{{content}}</div>', // Container for error items. 'errorList' => '<ul>{{content}}</ul>', // Error item wrapper. 'errorItem' => '<li>{{text}}</li>', // File input used by file(). 'file' => '<input type="file" name="{{name}}"{{attrs}}>', // Fieldset element used by allControls(). 'fieldset' => '<fieldset{{attrs}}>{{content}}</fieldset>', // Open tag used by create(). 'formStart' => '<form{{attrs}}>', // Close tag used by end(). 'formEnd' => '</form>', // General grouping container for control(). Defines input/label ordering. 'formGroup' => '{{label}}{{input}}', // Wrapper content used to hide other content. 'hiddenBlock' => '<div style="display:none;">{{content}}</div>', // Generic input element. 'input' => '<input type="{{type}}" name="{{name}}"{{attrs}}/>', // Submit input element. 'inputSubmit' => '<input type="{{type}}"{{attrs}}/>', // Container element used by control(). 'inputContainer' => '<div class="input {{type}}{{required}}">{{content}}</div>', // Container element used by control() when a field has an error. 'inputContainerError' => '<div class="input {{type}}{{required}} error">{{content}}{{error}}</div>', // Label element when inputs are not nested inside the label. 'label' => '<label{{attrs}}>{{text}}</label>', // Label element used for radio and multi-checkbox inputs. 'nestingLabel' => '{{hidden}}<label{{attrs}}>{{input}}{{text}}</label>', // Legends created by allControls() 'legend' => '<legend>{{text}}</legend>', // Multi-Checkbox input set title element. 'multicheckboxTitle' => '<legend>{{text}}</legend>', // Multi-Checkbox wrapping container. 'multicheckboxWrapper' => '<fieldset{{attrs}}>{{content}}</fieldset>', // Option element used in select pickers. 'option' => '<option value="{{value}}"{{attrs}}>{{text}}</option>', // Option group element used in select pickers. 'optgroup' => '<optgroup label="{{label}}"{{attrs}}>{{content}}</optgroup>', // Select element, 'select' => '<select name="{{name}}"{{attrs}}>{{content}}</select>', // Multi-select element, 'selectMultiple' => '<select name="{{name}}[]" multiple="multiple"{{attrs}}>{{content}}</select>', // Radio input element, 'radio' => '<input type="radio" name="{{name}}" value="{{value}}"{{attrs}}>', // Wrapping container for radio input/label, 'radioWrapper' => '{{label}}', // Textarea input element, 'textarea' => '<textarea name="{{name}}"{{attrs}}>{{value}}</textarea>', // Container for submit buttons. 'submitContainer' => '<div class="submit">{{content}}</div>', // Confirm javascript template for postLink() 'confirmJs' => '{{confirm}}', // selected class 'selectedClass' => 'selected', ], // set HTML5 validation message to custom required/empty messages 'autoSetCustomValidity' => true, ]

$_defaultWidgets

Default widgets

protected array<string, array<string|int, string>> $_defaultWidgets = ['button' => ['Button'], 'checkbox' => ['Checkbox'], 'file' => ['File'], 'label' => ['Label'], 'nestingLabel' => ['NestingLabel'], 'multicheckbox' => ['MultiCheckbox', 'nestingLabel'], 'radio' => ['Radio', 'nestingLabel'], 'select' => ['SelectBox'], 'textarea' => ['Textarea'], 'datetime' => ['DateTime', 'select'], 'year' => ['Year', 'select'], '_default' => ['Basic']]

$_groupedInputTypes

Grouped input types.

protected array<string|int, string> $_groupedInputTypes = ['radio', 'multicheckbox']

$_helperMap

A helper lookup table used to lazy load helper objects.

protected array<string, array<string|int, mixed>> $_helperMap = []

$_idSuffixes

A list of id suffixes used in the current rendering.

protected array<string|int, string> $_idSuffixes = []

$_lastAction

The action attribute value of the last created form.

protected string $_lastAction = ''

Used to make form/request specific hashes for form tampering protection.

$_View

The View instance this helper is attached to

protected View $_View

$formProtector

Form protector

protected FormProtector|null $formProtector

$helpers

Other helpers used by FormHelper

protected array<string|int, mixed> $helpers = ['Url', 'Html']

$supportedValueSources

The supported sources that can be used to populate input values.

protected array<string|int, string> $supportedValueSources = ['context', 'data', 'query']

context - Corresponds to ContextInterface instances. data - Corresponds to request data (POST/PUT). query - Corresponds to request's query string.

Methods

__call()

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"/>`

public __call(string $method, array<string|int, mixed> $params) : string

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
$method : string

Method name / input type to make.

$params : array<string|int, mixed>

Parameters for the method call

Tags
throws
CakeException

When there are no params for the method call.

Return values
string

Formatted input method.

__construct()

Construct the widgets and binds the default context providers

public __construct(View $view[, array<string, mixed> $config = [] ]) : mixed
Parameters
$view : View

The View this helper is being attached to.

$config : array<string, mixed> = []

Configuration settings for the helper.

__debugInfo()

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

public __debugInfo() : array<string, mixed>
Return values
array<string, mixed>

__get()

Lazy loads helpers.

public __get(string $name) : Helper|null|void
Parameters
$name : string

Name of the property being accessed.

Return values
Helper|null|void

Helper instance if helper with provided name exists

addClass()

Adds the given class to the element options

public addClass(array<string, mixed> $options, string $class[, string $key = 'class' ]) : array<string, mixed>
Parameters
$options : array<string, mixed>

Array options/attributes to add a class to

$class : string

The class name being added.

$key : string = 'class'

the key to use for class. Defaults to 'class'.

Return values
array<string, mixed>

Array of options with $key set.

addContextProvider()

Add a new context type.

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

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
$type : string

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

$check : callable

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

addWidget()

Add a new widget to FormHelper.

public addWidget(string $name, WidgetInterface|array<string|int, mixed> $spec) : void

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

Parameters
$name : string

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

$spec : WidgetInterface|array<string|int, mixed>

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

allControls()

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

public allControls([array<string|int, mixed> $fields = [] ][, array<string, mixed> $options = [] ]) : string

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
$fields : array<string|int, mixed> = []

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

$options : array<string, mixed> = []

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.
Tags
link
https://book.cakephp.org/4/en/views/helpers/form.html#generating-entire-forms
Return values
string

Completed form controls.

button()

Creates a `<button>` tag.

public button(string $title[, array<string, mixed> $options = [] ]) : string

Options:

  • type - Value for "type" attribute of button. Defaults to "submit".
  • escapeTitle - HTML entity encode the title of the button. Defaults to true.
  • escape - HTML entity encode the attributes of button tag. Defaults to true.
  • confirm - Confirm message to show. Form execution will only continue if confirmed then.
Parameters
$title : string

The button's caption. Not automatically HTML encoded

$options : array<string, mixed> = []

Array of options and HTML attributes.

Tags
link
https://book.cakephp.org/4/en/views/helpers/form.html#creating-button-elements
Return values
string

A HTML button tag.

checkbox()

Creates a checkbox input widget.

public checkbox(string $fieldName[, array<string, mixed> $options = [] ]) : array<string|int, string>|string

Options:

  • value - the value of the checkbox
  • checked - boolean indicate that this checkbox is checked.
  • hiddenField - boolean|string. Set to false to disable a hidden input from being generated. Passing a string will define the hidden input value.
  • 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
$fieldName : string

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

$options : array<string, mixed> = []

Array of HTML attributes.

Tags
link
https://book.cakephp.org/4/en/views/helpers/form.html#creating-checkboxes
Return values
array<string|int, string>|string

An HTML text input element.

configShallow()

Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.

public configShallow(array<string, mixed>|string $key[, mixed|null $value = null ]) : $this

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
$key : array<string, mixed>|string

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

$value : mixed|null = null

The value to set.

Return values
$this

contextFactory()

Set the context factory the helper will use.

public contextFactory([ContextFactory|null $instance = null ][, array<string|int, mixed> $contexts = [] ]) : ContextFactory
Parameters
$instance : ContextFactory|null = null

The context factory instance to set.

$contexts : array<string|int, mixed> = []

An array of context providers.

Return values
ContextFactory

control()

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

public control(string $fieldName[, array<string, mixed> $options = [] ]) : string

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 control(). 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
$fieldName : string

This should be "modelname.fieldname"

$options : array<string, mixed> = []

Each type of input takes different options.

Tags
link
https://book.cakephp.org/4/en/views/helpers/form.html#creating-form-controls
psalm-suppress

InvalidReturnType

psalm-suppress

InvalidReturnStatement

Return values
string

Completed form widget.

controls()

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

public controls(array<string|int, mixed> $fields[, array<string, mixed> $options = [] ]) : string

You can customize individual controls through $fields.

$this->Form->controls([
  'name' => ['label' => 'custom label'],
  'email'
]);
Parameters
$fields : array<string|int, mixed>

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

$options : array<string, mixed> = []

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.
Tags
link
https://book.cakephp.org/4/en/views/helpers/form.html#generating-entire-forms
Return values
string

Completed form inputs.

create()

Returns an HTML form element.

public create([mixed $context = null ][, array<string, mixed> $options = [] ]) : string

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.
  • url The URL the form submits to. Can be a string or a URL array.
  • 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
$context : mixed = null

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 null to make a context-less form.

$options : array<string, mixed> = []

An array of html attributes and options.

Tags
link
https://book.cakephp.org/4/en/views/helpers/form.html#Cake\View\Helper\FormHelper::create
Return values
string

An formatted opening FORM tag.

date()

Generate an input tag with type "date".

public date(string $fieldName[, array<string, mixed> $options = [] ]) : string

Options:

See dateTime() options.

Parameters
$fieldName : string

The field name.

$options : array<string, mixed> = []

Array of options or HTML attributes.

Return values
string

dateTime()

Generate an input tag with type "datetime-local".

public dateTime(string $fieldName[, array<string, mixed> $options = [] ]) : string

Options:

  • value | default The default value to be used by the input. If set to true current datetime will be used.
Parameters
$fieldName : string

The field name.

$options : array<string, mixed> = []

Array of options or HTML attributes.

Return values
string

email()

public email([string $fieldName = ][, array<string|int, mixed> $options = [] ]) : string

Creates input of type email.

Parameters
$fieldName : string =
$options : array<string|int, mixed> = []
Return values
string

end()

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

public end([array<string, mixed> $secureAttributes = [] ]) : string

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

Parameters
$secureAttributes : array<string, mixed> = []

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

Tags
link
https://book.cakephp.org/4/en/views/helpers/form.html#closing-the-form
Return values
string

A closing FORM tag.

error()

Returns a formatted error message for given form field, '' if no errors.

public error(string $field[, array<string|int, mixed>|string|null $text = null ][, array<string, mixed> $options = [] ]) : string

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 to html escape the contents of the error.
Parameters
$field : string

A field name, like "modelname.fieldname"

$text : array<string|int, mixed>|string|null = null

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

$options : array<string, mixed> = []

See above.

Tags
link
https://book.cakephp.org/4/en/views/helpers/form.html#displaying-and-checking-errors
Return values
string

Formatted errors or ''.

fieldset()

Wrap a set of inputs in a fieldset

public fieldset([string $fields = '' ][, array<string, mixed> $options = [] ]) : string
Parameters
$fields : string = ''

the form inputs to wrap in a fieldset

$options : array<string, mixed> = []

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.
Return values
string

Completed form inputs.

formatTemplate()

Formats a template string with $data

public formatTemplate(string $name, array<string, mixed> $data) : string
Parameters
$name : string

The template name.

$data : array<string, mixed>

The data to insert.

Return values
string

getConfig()

Returns the config.

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

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
$key : string|null = null

The key to get or null for the whole config.

$default : mixed = null

The return value when the key does not exist.

Return values
mixed

Configuration data at the named key or null if the key does not exist.

getConfigOrFail()

Returns the config for this specific key.

public getConfigOrFail(string $key) : mixed

The config value for this key must exist, it can never be null.

Parameters
$key : string

The key to get.

Tags
throws
InvalidArgumentException
Return values
mixed

Configuration data at the named key

getFormProtector()

Get form protector instance.

public getFormProtector() : FormProtector
Tags
throws
CakeException
Return values
FormProtector

getSourceValue()

Gets a single field value from the sources available.

public getSourceValue(string $fieldname[, array<string, mixed> $options = [] ]) : mixed
Parameters
$fieldname : string

The fieldname to fetch the value for.

$options : array<string, mixed> = []

The options containing default values.

Return values
mixed

Field value derived from sources or defaults.

getTemplates()

Gets templates to use or a specific template.

public getTemplates([string|null $template = null ]) : array<string|int, mixed>|string
Parameters
$template : string|null = null

String for reading a specific template, null for all.

Return values
array<string|int, mixed>|string

getValueSources()

Gets the value sources.

public getValueSources() : array<string|int, string>

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

Return values
array<string|int, string>

List of value sources.

getView()

Get the view instance this helper is bound to.

public getView() : View
Return values
View

The bound view instance.

getWidgetLocator()

Get the widget locator currently used by the helper.

public getWidgetLocator() : WidgetLocator
Tags
since
3.6.0
Return values
WidgetLocator

Current locator instance

implementedEvents()

Event listeners.

public implementedEvents() : array<string, mixed>
Return values
array<string, mixed>

initialize()

Constructor hook method.

public initialize(array<string, mixed> $config) : void

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

Parameters
$config : array<string, mixed>

The configuration settings provided to this helper.

label()

Returns a formatted LABEL element for HTML forms.

public label(string $fieldName[, string|null $text = null ][, array<string, mixed> $options = [] ]) : string

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
$fieldName : string

This should be "modelname.fieldname"

$text : string|null = null

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

$options : array<string, mixed> = []

An array of HTML attributes.

Tags
link
https://book.cakephp.org/4/en/views/helpers/form.html#creating-labels
Return values
string

The formatted LABEL element

month()

Generate an input tag with type "month".

public month(string $fieldName[, array<string, mixed> $options = [] ]) : string

Options:

See dateTime() options.

Parameters
$fieldName : string

The field name.

$options : array<string, mixed> = []

Array of options or HTML attributes.

Return values
string

multiCheckbox()

Creates a set of checkboxes out of options.

public multiCheckbox(string $fieldName, iterable<string|int, mixed> $options[, array<string, mixed> $attributes = [] ]) : string

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
$fieldName : string

Name attribute of the SELECT

$options : iterable<string|int, mixed>

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

$attributes : array<string, mixed> = []

The HTML attributes of the select element.

Tags
see
FormHelper::select()

for supported option formats.

Return values
string

Formatted SELECT element

number()

public number([string $fieldName = ][, array<string|int, mixed> $options = [] ]) : string

Creates input of type number.

Parameters
$fieldName : string =
$options : array<string|int, mixed> = []
Return values
string

password()

public password([string $fieldName = ][, array<string|int, mixed> $options = [] ]) : string

Creates input of type password.

Parameters
$fieldName : string =
$options : array<string|int, mixed> = []
Return values
string

postButton()

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

public postButton(string $title, array<string|int, mixed>|string $url[, array<string, mixed> $options = [] ]) : string

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
$title : string

The button's caption. Not automatically HTML encoded

$url : array<string|int, mixed>|string

URL as string or array

$options : array<string, mixed> = []

Array of options and HTML attributes.

Tags
link
https://book.cakephp.org/4/en/views/helpers/form.html#creating-standalone-buttons-and-post-links
Return values
string

A HTML button tag.

Creates an HTML link, but access the URL using the method you specify (defaults to POST). Requires javascript to be enabled in browser.

public postLink(string $title[, array<string|int, mixed>|string|null $url = null ][, array<string, mixed> $options = [] ]) : string

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
$title : string

The content to be wrapped by tags.

$url : array<string|int, mixed>|string|null = null

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

$options : array<string, mixed> = []

Array of HTML attributes.

Tags
link
https://book.cakephp.org/4/en/views/helpers/form.html#creating-standalone-buttons-and-post-links
Return values
string

An <a /> element.

radio()

Creates a set of radio widgets.

public radio(string $fieldName[, iterable<string|int, mixed> $options = [] ][, array<string, mixed> $attributes = [] ]) : string

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|string. Set to false to not include a hidden input with a value of ''. Can also be a string to set the value of the hidden input. 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
$fieldName : string

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

$options : iterable<string|int, mixed> = []

Radio button options array.

$attributes : array<string, mixed> = []

Array of attributes.

Tags
link
https://book.cakephp.org/4/en/views/helpers/form.html#creating-radio-buttons
Return values
string

Completed radio widget set.

resetTemplates()

Restores the default values built into FormHelper.

public resetTemplates() : void

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

public search([string $fieldName = ][, array<string|int, mixed> $options = [] ]) : string

Creates input of type search.

Parameters
$fieldName : string =
$options : array<string|int, mixed> = []
Return values
string

secure()

Generates a hidden field with a security hash based on the fields used in the form.

public secure([array<string|int, mixed> $fields = [] ][, array<string, mixed> $secureAttributes = [] ]) : string

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
$fields : array<string|int, mixed> = []

If set specifies the list of fields to be added to FormProtector for generating the hash.

$secureAttributes : array<string, mixed> = []

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

Return values
string

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

select()

Returns a formatted SELECT element.

public select(string $fieldName[, iterable<string|int, mixed> $options = [] ][, array<string, mixed> $attributes = [] ]) : string

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
$fieldName : string

Name attribute of the SELECT

$options : iterable<string|int, mixed> = []

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

$attributes : array<string, mixed> = []

The HTML attributes of the select element.

Tags
see
FormHelper::multiCheckbox()

for creating multiple checkboxes.

link
https://book.cakephp.org/4/en/views/helpers/form.html#creating-select-pickers
Return values
string

Formatted SELECT element

setConfig()

Sets the config.

public setConfig(array<string, mixed>|string $key[, mixed|null $value = null ][, bool $merge = true ]) : $this

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
$key : array<string, mixed>|string

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

$value : mixed|null = null

The value to set.

$merge : bool = true

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

Tags
throws
CakeException

When trying to set a key that is invalid.

Return values
$this

setTemplates()

Sets templates to use.

public setTemplates(array<string|int, string> $templates) : $this
Parameters
$templates : array<string|int, string>

Templates to be added.

Return values
$this

setValueSources()

Sets the value sources.

public setValueSources(array<string|int, string>|string $sources) : $this

You need to supply one or more valid sources, as a list of strings. Order sets priority.

Parameters
$sources : array<string|int, string>|string

A string or a list of strings identifying a source.

Tags
see
FormHelper::$supportedValueSources

for valid values.

throws
InvalidArgumentException

If sources list contains invalid value.

Return values
$this

setWidgetLocator()

Set the widget locator the helper will use.

public setWidgetLocator(WidgetLocator $instance) : $this
Parameters
$instance : WidgetLocator

The locator instance to set.

Tags
since
3.6.0
Return values
$this

submit()

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.

public submit([string|null $caption = null ][, array<string, mixed> $options = [] ]) : string

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
$caption : string|null = 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.

$options : array<string, mixed> = []

Array of options. See above.

Tags
link
https://book.cakephp.org/4/en/views/helpers/form.html#creating-buttons-and-submit-elements
Return values
string

A HTML submit button

text()

public text([string $fieldName = ][, array<string|int, mixed> $options = [] ]) : string

Creates input of type text.

Parameters
$fieldName : string =
$options : array<string|int, mixed> = []
Return values
string

textarea()

Creates a textarea widget.

public textarea(string $fieldName[, array<string, mixed> $options = [] ]) : string

Options:

  • escape - Whether the contents of the textarea should be escaped. Defaults to true.
Parameters
$fieldName : string

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

$options : array<string, mixed> = []

Array of HTML attributes, and special options above.

Tags
link
https://book.cakephp.org/4/en/views/helpers/form.html#creating-textareas
Return values
string

A generated HTML text input element

time()

Generate an input tag with type "time".

public time(string $fieldName[, array<string, mixed> $options = [] ]) : string

Options:

See dateTime() options.

Parameters
$fieldName : string

The field name.

$options : array<string, mixed> = []

Array of options or HTML attributes.

Return values
string

unlockField()

Add to the list of fields that are currently unlocked.

public unlockField(string $name) : $this

Unlocked fields are not included in the form protection field hash.

Parameters
$name : string

The dot separated name for the field.

Return values
$this

widget()

Render a named widget.

public widget(string $name[, array<string|int, mixed> $data = [] ]) : string

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
$name : string

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

$data : array<string|int, mixed> = []

The data to render.

Return values
string

year()

Returns a SELECT element for years

public year(string $fieldName[, array<string, mixed> $options = [] ]) : string

Attributes:

  • empty - If true, the empty select option is shown. If a string, that string is displayed as the empty element.
  • order - Ordering of year values in select options. Possible values 'asc', 'desc'. Default 'desc'
  • value The selected value of the input.
  • max The max year to appear in the select element.
  • min The min year to appear in the select element.
Parameters
$fieldName : string

The field name.

$options : array<string, mixed> = []

Options & attributes for the select elements.

Tags
link
https://book.cakephp.org/4/en/views/helpers/form.html#creating-year-inputs
Return values
string

Completed year select input

_configDelete()

Deletes a single config key.

protected _configDelete(string $key) : void
Parameters
$key : string

Key to delete.

Tags
throws
CakeException

if attempting to clobber existing config

_configRead()

Reads a config key.

protected _configRead(string|null $key) : mixed
Parameters
$key : string|null

Key to read.

_configWrite()

Writes a config key.

protected _configWrite(array<string, mixed>|string $key, mixed $value[, string|bool $merge = false ]) : void
Parameters
$key : array<string, mixed>|string

Key to write to.

$value : mixed

Value to write.

$merge : string|bool = false

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

Tags
throws
CakeException

if attempting to clobber existing config

_confirm()

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

protected _confirm(string $okCode, string $cancelCode) : string
Parameters
$okCode : string

Code to be executed after user chose 'OK'

$cancelCode : string

Code to be executed after user chose 'Cancel'

Return values
string

"onclick" JS code

_csrfField()

Return a CSRF input if the request data is present.

protected _csrfField() : string

Used to secure forms in conjunction with CsrfMiddleware.

Return values
string

_domId()

Generate an ID suitable for use in an ID attribute.

protected _domId(string $value) : string
Parameters
$value : string

The value to convert into an ID.

Return values
string

The generated id.

_extractOption()

Extracts a single option from an options array.

protected _extractOption(string $name, array<string, mixed> $options[, mixed $default = null ]) : mixed
Parameters
$name : string

The name of the option to pull out.

$options : array<string, mixed>

The array of options you want to extract.

$default : mixed = null

The default option value

Return values
mixed

the contents of the option or default

_formUrl()

Create the URL for a form based on the options.

protected _formUrl(ContextInterface $context, array<string, mixed> $options) : array<string|int, mixed>|string
Parameters
$context : ContextInterface

The context object to use.

$options : array<string, mixed>

An array of options from create()

Return values
array<string|int, mixed>|string

The action attribute for the form.

_getContext()

Find the matching context provider for the data.

protected _getContext([mixed $data = [] ]) : ContextInterface

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

Parameters
$data : mixed = []

The data to get a context provider for.

Tags
throws
RuntimeException

when the context class does not implement the ContextInterface.

Return values
ContextInterface

Context provider.

_getInput()

Generates an input element

protected _getInput(string $fieldName, array<string, mixed> $options) : array<string|int, mixed>|string
Parameters
$fieldName : string

the field name

$options : array<string, mixed>

The options for the input element

Return values
array<string|int, mixed>|string

The generated input element string or array if checkbox() is called with option 'hiddenField' set to '_split'.

_getLabel()

Generate label for input

protected _getLabel(string $fieldName, array<string, mixed> $options) : string|false
Parameters
$fieldName : string

The name of the field to generate label for.

$options : array<string, mixed>

Options list.

Return values
string|false

Generated label element or false.

_groupTemplate()

Generates an group template element

protected _groupTemplate(array<string, mixed> $options) : string
Parameters
$options : array<string, mixed>

The options for group template

Return values
string

The generated group template

_id()

Generate an ID attribute for an element.

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

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

Parameters
$name : string

The ID attribute name.

$val : string

The ID attribute value.

Return values
string

Generated id.

_idSuffix()

Generate an ID suffix.

protected _idSuffix(string $val) : string

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

Parameters
$val : string

The ID attribute value.

Return values
string

Generated id suffix.

_initInputField()

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

protected _initInputField(string $field[, array<string, mixed>|array<string|int, string> $options = [] ]) : array<string, mixed>

Will also add the error class if the field contains validation errors.

Options

  • secure - boolean whether 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
$field : string

Name of the field to initialize options for.

$options : array<string, mixed>|array<string|int, string> = []

Array of options to append options into.

Return values
array<string, mixed>

Array of options for the input.

_inputContainerTemplate()

Generates an input container template

protected _inputContainerTemplate(array<string, mixed> $options) : string
Parameters
$options : array<string, mixed>

The options for input container template

Return values
string

The generated input container template

_inputLabel()

Generate a label for an input() call.

protected _inputLabel(string $fieldName[, array<string, mixed>|string|null $label = null ][, array<string, mixed> $options = [] ]) : string

$options can contain a hash of id overrides. These overrides will be used instead of the generated values if present.

Parameters
$fieldName : string

The name of the field to generate label for.

$label : array<string, mixed>|string|null = null

Label text or array with label attributes.

$options : array<string, mixed> = []

Options for the label element.

Return values
string

Generated label element

_inputType()

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

protected _inputType(string $fieldName, array<string, mixed> $options) : string
Parameters
$fieldName : string

the name of the field to guess a type for

$options : array<string, mixed>

the options passed to the input method

Return values
string

_isDisabled()

Determine if a field is disabled.

protected _isDisabled(array<string, mixed> $options) : bool
Parameters
$options : array<string, mixed>

The option set.

Return values
bool

Whether the field is disabled.

_lastAction()

Correctly store the last created form action URL.

protected _lastAction([array<string|int, mixed>|string|null $url = null ]) : void
Parameters
$url : array<string|int, mixed>|string|null = null

The URL of the last form.

_magicOptions()

Magically set option type and corresponding options

protected _magicOptions(string $fieldName, array<string, mixed> $options, bool $allowOverride) : array<string, mixed>
Parameters
$fieldName : string

The name of the field to generate options for.

$options : array<string, mixed>

Options list.

$allowOverride : bool

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

Return values
array<string, mixed>

_optionsOptions()

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

protected _optionsOptions(string $fieldName, array<string, mixed> $options) : array<string, mixed>
Parameters
$fieldName : string

The name of the field to find options for.

$options : array<string, mixed>

Options list.

Return values
array<string, mixed>

_parseOptions()

Generates input options array

protected _parseOptions(string $fieldName, array<string, mixed> $options) : array<string, mixed>
Parameters
$fieldName : string

The name of the field to parse options for.

$options : array<string, mixed>

Options list.

Return values
array<string, mixed>

Options

createFormProtector()

Create FormProtector instance.

protected createFormProtector(array<string, mixed> $formTokenData) : FormProtector
Parameters
$formTokenData : array<string, mixed>

Token data.

Return values
FormProtector

setRequiredAndCustomValidity()

Set required attribute and custom validity JS.

protected setRequiredAndCustomValidity(string $fieldName, array<string, mixed> $options) : array<string, mixed>
Parameters
$fieldName : string

The name of the field to generate options for.

$options : array<string, mixed>

Options list.

Return values
array<string, mixed>

Modified options list.

validateValueSources()

Validate value sources.

protected validateValueSources(array<string|int, string> $sources) : void
Parameters
$sources : array<string|int, string>

A list of strings identifying a source.

Tags
throws
InvalidArgumentException

If sources list contains invalid value.


        
On this page

Search results