Class FormHelper
Form helper library.
Automatic generation of HTML FORMs from given data.
Constants
-
string
SECURE_SKIP ¶'skip'
Constant used internally to skip the securing process, and neither add the field to the hash or to the unlocked fields.
Property Summary
-
$Html public @property
HtmlHelper
-
$Url public @property
UrlHelper
-
$_View protected
Cake\View\View
The View instance this helper is attached to
-
$_config protected
array
Runtime config
-
$_configInitialized protected
bool
Whether the config property has already been configured with defaults
-
$_context protected
Cake\View\Form\ContextInterface
Context for the current form.
-
$_contextProviders protected
array
Context provider methods.
-
$_datetimeOptions protected
array
Special options used for datetime inputs.
-
$_datetimeParts protected
array
The various pickers that make up a datetime picker.
-
$_defaultConfig protected
array
Default config for the helper.
-
$_defaultWidgets protected
array
Default widgets
-
$_helperMap protected
array
A helper lookup table used to lazy load helper objects.
-
$_idPrefix protected
string
Prefix for id attribute.
-
$_idSuffixes protected
array
A list of id suffixes used in the current rendering.
-
$_lastAction protected
string
The action attribute value of the last created form. Used to make form/request specific hashes for SecurityComponent.
-
$_registry protected
Cake\View\Widget\WidgetRegistry
Registry for input widgets.
-
$_templater protected
Cake\View\StringTemplate
StringTemplate instance.
-
$_unlockedFields protected
array
An array of field names that have been excluded from the Token hash used by SecurityComponent's validatePost method
-
$fields public
array
List of fields created, used with secure forms.
-
$fieldset public
array
Holds the fields ['field_name' => ['type' => 'string', 'length' => 100]], primaryKey and validates ['field_name']
-
$helpers public
array
Other helpers used by FormHelper
-
$plugin public
string
Plugin path
-
$request public
Cake\Network\Request
Request object
-
$requestType public
string
Defines the type of form being created. Set by FormHelper::create().
-
$tags public
array
Holds tag templates.
-
$theme public
string
The current theme name if any.
Method Summary
-
__call() public
Missing method handler - implements various simple input types. Is used to create inputs of various types. e.g.
$this->Form->text();
will create<input type="text" />
while$this->Form->range();
will create<input type="range" />
-
__construct() public
Construct the widgets and binds the default context providers
-
__debugInfo() public
Returns an array that can be used to describe the internal state of this object.
-
__get() public
Lazy loads helpers.
-
_addDefaultContextProviders() protected
Add the default suite of context providers provided by CakePHP.
-
_clearIds() protected
Clear the stored ID suffixes.
-
_configDelete() protected
Delete a single config key
-
_configRead() protected
Read a config variable
-
_configWrite() protected
Write a config variable
-
_confirm() protected
Returns a string to be used as onclick handler for confirm dialogs.
-
_csrfField() protected
Return a CSRF input if the request data is present. Used to secure forms in conjunction with CsrfComponent & SecurityComponent
-
_datetimeOptions() protected
Helper method for converting from FormHelper options data to widget format.
-
_domId() protected
Generate an ID suitable for use in an ID attribute.
-
_extractOption() protected
Extracts a single option from an options array.
-
_formUrl() protected
Create the URL for a form based on the options.
-
_getContext() protected
Find the matching context provider for the data.
-
_getInput() protected
Generates an input element
-
_getLabel() protected
Generate label for input
-
_groupTemplate() protected
Generates an group template element
-
_id() protected
Generate an ID attribute for an element.
-
_initInputField() protected
Sets field defaults and adds field to form security input hash. Will also add the error class if the field contains validation errors.
-
_inputContainerTemplate() protected
Generates an input container template
-
_inputLabel() protected
Generate a label for an input() call.
-
_inputType() protected
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
-
_isRequiredField() protected
Returns if a field is required to be filled based on validation properties from the validating object.
-
_lastAction() protected
Correctly store the last created form action URL.
-
_magicOptions() protected
Magically set option type and corresponding options
-
_optionsOptions() protected
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() protected
Generates input options array
-
_secure() protected
Determine which fields of a form should be used for hash. Populates $this->fields
-
_secureFieldName() protected
Get the field name for use with _secure().
-
_singleDatetime() protected
Helper method for the various single datetime component methods.
-
addClass() public
Adds the given class to the element options
-
addContextProvider() public
Add a new context type.
-
addWidget() public
Add a new widget to FormHelper.
-
allInputs() public
Generate a set of inputs for
$fields
. If $fields is empty the fields of current model will be used. -
button() public
Creates a
<button>
tag. -
checkbox() public
Creates a checkbox input widget.
-
config() public
Usage
-
configShallow() public
Merge provided config with existing config. Unlike
config()
which does a recursive merge for nested keys, this method does a simple merge. -
context() public
Get the context instance for the current form set.
-
create() public
Returns an HTML FORM element.
-
date() public
Generate date inputs.
-
dateTime() public
Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
-
day() public
Returns a SELECT element for days.
-
end() public
Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden input fields where appropriate.
-
error() public
Returns a formatted error message for given form field, '' if no errors.
-
fieldset() public
Wrap a set of inputs in a fieldset
-
file() public
Creates file input widget.
-
formatTemplate() public
Format a template string with $data
-
hidden() public
Creates a hidden input field.
-
hour() public
Returns a SELECT element for hours.
-
implementedEvents() public
Event listeners.
-
input() public
Generates a form input element complete with label and wrapper div
-
inputs() public
Generate a set of inputs for
$fields
wrapped in a fieldset element. -
isFieldError() public
Returns true if there is an error for the given field, otherwise false
-
label() public
Returns a formatted LABEL element for HTML forms.
-
meridian() public
Returns a SELECT element for AM or PM.
-
minute() public
Returns a SELECT element for minutes.
-
month() public
Returns a SELECT element for months.
-
multiCheckbox() public
Creates a set of checkboxes out of options.
-
postButton() public
Create a
<button>
tag with a surrounding<form>
that submits via POST. -
postLink() public
Creates an HTML link, but access the URL using the method you specify (defaults to POST). Requires javascript to be enabled in browser.
-
radio() public
Creates a set of radio widgets.
-
resetTemplates() public
Restores the default values built into FormHelper.
-
secure() public
Generates a hidden field with a security hash based on the fields used in the form.
-
select() public
Returns a formatted SELECT element.
-
submit() public
Creates a submit button element. This method will generate
<input />
elements that can be used to submit, and reset forms by using $options. image submits can be created by supplying an image path for $caption. -
templater() public
templater
-
templates() public
Get/set templates to use.
-
textarea() public
Creates a textarea widget.
-
time() public
Generate time inputs.
-
unlockField() public
Add to or get the list of fields that are currently unlocked. Unlocked fields are not included in the field hash used by SecurityComponent unlocking a field once its been added to the list of secured fields will remove it from the list of fields.
-
widget() public
Render a named widget.
-
widgetRegistry() public
Set the widget registry the helper will use.
-
year() public
Returns a SELECT element for years
Method Detail
__call() ¶ public
__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
Returns
string
Throws
Cake\Core\Exception\Exception
When there are no params for the method call.
__construct() ¶ public
__construct(Cake\View\View $View, array $config = [])
Construct the widgets and binds the default context providers
Parameters
-
Cake\View\View
$View The View this helper is being attached to.
-
array
$config optional Configuration settings for the helper.
__debugInfo() ¶ public
__debugInfo(): array
Returns an array that can be used to describe the internal state of this object.
Returns
array
__get() ¶ public
__get(string $name): Cake\View\Helper|void
Lazy loads helpers.
Parameters
-
string
$name Name of the property being accessed.
Returns
Cake\View\Helper|void
_addDefaultContextProviders() ¶ protected
_addDefaultContextProviders(): void
Add the default suite of context providers provided by CakePHP.
Returns
void
_configDelete() ¶ protected
_configDelete(string $key): void
Delete a single config key
Parameters
-
string
$key Key to delete.
Returns
void
Throws
Cake\Core\Exception\Exception
if attempting to clobber existing config
_configRead() ¶ protected
_configRead(string|null $key): mixed
Read a config variable
Parameters
-
string|null
$key Key to read.
Returns
mixed
_configWrite() ¶ protected
_configWrite(string|array $key, mixed $value, bool|string $merge = false): void
Write a config variable
Parameters
-
string|array
$key Key to write to.
-
mixed
$value Value to write.
-
bool|string
$merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
Returns
void
Throws
Cake\Core\Exception\Exception
if attempting to clobber existing config
_confirm() ¶ protected
_confirm(string $message, string $okCode, string $cancelCode = '', array $options = []): 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 optional Code to be executed after user chose 'Cancel'
-
array
$options optional Array of options
Returns
string
_csrfField() ¶ protected
_csrfField(): string
Return a CSRF input if the request data is present. Used to secure forms in conjunction with CsrfComponent & SecurityComponent
Returns
string
_datetimeOptions() ¶ protected
_datetimeOptions(array $options): array
Helper method for converting from FormHelper options data to widget format.
Parameters
-
array
$options Options to convert.
Returns
array
_domId() ¶ protected
_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
_extractOption() ¶ protected
_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 optional The default option value
Returns
mixed
_formUrl() ¶ protected
_formUrl(Cake\View\Form\ContextInterface $context, array $options): string
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
_getContext() ¶ protected
_getContext(mixed $data = []): mixed
Find the matching context provider for the data.
If no type can be matched a NullContext will be returned.
Parameters
-
mixed
$data optional The data to get a context provider for.
Returns
mixed
Throws
RuntimeException
when the context class does not implement the ContextInterface.
_getInput() ¶ protected
_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
_getLabel() ¶ protected
_getLabel(string $fieldName, array $options): bool|string
Generate label for input
Parameters
-
string
$fieldName The name of the field to generate label for.
-
array
$options Options list.
Returns
bool|string
_groupTemplate() ¶ protected
_groupTemplate(array $options): string
Generates an group template element
Parameters
-
array
$options The options for group template
Returns
string
_id() ¶ protected
_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
_initInputField() ¶ protected
_initInputField(string $field, array $options = []): 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 thedisabled
option, will also omit the field from being part of the hashed key.default
- mixed - The value to use if there is no value in the form's context.disabled
- mixed - Either a boolean indicating disabled state, or the string in a numerically indexed value.
This method will convert a numerically indexed 'disabled' into an associative array value. FormHelper's internals expect associative options.
The output of this function is a more complete set of input attributes that can be passed to a form widget to generate the actual input.
Parameters
-
string
$field Name of the field to initialize options for.
-
array
$options optional Array of options to append options into.
Returns
array
_inputContainerTemplate() ¶ protected
_inputContainerTemplate(array $options): string
Generates an input container template
Parameters
-
array
$options The options for input container template
Returns
string
_inputLabel() ¶ protected
_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
_inputType() ¶ protected
_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
_isRequiredField() ¶ protected
_isRequiredField(Cake\Validation\ValidationSet $validationRules): bool
Returns if a field is required to be filled based on validation properties from the validating object.
Parameters
-
Cake\Validation\ValidationSet
$validationRules Validation rules set.
Returns
bool
_lastAction() ¶ protected
_lastAction(string|array $url): void
Correctly store the last created form action URL.
Parameters
-
string|array
$url The URL of the last form.
Returns
void
_magicOptions() ¶ protected
_magicOptions(string $fieldName, array $options, bool $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.
-
bool
$allowOverride Whether or not it is allowed for this method to overwrite the 'type' key in options.
Returns
array
_optionsOptions() ¶ protected
_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
_parseOptions() ¶ protected
_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
_secure() ¶ protected
_secure(bool $lock, string|array $field, mixed $value = null): void
Determine which fields of a form should be used for hash. Populates $this->fields
Parameters
-
bool
$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 optional Field value, if value should not be tampered with.
Returns
void
_secureFieldName() ¶ protected
_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
_singleDatetime() ¶ protected
_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
addClass() ¶ public
addClass(array $options = [], string $class = null, string $key = 'class'): array
Adds the given class to the element options
Parameters
-
array
$options optional Array options/attributes to add a class to
-
string
$class optional The class name being added.
-
string
$key optional the key to use for class.
Returns
array
addContextProvider() ¶ public
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.
Returns
void
addWidget() ¶ public
addWidget(string $name, arrayCake\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'.
-
arrayCake\View\Widget\WidgetInterface
$spec Either a string class name or an object implementing the WidgetInterface.
Returns
void
allInputs() ¶ public
allInputs(array $fields = [], array $options = []): string
Generate a set of inputs for $fields
. If $fields is empty the fields of current model
will be used.
You can customize individual inputs through $fields
.
$this->Form->allInputs([
'name' => ['label' => 'custom label']
]);
You can exclude fields by specifying them as false:
$this->Form->allInputs(['title' => false]);
In the above example, no field would be generated for the title field.
Parameters
-
array
$fields optional 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 optional 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 enabledlegend
Set to false to disable the legend for the generated input set. Or supply a string to customize the legend text.
Returns
string
Links
button() ¶ public
button(string $title, array $options = []): 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.
Parameters
-
string
$title The button's caption. Not automatically HTML encoded
-
array
$options optional Array of options and HTML attributes.
Returns
string
Links
checkbox() ¶ public
checkbox(string $fieldName, array $options = []): string|array
Creates a checkbox input widget.
Options:
value
- the value of the checkboxchecked
- boolean indicate that this checkbox is checked.hiddenField
- boolean to indicate if you want the results of checkbox() to include a hidden input with a value of ''.disabled
- create a disabled input.default
- Set the default value for the checkbox. This allows you to start checkboxes as checked, without having to check the POST data. A matching POST data value, will overwrite the default value.
Parameters
-
string
$fieldName Name of a field, like this "modelname.fieldname"
-
array
$options optional Array of HTML attributes.
Returns
string|array
Links
config() ¶ public
config(string|array|null $key = null, mixed|null $value = null, bool $merge = true): mixed
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 optional The key to get/set, or a complete array of configs.
-
mixed|null
$value optional The value to set.
-
bool
$merge optional Whether to recursively merge or overwrite existing config, defaults to true.
Returns
mixed
Throws
Cake\Core\Exception\Exception
When trying to set a key that is invalid.
configShallow() ¶ public
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->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
$key The key to set, or a complete array of configs.
-
mixed|null
$value optional The value to set.
Returns
$this
context() ¶ public
context(Cake\View\Form\ContextInterface|null $context = null): nullCake\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 optional Either the new context when setting, or null to get.
Returns
nullCake\View\Form\ContextInterface
create() ¶ public
create(mixed $model = null, array $options = []): 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.action
The controller action the form submits to, (optional). Use this option if you don't need to change the controller from the current request's controller.url
The URL the form submits to. Can be a string or a URL array. If you use 'url' you should leave 'action' undefined.encoding
Set the accept-charset encoding for the form. Defaults toConfigure::read('App.encoding')
templates
The templates you want to use for this form. Any templates will be merged on top of the already loaded templates. This option can either be a filename in /config that contains the templates you want to load, or an array of templates to use.context
Additional options for the context class. For example the EntityContext accepts a 'table' option that allows you to set the specific Table class the form should be based on.idPrefix
Prefix for generated ID attributes.
Parameters
-
mixed
$model optional The context for which the form is being defined. Can be an ORM entity, ORM resultset, or an array of meta data. You can use false or null to make a model-less form.
-
array
$options optional An array of html attributes and options.
Returns
string
Links
date() ¶ public
date(string $fieldName, array $options = []): string
Generate date inputs.
Options:
See dateTime() for date options.
Parameters
-
string
$fieldName Prefix name for the SELECT element
-
array
$options optional Array of Options
Returns
string
See Also
dateTime() ¶ public
dateTime(string $fieldName, array $options = []): 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 providedtime()
will be used.monthNames
If false, 2 digit numbers will be used instead of text. If an array, the given array will be used.minYear
The lowest year to use in the year selectmaxYear
The maximum year to use in the year selectorderYear
- Order of year values in select options. Possible values 'asc', 'desc'. Default 'desc'.
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 providedtime()
will be used.timeFormat
The time format to use, either 12 or 24.interval
The interval for the minutes select. Defaults to 1round
- Set toup
ordown
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 optional Array of Options
Returns
string
Links
day() ¶ public
day(string $fieldName = null, array $options = []): 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
$fieldName optional Prefix name for the SELECT element
-
array
$options optional Options & HTML attributes for the select element
Returns
string
Links
end() ¶ public
end(array $secureAttributes = []): string
Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden input fields where appropriate.
Parameters
-
array
$secureAttributes optional Secure attributes which will be passed as HTML attributes into the hidden input elements generated for the Security Component.
Returns
string
Links
error() ¶ public
error(string $field, string|array $text = null, array $options = []): 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
$text optional Error message as string or array of messages. If an array, it should be a hash of key names => messages.
-
array
$options optional See above.
Returns
string
Links
fieldset() ¶ public
fieldset(string $fields = '', array $options = []): string
Wrap a set of inputs in a fieldset
Parameters
-
string
$fields optional the form inputs to wrap in a fieldset
-
array
$options optional 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 enabledlegend
Set to false to disable the legend for the generated input set. Or supply a string to customize the legend text.
Returns
string
file() ¶ public
file(string $fieldName, array $options = []): string
Creates file input widget.
Parameters
-
string
$fieldName Name of a field, in the form "modelname.fieldname"
-
array
$options optional Array of HTML attributes.
Returns
string
Links
formatTemplate() ¶ public
formatTemplate(string $name, array $data): string
Format a template string with $data
Parameters
-
string
$name The template name.
-
array
$data The data to insert.
Returns
string
hidden() ¶ public
hidden(string $fieldName, array $options = []): string
Creates a hidden input field.
Parameters
-
string
$fieldName Name of a field, in the form of "modelname.fieldname"
-
array
$options optional Array of HTML attributes.
Returns
string
Links
hour() ¶ public
hour(string $fieldName, array $options = []): 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 optional List of HTML attributes
Returns
string
Links
implementedEvents() ¶ public
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
input() ¶ public
input(string $fieldName, array $options = []): string
Generates a form input element complete with label and wrapper div
Options
See each field type method for more information. Any options that are part of
$attributes or $options for the different type methods can be included in $options
for input().
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 tofalse
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 defaultradioWrapper
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.
Parameters
-
string
$fieldName This should be "modelname.fieldname"
-
array
$options optional Each type of input takes different options.
Returns
string
Links
inputs() ¶ public
inputs(array $fields, array $options = []): string
Generate a set of inputs for $fields
wrapped in a fieldset element.
You can customize individual inputs through $fields
.
$this->Form->inputs([
'name' => ['label' => 'custom label'],
'email'
]);
Parameters
-
array
$fields An array of the fields to generate. This array allows you to set custom types, labels, or other options.
-
array
$options optional 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 enabledlegend
Set to false to disable the legend for the generated input set. Or supply a string to customize the legend text.
Returns
string
Links
isFieldError() ¶ public
isFieldError(string $field): bool
Returns true if there is an error for the given field, otherwise false
Parameters
-
string
$field This should be "modelname.fieldname"
Returns
bool
Links
label() ¶ public
label(string $fieldName, string $text = null, array $options = []): 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().
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
$text optional Text that will appear in the label field. If $text is left undefined the text will be inflected from the fieldName.
-
array
$options optional An array of HTML attributes.
Returns
string
Links
meridian() ¶ public
meridian(string $fieldName, array $options = []): 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 optional Array of options
Returns
string
Links
minute() ¶ public
minute(string $fieldName, array $options = []): 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 optional Array of options.
Returns
string
Links
month() ¶ public
month(string $fieldName, array $options = []): 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 optional Attributes for the select element
Returns
string
Links
multiCheckbox() ¶ public
multiCheckbox(string $fieldName, arrayTraversable $options, array $attributes = []): 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.
Can be used in place of a select box with the multiple attribute.
Parameters
-
string
$fieldName Name attribute of the SELECT
-
arrayTraversable
$options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the checkboxes element.
-
array
$attributes optional The HTML attributes of the select element.
Returns
string
See Also
postButton() ¶ public
postButton(string $title, string|array $url, array $options = []): string
Create a <button>
tag with a surrounding <form>
that submits via POST.
This method creates a <form>
element. So do not use this method in an already opened form.
Instead use FormHelper::submit() or FormHelper::button() to create buttons inside opened forms.
Options:
data
- Array with key/value to pass in input hidden- Other options is the same of button method.
Parameters
-
string
$title The button's caption. Not automatically HTML encoded
-
string|array
$url URL as string or array
-
array
$options optional Array of options and HTML attributes.
Returns
string
Links
postLink() ¶ public
postLink(string $title, string|array $url = null, array $options = []): 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. So do not use this method inside an
existing form. Instead you should add a submit button using FormHelper::submit()
Options:
data
- Array with key/value to pass in input hiddenmethod
- Request method to use. Set to 'delete' to simulate HTTP/1.1 DELETE request. Defaults to 'post'.confirm
- Confirm message to show.block
- Set to true to append form to view block "postLink" or provide custom block name.- 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
$url optional Cake-relative URL or array of URL parameters, or external URL (starts with http://)
-
array
$options optional Array of HTML attributes.
Returns
string
Links
radio() ¶ public
radio(string $fieldName, arrayTraversable $options = [], array $attributes = []): string
Creates a set of radio widgets.
Attributes:
value
- Indicates the value when this radio button is checked.label
- boolean to indicate whether or not labels for widgets should be displayed.hiddenField
- boolean to indicate if you want the results of radio() to include a hidden input with a value of ''. This is useful for creating radio sets that are non-continuous.disabled
- Set totrue
ordisabled
to disable all the radio buttons.empty
- Set totrue
to create an input with the value '' as the first option. Whentrue
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"
-
arrayTraversable
$options optional Radio button options array.
-
array
$attributes optional Array of attributes.
Returns
string
Links
resetTemplates() ¶ public
resetTemplates(): void
Restores the default values built into FormHelper.
This method will not reset any templates set in custom widgets.
Returns
void
secure() ¶ public
secure(array $fields = [], array $secureAttributes = []): void|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 optional If set specifies the list of fields to use when generating the hash, else $this->fields is being used.
-
array
$secureAttributes optional will be passed as HTML attributes into the hidden input elements generated for the Security Component.
Returns
void|string
select() ¶ public
select(string $fieldName, arrayTraversable $options = [], array $attributes = []): 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 = [
['name' => 'United states', 'value' => 'USA'],
['name' => 'USA', 'value' => 'USA'],
];
Parameters
-
string
$fieldName Name attribute of the SELECT
-
arrayTraversable
$options optional Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the SELECT element
-
array
$attributes optional The HTML attributes of the select element.
Returns
string
See Also
Links
submit() ¶ public
submit(string $caption = null, array $options = []): 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'- Other attributes will be assigned to the input element.
Parameters
-
string
$caption optional 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 optional Array of options. See above.
Returns
string
Links
templater() ¶ public
templater(): Cake\View\StringTemplate
templater
Returns
Cake\View\StringTemplate
templates() ¶ public
templates(string|null|array $templates = null): $this|string|array
Get/set templates to use.
Parameters
-
string|null|array
$templates optional null or string allow reading templates. An array allows templates to be added.
Returns
$this|string|array
textarea() ¶ public
textarea(string $fieldName, array $options = []): 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 optional Array of HTML attributes, and special options above.
Returns
string
Links
time() ¶ public
time(string $fieldName, array $options = []): string
Generate time inputs.
Options:
See dateTime() for time options.
Parameters
-
string
$fieldName Prefix name for the SELECT element
-
array
$options optional Array of Options
Returns
string
See Also
unlockField() ¶ public
unlockField(string|null $name = null): mixed
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 optional The dot separated name for the field.
Returns
mixed
Links
widget() ¶ public
widget(string $name, array $data = []): 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 optional The data to render.
Returns
string
widgetRegistry() ¶ public
widgetRegistry(Cake\View\Widget\WidgetRegistry $instance = null, array $widgets = []): Cake\View\Widget\WidgetRegistry
Set the widget registry the helper will use.
Parameters
-
Cake\View\Widget\WidgetRegistry
$instance optional The registry instance to set.
-
array
$widgets optional An array of widgets
Returns
Cake\View\Widget\WidgetRegistry
year() ¶ public
year(string $fieldName, array $options = []): 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 optional Options & attributes for the select elements.
Returns
string
Links
Property Detail
$_configInitialized ¶ protected
Whether the config property has already been configured with defaults
Type
bool
$_lastAction ¶ protected
The action attribute value of the last created form. Used to make form/request specific hashes for SecurityComponent.
Type
string
$_unlockedFields ¶ protected
An array of field names that have been excluded from the Token hash used by SecurityComponent's validatePost method
Type
array
$fieldset ¶ public
Holds the fields ['field_name' => ['type' => 'string', 'length' => 100]], primaryKey and validates ['field_name']
Type
array
$requestType ¶ public
Defines the type of form being created. Set by FormHelper::create().
Type
string