diff --git a/en/views/helpers/form.rst b/en/views/helpers/form.rst index 8ca594fae2..406ce14adf 100644 --- a/en/views/helpers/form.rst +++ b/en/views/helpers/form.rst @@ -16,39 +16,53 @@ Starting a Form .. php:method:: create(mixed $context = null, array $options = []) +* ``$model`` - The context for which the form is being defined. Can be an ORM + entity, ORM resultset, array of metadata or ``false/null`` (to make a + model-less form). +* ``$options`` - An array of options and/or HTML attributes. + The first method you'll need to use in order to take advantage of the FormHelper is ``create()``. This method outputs an opening form tag. All parameters are optional. If ``create()`` is called with no parameters supplied, it assumes you are building a form that submits to the current controller, via the current URL. The default method for form submission is POST. -If you were to call ``create()`` inside the view for UsersController::add(), you -would see something like the following output in the rendered view: +If you were to call ``create()`` inside the view for ``UsersController::add()``, +you would see something like the following output in the rendered view: .. code-block:: html
-The ``$context`` argument is used as the form's 'context'. There are several -built-in form contexts and you can add your own, which we'll cover in the next -section. The built-in providers map to the following values of ``$context``: +The ``$model`` argument is used as the form's 'context'. There are several +built-in form contexts and you can add your own, which we'll cover below, in +a following section. The built-in providers map to the following values of +``$model``: + +* An ``Entity`` instance or an iterator will map to + `EntityContext `_; + this context class allows FormHelper to work with results from the + built-in ORM. -* An ``Entity`` instance or, an iterator map to the ``EntityContext``, this - context allows FormHelper to work with results from the built-in ORM. -* An array containing the ``schema`` key, maps to ``ArrayContext`` which allows - you to create simple data structures to build forms against. -* ``null`` and ``false`` map to the ``NullContext``, this context class simply - satisifies the interface FormHelper requires. This context is useful if you - want to build a short form that doesn't require ORM persistence. +* An array containing the ``'schema'`` key, will map to + `ArrayContext `_ + which allows you to create simple data structures to build forms against. -All contexts classes also have access to the request data, making it simpler to +* ``null`` and ``false`` will map to + `NullContext `_; + this context class + simply satisfies the interface FormHelper requires. This context is useful if + you want to build a short form that doesn't require ORM persistence. + +All context classes also have access to the request data, making it simpler to build forms. Once a form has been created with a context, all controls you create will use the active context. In the case of an ORM backed form, FormHelper can access associated data, validation errors and schema metadata. You can close the active -context using the ``end()`` method, or by calling ``create()`` again. To create -a form for an entity, do the following:: +context using the ``end()`` method, or by calling ``create()`` again. + +To create a form for an entity, do the following:: // If you are on /articles/add // $article should be an empty Article entity. @@ -63,9 +77,11 @@ Output: This will POST the form data to the ``add()`` action of ArticlesController. However, you can also use the same logic to create an edit form. The FormHelper uses the ``Entity`` object to automatically detect whether to -create an add or edit form. If the provided entity is not 'new', the form will -be created as an edit form. For example, if we browse to -**http://example.org/articles/edit/5**, we could do the following:: +create an *add* or *edit* form. If the provided entity is not 'new', the form +will be created as an *edit* form. + +For example, if we browse to **http://example.org/articles/edit/5**, we could +do the following:: // src/Controller/ArticlesController.php: public function edit($id = null) @@ -91,12 +107,57 @@ Output: .. note:: - Since this is an edit form, a hidden input field is generated to + Since this is an *edit* form, a hidden ``input`` field is generated to override the default HTTP method. +Options for Form Creation +------------------------- + The ``$options`` array is where most of the form configuration happens. This special array can contain a number of different key-value pairs that affect the way the form tag is generated. +Valid values: + +* ``'type'`` - Allows you to choose the type of form to create. If no type is + provided then it will be autodetected based on the form context. + Valid values: + + * ``'get'`` - Will set the form method to HTTP GET. + * ``'file'`` - Will set the form method to POST and the ``'enctype'`` to + "multipart/form-data". + * ``'post'`` - Will set the method to POST. + * ``'put', 'delete', 'patch'`` - Will override the HTTP method with PUT, + DELETE or PATCH respectively, when the form is submitted. + +* ``'method'`` - Valid values are the same as above. Allows you to explicitly + override the form's method. + +* ``'url'`` - Specify the URL the form will submit to. Can be a string or a URL + array. + +* ``'encoding'`` - Sets the ``accept-charset`` encoding for the form. Defaults + to ``Configure::read('App.encoding')``. + +* ``'enctype'`` - Allows you to set the form encoding explicitly. + +* ``'templates'`` - The templates you want to use for this form. Any templates + provided will be merged on top of the already loaded templates. Can be either + a filename from ``/config`` or an array of templates to use. + +* ``'context'`` - Additional options for the form 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. + +* ``'templateVars'`` - Allows you to provide template variables for the + ``formStart`` template. + +.. tip:: + + Besides the above options you can provide, in the ``$options`` argument, + any valid HTML attributes that you want to pass to the created ``form`` + element. .. _form-values-from-query-string: @@ -153,10 +214,12 @@ Output: -Specifying 'file' changes the form submission method to 'post', and includes an -enctype of "multipart/form-data" on the form tag. This is to be used if there -are any file elements inside the form. The absence of the proper enctype -attribute will cause the file uploads not to function:: +Specifying a ``'file'`` value for ``type``, changes the form submission method +to 'post', and includes an ``enctype`` of "multipart/form-data" on the form tag. +This is to be used if there are any file elements inside the form. The absence +of the proper ``enctype`` attribute will cause the file uploads not to function. + +E.g. :: echo $this->Form->create($article, ['type' => 'file']); @@ -164,20 +227,23 @@ Output: .. code-block:: html - + -When using 'put', 'patch' or 'delete', your form will be functionally equivalent -to a 'post' form, but when submitted, the HTTP request method will be overridden -with 'PUT', 'PATCH' or 'DELETE', respectively. This allows CakePHP to emulate -proper REST support in web browsers. +When using ``'put'``, ``'patch'`` or ``'delete'`` as ``'type'`` values, your +form will be functionally equivalent to a 'post' form, but when submitted, the +HTTP request method will be overridden with 'PUT', 'PATCH' or 'DELETE', +respectively. +This allows CakePHP to emulate proper REST support in web browsers. Setting a URL for the Form -------------------------- -Using the ``url`` option allows you to point the form to a specific action in -your current controller or another controller in your application. For example, +Using the ``'url'`` option allows you to point the form to a specific action in +your current controller or another controller in your application. + +For example, if you'd like to point the form to the ``login()`` action of the current -controller, you would supply an $options array like the following:: +controller, you would supply an ``$options`` array, like the following:: echo $this->Form->create($article, ['url' => ['action' => 'login']]); @@ -201,7 +267,7 @@ Output: -or can point to an external domain:: +Or you can point to an external domain:: echo $this->Form->create(null, [ 'url' => 'http://www.google.com/search', @@ -229,7 +295,7 @@ rules that only apply when an account is being registered:: ]); The above will use the rules defined in the ``register`` validator, which are -defined by ``UsersTable::validationRegister()``, for the ``$user`` and all +defined by ``UsersTable::validationRegister()``, for ``$user`` and all related associations. If you are creating a form for associated entities, you can define validation rules for each association by using an array:: @@ -274,13 +340,39 @@ Creating Form Controls .. php:method:: control(string $fieldName, array $options = []) + +* ``$fieldName`` - A field name in the form ``'Modelname.fieldname'``. +* ``$options`` - An optional array that can include both + :ref:`control-specific-options`, and options of the other methods (which + ``control()`` employs internally to generate various HTML elements) as + well as any valid HTML attributes. + The ``control()`` method lets you to generate complete form controls. These -controls will include a wrapping div, label, control widget, and validation error if +controls will include a wrapping ``div``, ``label``, control widget, and validation error if necessary. By using the metadata in the form context, this method will choose an appropriate control type for each field. Internally ``control()`` uses the other methods of FormHelper. -The type of control created depends on the column datatype: +.. tip:: + + Plese note that while the fields generated by the ``control()`` method are + called generically "inputs" on this page, technically speaking, the + ``control()`` method can generate not only all of the HTML ``input`` type + elements, but also other HTML form elements (e.g. ``select``, + ``button``, ``textarea``). + +By default the ``control()`` method will employ the following widget templates:: + + 'inputContainer' => '
{{content}}
' + 'input' => '' + +In case of validation errors it will also use:: + + 'inputContainerError' => '
{{content}}{{error}}
' + +The type of control created (when we provide no additional options to specify the +generated element type) is inferred via model introspection and +depends on the column datatype: Column Type Resulting Form Field @@ -316,12 +408,20 @@ you need to:: echo $this->Form->control('published', ['type' => 'checkbox']); +.. tip:: + + As a small subtlety, generating specific elements via the ``control()`` + form method will always also generate the wrapping ``div``, by default. + Generating the same type of element via one of the specific form methods + (e.g. ``$this->Form->checkbox('published');``) in most cases won't generate + the wrapping ``div``. Depending on your needs you can use one or another. + .. _html5-required: -The wrapping div will have a ``required`` class name appended if the +The wrapping ``div`` will have a ``required`` class name appended if the validation rules for the model's field indicate that it is required and not -allowed to be empty. You can disable automatic required flagging using the -required option:: +allowed to be empty. You can disable automatic ``required`` flagging using the +``'required'`` option:: echo $this->Form->control('title', ['required' => false]); @@ -330,20 +430,21 @@ To skip browser validation triggering for the whole form you can set option :php:meth:`~Cake\\View\\Helper\\FormHelper::submit()` or set ``'novalidate' => true`` in options for :php:meth:`~Cake\\View\\Helper\\FormHelper::create()`. -For example, let's assume that your User model includes fields for a -username (varchar), password (varchar), approved (datetime) and -quote (text). You can use the control() method of the FormHelper to +For example, let's assume that your Users model includes fields for a +*username* (varchar), *password* (varchar), *approved* (datetime) and +*quote* (text). You can use the ``control()`` method of the FormHelper to create appropriate controls for all of these form fields:: echo $this->Form->create($user); - // Text - echo $this->Form->control('username'); - // Password - echo $this->Form->control('password'); - // Day, month, year, hour, minute, meridian - echo $this->Form->control('approved'); - // Textarea - echo $this->Form->control('quote'); + // The following generates a Text input + echo $this->Form->input('username'); + // The following generates a Password input + echo $this->Form->input('password'); + // Assuming 'approved' is a datetime or timestamp field the following + //generates: Day, Month, Year, Hour, Minute + echo $this->Form->input('approved'); + // The following generates a Textarea element + echo $this->Form->input('quote'); echo $this->Form->button('Add'); echo $this->Form->end(); @@ -356,12 +457,14 @@ A more extensive example showing some options for a date field:: 'maxYear' => date('Y') - 18, ]); -Besides the specific options for ``control()`` found below, you can specify -any option for the control type & any HTML attribute (for instance ``onfocus``). +Besides the specific :ref:`control-specific-options`, +you also can specify any option accepted by corresponding specific method +for the chosen (or inferred by Cake) +control type and any HTML attribute (for instance ``onfocus``). -If you want to create a select field while using a belongsTo - or -hasOne - Relation, you can add the following to your Users-controller -(assuming your User belongsTo Group):: +If you want to create a ``select`` form field while using a *belongsTo* (or +*hasOne*) relation, you can add the following to your UsersController +(assuming your User *belongsTo* Group):: $this->set('groups', $this->Users->Groups->find('list')); @@ -369,8 +472,8 @@ Afterwards, add the following to your view template:: echo $this->Form->control('group_id', ['options' => $groups]); -To make a select box for a belongsToMany Groups association you can add the -following to your UsersController:: +To make a ``select`` box for a *belongsToMany* Groups association you can +add the following to your UsersController:: $this->set('groups', $this->Users->Groups->find('list')); @@ -378,9 +481,11 @@ Afterwards, add the following to your view template:: echo $this->Form->control('groups._ids', ['options' => $groups]); -If your model name consists of two or more words, e.g., -"UserGroup", when passing the data using set() you should name your -data in a pluralised and camelCased format as follows:: +If your model name consists of two or more words (e.g. +"UserGroups"), when passing the data using ``set()`` you should name your +data in a pluralised and +`lower camelCased `_ +format as follows:: $this->set('userGroups', $this->UserGroups->find('list')); @@ -394,7 +499,7 @@ Field Naming Conventions When creating control widgets you should name your fields after the matching attributes in the form's entity. For example, if you created a form for an -``$article``, you would create fields named after the properities. E.g +``$article`` entity, you would create fields named after the properties. E.g. ``title``, ``body`` and ``published``. You can create controls for associated models, or arbitrary models by passing in @@ -413,105 +518,150 @@ You may notice additional fields named ``year``, ``month``, ``day``, ``hour``, ``minute``, or ``meridian`` being added. These fields will be automatically converted into ``DateTime`` objects when entities are marshalled. +.. _control-specific-options: -Options -------- +Options for Control +------------------- -``FormHelper::control()`` supports a large number of options. In addition to its -own options ``control()`` accepts options for the generated control types, as well as -HTML attributes. The following will cover the options specific to +``FormHelper::control()`` supports a large number of options via its ``$options`` +argument. In addition to its own options, ``control()`` accepts options for the +inferred/chosen generated control types (e.g. for ``checkbox`` or ``textarea``), +as well as HTML attributes. This subsection will cover the options specific to ``FormHelper::control()``. -* ``$options['type']`` You can force the type of an control, overriding model - introspection, by specifying a type. In addition to the field types found in - the :ref:`automagic-form-elements`, you can also create 'file', 'password', - and any type supported by HTML5:: +* ``$options['type']`` - A string that specifies the widget type + to be generated. In addition to the field types found in the + :ref:`automagic-form-elements`, you can also create ``'file'``, + ``'password'``, and any other type supported by HTML5. By specifying a + ``'type'`` you will force the type of the generated control, overriding model + introspection. Defaults to ``null``. - echo $this->Form->control('field', ['type' => 'file']); - echo $this->Form->control('email', ['type' => 'email']); + E.g. :: + + echo $this->Form->control('field', ['type' => 'file']); + echo $this->Form->control('email', ['type' => 'email']); Output: .. code-block:: html -
- - -
- +
+ + +
+ -* ``$options['label']`` Set this key to the string you would like to be - displayed within the label that usually accompanies the control:: +* ``$options['label']`` - Either a string caption or an array of + :ref:`options for the label`. You can set this key to the + string you would like to be displayed within the label that usually + accompanies the ``input`` HTML element. Defaults to ``null``. - echo $this->Form->control('name', [ - 'label' => 'The User Alias' - ]); + E.g. :: + + echo $this->Form->control('name', [ + 'label' => 'The User Alias' + ]); Output: .. code-block:: html -
- - -
+
+ + +
- Alternatively, set this key to ``false`` to disable the output of the - label:: + Alternatively, set this key to ``false`` to disable the generation of the + ``label`` element. - echo $this->Form->control('name', ['label' => false]); + E.g. :: + + echo $this->Form->control('name', ['label' => false]); Output: .. code-block:: html -
- -
+
+ +
Set this to an array to provide additional options for the - ``label`` element. If you do this, you can use a ``text`` key in - the array to customize the label text:: + ``label`` element. If you do this, you can use a ``'text'`` key in + the array to customize the label text. - echo $this->Form->control('name', [ - 'label' => [ - 'class' => 'thingy', - 'text' => 'The User Alias' - ] - ]); + E.g. :: + + echo $this->Form->control('name', [ + 'label' => [ + 'class' => 'thingy', + 'text' => 'The User Alias' + ] + ]); Output: .. code-block:: html -
- - -
+
+ + +
+ +* ``$options['options']`` - You can provide in here an array containing + the elements to be generated for widgets such as ``radio`` or ``select``, + which require an array of items as an argument (see + :ref:`create-radio-button` and :ref:`create-select-picker` for more details). + Defaults to ``null``. -* ``$options['error']`` Using this key allows you to override the default model - error messages and can be used, for example, to set i18n messages. +* ``$options['error']`` - Using this key allows you to override the default + model error messages and can be used, for example, to set i18n messages. To + disable the error message output & field classes set the ``'error'`` key to + ``false``. Defaults to ``null``. - To disable error message output & field classes set the error key to ``false``:: + E.g. :: - echo $this->Form->control('name', ['error' => false]); + echo $this->Form->control('name', ['error' => false]); To override the model error messages use an array with - the keys matching the original validation error messages:: + the keys matching the original validation error messages. - $this->Form->control('name', [ - 'error' => ['Not long enough' => __('This is not long enough')] - ]); + E.g. :: + + $this->Form->control('name', [ + 'error' => ['Not long enough' => __('This is not long enough')] + ]); As seen above you can set the error message for each validation rule you have in your models. In addition you can provide i18n messages for your forms. -Generating Specific Types of Inputs -=================================== +* ``$options['nestedInput']`` - Used with checkboxes and radio buttons. + Controls whether the input element is generated + inside or outside the ``label`` element. When ``control()`` generates a + checkbox or a radio button, you can set this to ``false`` to force the + generation of the HTML ``input`` element outside of the ``label`` element. + + On the other hand you can set this to ``true`` for any control type to force the + generated input element inside the label. If you change this for radio buttons + then you need to also modify the default + :ref:`radioWrapper` template. Depending on the generated + control type it defaults to ``true`` or ``false``. + +* ``$options['templates']`` - The templates you want to use for this input. Any + specified templates will be merged on top of the already loaded templates. + This option can be either a filename in ``/config`` that contains the + templates you want to load, or an array of templates to use. + +* ``$options['labelOptions']`` - Set this to ``false`` to disable labels around + nestedWidgets or set it to an array of attributes to be provided to the + ``label`` tag. + +Generating Specific Types of Controls +===================================== In addition to the generic ``control()`` method, ``FormHelper`` has specific methods for generating a number of different types of controls. These can be used @@ -520,52 +670,55 @@ to generate just the control widget itself, and combined with other methods like :php:meth:`~Cake\\View\\Helper\\FormHelper::error()` to generate fully custom form layouts. -.. _general-input-options: +.. _general-control-options: -Common Options --------------- +Common Options For Specific Controls +------------------------------------ -Many of the various control element methods support a common set of options. All -of these options are also supported by ``control()``. To reduce repetition the -common options shared by all control methods are as follows: +Many of the various control element methods support a common set of options which, +depending on the form method used, must be provided inside the ``$options`` or +in the ``$attributes`` array argument. All of these options are also supported +by the ``control()`` method. +To reduce repetition, the common options shared by all control methods are +as follows: -* ``$options['id']`` Set this key to force the value of the DOM id for the control. - This will override the idPrefix that may be set. +* ``'id'`` - Set this key to force the value of the DOM id for the control. + This will override the ``'idPrefix'`` that may be set. -* ``$options['default']`` Used to set a default value for the control field. The +* ``'default'`` - Used to set a default value for the control field. The value is used if the data passed to the form does not contain a value for the field (or if no data is passed at all). An explicit default value will override any default values defined in the schema. Example usage:: - echo $this->Form->text('ingredient', ['default' => 'Sugar']); + echo $this->Form->text('ingredient', ['default' => 'Sugar']); - Example with select field (Size "Medium" will be selected as + Example with ``select`` field (size "Medium" will be selected as default):: - $sizes = ['s' => 'Small', 'm' => 'Medium', 'l' => 'Large']; - echo $this->Form->select('size', $sizes, ['default' => 'm']); + $sizes = ['s' => 'Small', 'm' => 'Medium', 'l' => 'Large']; + echo $this->Form->select('size', $sizes, ['default' => 'm']); .. note:: - You cannot use ``default`` to check a checkbox - instead you might - set the value in ``$this->request->getData()`` in your controller, - or set the control option ``checked`` to ``true``. + You cannot use ``default`` to check a checkbox - instead you might + set the value in ``$this->request->data`` in your controller, + or set the control option ``'checked'`` to ``true``. - Beware of using ``false`` to assign a default value. A ``false`` value is - used to disable/exclude options of an control field, so ``'default' => false`` - would not set any value at all. Instead use ``'default' => 0``. + Beware of using ``false`` to assign a default value. A ``false`` value is + used to disable/exclude options of a control field, so ``'default' => false`` + would not set any value at all. Instead use ``'default' => 0``. -* ``$options['value']`` Used to set a specific value for the control field. This +* ``'value'`` - Used to set a specific value for the control field. This will override any value that may else be injected from the context, such as Form, Entity or ``request->getData()`` etc. .. note:: - If you want to set a field to not render its value fetched from - context or valuesSource you will need to set ``$options['value']`` to ``''`` - (instead of setting it to ``null``). + If you want to set a field to not render its value fetched from + context or valuesSource you will need to set ``'value'`` to ``''`` + (instead of setting it to ``null``). In addition to the above options, you can mixin any HTML attribute you wish to use. Any non-special option name will be treated as an HTML attribute, and @@ -576,278 +729,321 @@ applied to the generated HTML control element. in your database schema. You can disable this behavior by setting the ``schemaDefault`` option to ``false``. -Options for Select, Checkbox and Radio Inputs ---------------------------------------------- +Creating Input Elements +======================= -* ``$options['value']`` may also be used in combination with a select-type control - (i.e. For types select, date, time, datetime). Set 'value' to the value of the - item you wish to be selected by default when the control is rendered:: +The rest of the methods available in the FormHelper are for +creating specific form elements. Many of these methods also make +use of a special ``$options`` or ``$attributes`` parameter. In this case, +however, this parameter is used primarily to specify HTML tag attributes +(such as the value or DOM id of an element in the form). - echo $this->Form->time('close_time', [ - 'value' => '13:30:00' - ]); +Creating Text Inputs +-------------------- - .. note:: +.. php:method:: text(string $name, array $options) - The value key for date and datetime controls may also be a UNIX - timestamp, or a DateTime object. +* ``$name`` - A field name in the form ``'Modelname.fieldname'``. +* ``$options`` - An optional array including any of the + :ref:`general-control-options` as well as any valid HTML attributes. - For select control where you set the ``multiple`` attribute to true, - you can use an array of the values you want to select by default:: +Creates a simple ``input`` HTML element of ``text`` type. - echo $this->Form->select('rooms', [ - 'multiple' => true, - // options with values 1 and 3 will be selected as default - 'default' => [1, 3] - ]); +E.g. :: -* ``$options['empty']`` If set to ``true``, forces the control to remain empty. + echo $this->Form->text('username', ['class' => 'users']); - When passed to a select list, this creates a blank option with an - empty value in your drop down list. If you want to have a empty - value with text displayed instead of just a blank option, pass in a - string to empty:: +Will output: - echo $this->Form->select( - 'field', - [1, 2, 3, 4, 5], - ['empty' => '(choose one)'] - ); +.. code-block:: html - Output: + - .. code-block:: html +Creating Password Inputs +------------------------ - +.. php:method:: password(string $fieldName, array $options) - Options can also supplied as key-value pairs. +* ``$fieldName`` - A field name in the form ``'Modelname.fieldname'``. +* ``$options`` - An optional array including any of the + :ref:`general-control-options` as well as any valid HTML attributes. -* ``$options['hiddenField']`` For certain control types (checkboxes, radios) a - hidden input is created so that the key in ``$this->request->getData()`` will exist - even without a value specified: +Creates a simple ``input`` element of ``password`` type. - .. code-block:: html +E.g. :: - - + echo $this->Form->password('password'); - This can be disabled by setting the ``$options['hiddenField'] = false``:: +Will output: - echo $this->Form->checkbox('published', ['hiddenField' => false]); +.. code-block:: html - Which outputs: + - .. code-block:: html +Creating Hidden Inputs +---------------------- - +.. php:method:: hidden(string $fieldName, array $options) - If you want to create multiple blocks of controls on a form that are - all grouped together, you should use this parameter on all controls - except the first. If the hidden input is on the page in multiple - places, only the last group of input's values will be saved +* ``$fieldName`` - A field name in the form ``'Modelname.fieldname'``. +* ``$options`` - An optional array including any of the + :ref:`general-control-options` as well as any valid HTML attributes. - In this example, only the tertiary colors would be passed, and the - primary colors would be overridden: +Creates a hidden form input. - .. code-block:: html +E.g. :: -

Primary Colors

- - + echo $this->Form->hidden('id'); - +Will output: - +.. code-block:: html -

Tertiary Colors

- - - - + - Disabling the ``'hiddenField'`` on the second input group would - prevent this behavior. +Creating Textareas +------------------ - You can set a different hidden field value other than 0 such as 'N':: +.. php:method:: textarea(string $fieldName, array $options) - echo $this->Form->checkbox('published', [ - 'value' => 'Y', - 'hiddenField' => 'N', - ]); +* ``$fieldName`` - A field name in the form ``'Modelname.fieldname'``. +* ``$options`` - An optional array including any of the + :ref:`general-control-options`, of the specific textarea options (see below) + as well as any valid HTML attributes. -Datetime Options ----------------- +Creates a textarea control field. The default widget template used is:: -* ``$options['timeFormat']`` Used to specify the format of the select controls for - a time-related set of controls. Valid values include ``12``, ``24``, and ``null``. + 'textarea' => '' -* ``$options['minYear'], $options['maxYear']`` Used in combination with a - date/datetime control. Defines the lower and/or upper end of values shown in the - years select field. +For example:: -* ``$options['orderYear']`` Used in combination with a date/datetime control. - Defines the order in which the year values will be set. Valid values include - 'asc', 'desc'. The default value is 'desc'. + echo $this->Form->textarea('notes'); -* ``$options['interval']`` This option specifies the number of minutes between - each option in the minutes select box:: +Will output: - echo $this->Form->control('time', [ - 'type' => 'time', - 'interval' => 15 - ]); +.. code-block:: html - Would create 4 options in the minute select. One for each 15 - minutes. + -* ``$options['round']`` Can be set to `up` or `down` to force rounding in either - direction. Defaults to null which rounds half up according to `interval`. +If the form is being edited (i.e. the array ``$this->request->data`` +contains the information previously saved for the ``User`` entity), the value +corresponding to ``notes`` field will automatically be added to the HTML +generated. -* ``$options['monthNames']`` If ``false``, 2 digit numbers will be used instead - of text. If it is given an array like ``['01' => 'Jan', '02' => 'Feb', ...]`` - then the given array will be used. +Example: -Creating Input Elements -======================= +.. code-block:: html -Creating Text Inputs --------------------- + -.. php:method:: text(string $name, array $options) +**Options for Textarea** -The rest of the methods available in the FormHelper are for -creating specific form elements. Many of these methods also make -use of a special $options parameter. In this case, however, -$options is used primarily to specify HTML tag attributes (such as -the value or DOM id of an element in the form):: +In addition to the :ref:`general-control-options`, ``textarea()`` supports a +couple of specific options: - echo $this->Form->text('username', ['class' => 'users']); +* ``'escape'`` - Determines whether or not the contents of the textarea should + be escaped. Defaults to ``true``. -Will output: + E.g. :: -.. code-block:: html + echo $this->Form->textarea('notes', ['escape' => false]); + // OR.... + echo $this->Form->control('notes', ['type' => 'textarea', 'escape' => false]); - +* ``'rows', 'cols'`` - You can use these two keys to set the HTML attributes + which specify the number of rows and columns for the ``textarea`` field. -Creating Password Inputs ------------------------- + E.g. :: -.. php:method:: password(string $fieldName, array $options) + echo $this->Form->textarea('comment', ['rows' => '5', 'cols' => '5']); -Creates a password field. :: + Output: - echo $this->Form->password('password'); + .. code-block:: html -Will output: + -.. code-block:: html +Creating Select, Checkbox and Radio Controls +-------------------------------------------- - +These controls share some commonalities and a few options and thus, they are +all grouped in this subsection for easier reference. -Creating Hidden Inputs ----------------------- +.. _checkbox-radio-select-options: -.. php:method:: hidden(string $fieldName, array $options) +Options for Select, Checkbox and Radio Controls +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Creates a hidden form input. Example:: +You can find below the options which are shared by ``select()``, +``checkbox()`` and ``radio()`` (the options particular only to one of the +methods are described in each method's own section.) - echo $this->Form->hidden('id'); +* ``'value'`` - Sets or selects the value of the affected element(s): -Will output: + * For checkboxes, it sets the HTML ``'value'`` attribute assigned + to the ``input`` element to whatever you provide as value. -.. code-block:: html + * For radio buttons or select pickers it defines which element will be + selected when the form is rendered (in this case ``'value'`` must be + assigned a valid, existent element value). May also be used in + combination with any select-type control, + such as ``date()``, ``time()``, ``datetime()``:: - + echo $this->Form->time('close_time', [ + 'value' => '13:30:00' + ]); -Creating Textareas ------------------- + .. note:: -.. php:method:: textarea(string $fieldName, array $options) + The ``'value'`` key for ``date()`` and ``dateTime()`` controls may also have + as value a UNIX timestamp, or a DateTime object. -Creates a textarea control field. :: + For a ``select`` control where you set the ``'multiple'`` attribute to + ``true``, you can provide an array with the values you want to select + by default:: - echo $this->Form->textarea('notes'); + // HTML ' - +May also use:: -The ``select`` control type allows for a special ``$option`` -attribute called ``'escape'`` which accepts a bool and determines -whether to HTML entity encode the contents of the select options. -Defaults to ``true``:: + 'optgroup' => '{{content}}' + 'selectMultiple' => '' - $options = ['M' => 'Male', 'F' => 'Female']; - echo $this->Form->select('gender', $options, ['escape' => false]); +**Attributes for Select Pickers** -* ``$attributes['options']`` This key allows you to manually specify options for - a select control, or for a radio group. Unless the 'type' is specified as - 'radio', the FormHelper will assume that the target output is a select control:: +* ``'multiple'`` - If set to ``true`` allows multiple selections in the select + picker. If set to ``'checkbox'``, multiple checkboxes will be created instead. + Defaults to ``null``. - echo $this->Form->select('field', [1,2,3,4,5]); +* ``'escape'`` - Boolean. If ``true`` the contents of the ``option`` elements + inside the select picker will be HTML entity encoded. Defaults to ``true``. - Output: +* ``'val'`` - Allows preselecting a value in the select picker. - .. code-block:: html +* ``'disabled'`` - Controls the ``disabled`` attribute. If set to ``true`` + disables the whole select picker. If set to an array it will disable + only those specific ``option`` elements whose values are provided in + the array. + +The ``$options`` argument allows you to manually specify +the contents of the ``option`` elements of a ``select`` control. + +E.g. :: + + echo $this->Form->select('field', [1, 2, 3, 4, 5]); + +Output: + +.. code-block:: html - Options can also be supplied as key-value pairs:: +The array for ``$options`` can also be supplied as key-value pairs. + +E.g. :: echo $this->Form->select('field', [ 'Value 1' => 'Label 1', @@ -987,9 +1251,9 @@ Defaults to ``true``:: 'Value 3' => 'Label 3' ]); - Output: +Output: - .. code-block:: html +.. code-block:: html - If you would like to generate a select with optgroups, just pass - data in hierarchical format. This works on multiple checkboxes and radio - buttons too, but instead of optgroups wraps elements in fieldsets:: +If you would like to generate a ``select`` with optgroups, just pass +data in hierarchical format (nested array). This works on multiple +checkboxes and radio buttons too, but instead of ``optgroup`` it wraps +the elements in ``fieldset`` elements. + +For example:: $options = [ - 'Group 1' => [ - 'Value 1' => 'Label 1', - 'Value 2' => 'Label 2' - ], - 'Group 2' => [ - 'Value 3' => 'Label 3' - ] + 'Group 1' => [ + 'Value 1' => 'Label 1', + 'Value 2' => 'Label 2' + ], + 'Group 2' => [ + 'Value 3' => 'Label 3' + ] ]; echo $this->Form->select('field', $options); - Output: +Output: - .. code-block:: html +.. code-block:: html -To generate attributes within an option tag:: +To generate HTML attributes within an ``option`` tag:: $options = [ - [ 'text' => 'Description 1', 'value' => 'value 1', 'attr_name' => 'attr_value 1' ], - [ 'text' => 'Description 2', 'value' => 'value 2', 'attr_name' => 'attr_value 2' ], - [ 'text' => 'Description 3', 'value' => 'value 3', 'other_attr_name' => 'other_attr_value' ], + ['text' => 'Description 1', 'value' => 'value 1', 'attr_name' => 'attr_value 1'], + ['text' => 'Description 2', 'value' => 'value 2', 'attr_name' => 'attr_value 2'], + ['text' => 'Description 3', 'value' => 'value 3', 'other_attr_name' => 'other_attr_value'], ]; echo $this->Form->select('field', $options); @@ -1045,21 +1312,58 @@ Output: -* ``$attributes['multiple']`` If 'multiple' has been set to ``true`` for an - control that outputs a select, the select will allow multiple selections:: +**Controlling Select Pickers via Attributes** - echo $this->Form->select('field', $options, ['multiple' => true]); +By using specific options in the ``$attributes`` parameter you can control +certain behaviors of the ``select()`` method. - Alternatively set 'multiple' to 'checkbox' to output a list of - related check boxes:: +* ``'empty'`` - Set the ``'empty'`` key in the ``$attributes`` argument + to ``true`` (the default value is ``false``) to add a blank option with an + empty value at the top of your dropdown list. - $options = [ - 'Value 1' => 'Label 1', - 'Value 2' => 'Label 2' - ]; - echo $this->Form->select('field', $options, [ - 'multiple' => 'checkbox' - ]); + For example:: + + $options = ['M' => 'Male', 'F' => 'Female']; + echo $this->Form->select('gender', $options, ['empty' => true]); + + Will output: + + .. code-block:: html + + + +* ``'escape'`` - The ``select()`` method allows for an attribute + called ``'escape'`` which accepts a boolean value and determines + whether to HTML entity encode the contents of the ``select``'s ``option`` + elements. + + E.g. :: + + // This will prevent HTML-encoding the contents of each option element + $options = ['M' => 'Male', 'F' => 'Female']; + echo $this->Form->select('gender', $options, ['escape' => false]); + +* ``'multiple'`` - If set to ``true``, the select picker will allow + multiple selections. + + E.g. :: + + echo $this->Form->select('field', $options, ['multiple' => true]); + + Alternatively, set ``'multiple'`` to ``'checkbox'`` in order to output a + list of related checkboxes:: + + $options = [ + 'Value 1' => 'Label 1', + 'Value 2' => 'Label 2' + ]; + echo $this->Form->select('field', $options, [ + 'multiple' => 'checkbox' + ]); Output: @@ -1067,63 +1371,98 @@ Output:
- +
- +
-* ``$attributes['disabled']`` When creating checkboxes, this option can be set - to disable all or some checkboxes. To disable all checkboxes set disabled - to ``true``:: +* ``'disabled'`` - This option can be set in order to disable all or some + of the ``select``'s ``option`` items. To disable all items set ``'disabled'`` + to ``true``. To disable only certain items, assign to ``'disabled'`` + an array containing the keys of the items to be disabled. - $options = [ - 'Value 1' => 'Label 1', - 'Value 2' => 'Label 2' - ]; - echo $this->Form->select('field', $options, [ - 'multiple' => 'checkbox', - 'disabled' => ['Value 1'] - ]); + E.g. :: + + $options = [ + 'M' => 'Masculine', + 'F' => 'Feminine', + 'N' => 'Neuter' + ]; + echo $this->Form->select('gender', $options, [ + 'disabled' => ['M', 'N'] + ]); + + Will output: + + .. code-block:: html + + + + This option also works when ``'multiple'`` is set to ``'checkbox'``:: + + $options = [ + 'Value 1' => 'Label 1', + 'Value 2' => 'Label 2' + ]; + echo $this->Form->select('field', $options, [ + 'multiple' => 'checkbox', + 'disabled' => ['Value 1'] + ]); Output: .. code-block:: html - -
+ +
-
-
+
+
-
+
Creating File Inputs -------------------- .. php:method:: file(string $fieldName, array $options) +* ``$fieldName`` - A field name in the form ``'Modelname.fieldname'``. +* ``$options`` - An optional array including any of the + :ref:`general-control-options` as well as any valid HTML attributes. + +Creates a file upload field in the form. +The widget template used by default is:: + + 'file' => '' + To add a file upload field to a form, you must first make sure that -the form enctype is set to "multipart/form-data", so start off with -a create function such as the following:: +the form enctype is set to ``'multipart/form-data'``. + +So start off with a ``create()`` method such as the following:: echo $this->Form->create($document, ['enctype' => 'multipart/form-data']); // OR echo $this->Form->create($document, ['type' => 'file']); -Next add either of the two lines to your form view file:: +Next add a line that looks like either of the following two lines +to your form's view template file:: echo $this->Form->control('submittedfile', [ 'type' => 'file' @@ -1132,19 +1471,24 @@ Next add either of the two lines to your form view file:: // OR echo $this->Form->file('submittedfile'); -Due to the limitations of HTML itself, it is not possible to put -default values into input fields of type 'file'. Each time the form -is displayed, the value inside will be empty. +.. note:: + + Due to the limitations of HTML itself, it is not possible to put + default values into input fields of type 'file'. Each time the form + is displayed, the value inside will be empty. Upon submission, file fields provide an expanded data array to the script receiving the form data. For the example above, the values in the submitted data array would -be organized as follows, if the CakePHP was installed on a Windows -server. 'tmp\_name' will have a different path in a Unix -environment:: +be organized as follows, if CakePHP was installed on a Windows +server (the key ``'tmp\_name'`` will contain a different path +in a Unix environment):: + + $this->request->data['submittedfile'] - $this->request->data['submittedfile'] = [ + // would contain the following array: + [ 'name' => 'conference_schedule.pdf', 'type' => 'application/pdf', 'tmp_name' => 'C:/WINDOWS/TEMP/php1EE.tmp', @@ -1159,31 +1503,99 @@ way PHP handles data passed via file fields .. note:: When using ``$this->Form->file()``, remember to set the form - encoding-type, by setting the type option to 'file' in + encoding-type, by setting the ``'type'`` option to ``'file'`` in ``$this->Form->create()``. -Creating DateTime Inputs ------------------------- +Creating Date & Time Related Controls +------------------------------------- + +The date and time related methods share a number of common traits and options +and hence are grouped together into this subsection. + +.. _datetime-options: + +Common Options for Date & Time Controls +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +These options are common for the date and time related controls: + +* ``'empty'`` - If ``true`` an extra, empty, ``option`` HTML element is + added inside ``select`` at the top of the list. If a string, that string is + displayed as the empty element. Defaults to ``true``. + +* ``'default'`` | ``value`` - Use either of the two to set the default value to + be shown by the field. A value in ``$this->request->data`` matching the field + name will override this value. If no default is provided ``time()`` will + be used. + +* ``'year', 'month', 'day', 'hour', 'minute', 'second', 'meridian'`` - These + options allow you to control which control elements are generated or not. + By setting any of these options to ``false`` you can disable the generation + of that specific that select picker (if by default it would be rendered in + the used method). In addition each option allows you to pass HTML attributes + to that specific ``select`` element. + +.. _date-options: + +Options for Date-Related Controls +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +These options are concerning the date-related methods - i.e. ``year()``, +``month()``, ``day()``, ``dateTime()`` and ``date()``: + +* ``'monthNames'`` - If ``false``, 2 digit numbers will be used instead of text + for displaying months in the select picker. If set to an array (e.g. + ``['01' => 'Jan', '02' => 'Feb', ...]``), the given array will be used. + +* ``'minYear'`` - The lowest value to use in the year select picker. + +* ``'maxYear'`` - The maximum value to use in the year select picker. + +* ``'orderYear'`` - The order of year values in the year select picker. + Possible values are ``'asc'`` and ``'desc'``. Defaults to ``'desc'``. + +.. _time-options: + +Options for Time-Related Controls +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +These options are concerning the time-related methods - ``hour()``, +``minute()``, ``second()``, ``dateTime()`` and ``time()``: + +* ``'interval'`` - The interval in minutes between the values which are + displayed in the ``option`` elements of the minutes select picker. + Defaults to 1. + +* ``'round'`` - Set to ``up`` or ``down`` if you want to force rounding minutes + in either direction when the value doesn't fit neatly into an interval. + Defaults to ``null``. + +* ``timeFormat`` - Applies to ``dateTime()`` and ``time()``. The time format to + use in the select picker; either ``12`` or ``24``. When this option is set to + anything else than ``24`` the format will be automatically set to ``12`` and + the ``meridian`` select picker will be displayed automatically to the right of + the seconds select picker. Defaults to 24. + +* ``format`` - Applies to ``hour()``. The time format to use; either ``12`` or + ``24``. In case it's set to ``12`` the ``meridian`` select picker won't be + automatically displayed. It's up to you to either add it or provide means + to infer from the form context the right period of the day. Defaults to 24. + +* ``second`` - Applies to ``dateTime()`` and ``time()``. Set to ``true`` to + enable the seconds drop down. Defaults to ``false``. + +Creating DateTime Controls +~~~~~~~~~~~~~~~~~~~~~~~~~~ .. php:method:: dateTime($fieldName, $options = []) -Creates a set of select controls for date and time. This method accepts a number -of options: - -* ``monthNames`` If ``false``, 2 digit numbers will be used instead of text. - If an array, the given array will be used. -* ``minYear`` The lowest year to use in the year select -* ``maxYear`` The maximum year to use in the year select -* ``interval`` The interval for the minutes select. Defaults to 1 -* ``empty`` - If ``true``, the empty select option is shown. If a string, - that string is displayed as the empty element. -* ``round`` - Set to ``up`` or ``down`` if you want to force rounding in either - direction. Defaults to null. -* ``default`` The default value to be used by the control. A value in - ``$this->request->getData()`` matching the field name will override this value. If - no default is provided ``time()`` will be used. -* ``timeFormat`` The time format to use, either 12 or 24. -* ``second`` Set to ``true`` to enable seconds drop down. +* ``$fieldName`` - A string that will be used as a prefix for the HTML ``name`` + attribute of the ``select`` elements. +* ``$options`` - An optional array including any of the + :ref:`general-control-options`, or specific datetime options (see above), + as well as any valid HTML attributes. + +Creates a set of ``select`` elements for date and time. To control the order of controls, and any elements/content between the controls you can override the ``dateWidget`` template. By default the ``dateWidget`` template @@ -1191,8 +1603,54 @@ is:: {{year}}{{month}}{{day}}{{hour}}{{minute}}{{second}}{{meridian}} -To create a datetime controls with custom classes/attributes on a specific select -box, you can use the options in each component:: +Calling the method without additional options will generate, by default, +5 select pickers, for: year (4 digits), month (full English name), day (num), +hour (num), minutes (num). + +For example :: + + form->dateTime('registered') ?> + +Output: + +.. code-block:: html + + + + + + + +To create datetime controls with custom classes/attributes on a specific select +box, you can provide them as arrays of options for each component, within the +``$options`` argument. + +For example :: echo $this->Form->datetime('released', [ 'year' => [ @@ -1204,7 +1662,7 @@ box, you can use the options in each component:: ], ]); -Which would create the following two selects: +Which would create the following two select pickers: .. code-block:: html @@ -1220,25 +1678,76 @@ Which would create the following two selects: -Creating Time Inputs --------------------- +Creating Date Controls +~~~~~~~~~~~~~~~~~~~~~~ +.. php:method:: date($fieldName, $options = []) + +* ``$fieldName`` - A field name that will be used as a prefix for the HTML + ``name`` attribute of the ``select`` elements. +* ``$options`` - An optional array including any of the + :ref:`general-control-options`, of the :ref:`datetime-options`, any applicable + :ref:`time-options`, as well as any valid HTML attributes. + +Creates, by default, three select pickers populated with values for: +year (4 digits), month (full English name) and day (numeric), respectively. + +You can further control the generated ``select`` elements by providing +additional options. + +For example:: + + // Assuming current year is 2017; this disables day picker, removes empty + // option on year picker, limits lowest year, adds HTML attributes on year, + // adds a string 'empty' option on month, changes month to numeric + Form->date('registered', [ + 'minYear' => 2018, + 'monthNames' => false, + 'empty' => [ + 'year' => false, + 'month' => 'Choose month...' + ], + 'day' => false, + 'year' => [ + 'class' => 'cool-years', + 'title' => 'Registration Year' + ] + ]); + ?> + +Output: + +.. code-block:: html + + + + +Creating Time Controls +~~~~~~~~~~~~~~~~~~~~~~ .. php:method:: time($fieldName, $options = []) -Creates two select elements populated with 24 hours and 60 minutes for ``hour`` -and ``minute``, respectively. -Additionally, HTML attributes may be supplied in $options for each specific -``type``. If ``$options['empty']`` is ``false``, the select will not include an -empty option: - -* ``empty`` - If ``true``, the empty select option is shown. If a string, - that string is displayed as the empty element. -* ``default`` | ``value`` The default value to be used by the control. A value in - ``$this->request->getData()`` matching the field name will override this value. - If no default is provided ``time()`` will be used. -* ``timeFormat`` The time format to use, either 12 or 24. Defaults to 24. -* ``second`` Set to ``true`` to enable seconds drop down. -* ``interval`` The interval for the minutes select. Defaults to 1. +* ``$fieldName`` - A field name that will be used as a prefix for the HTML + ``name`` attribute of the ``select`` elements. +* ``$options`` - An optional array including any of the + :ref:`general-control-options`, of the :ref:`datetime-options`, any applicable + :ref:`time-options`, as well as any valid HTML attributes. + +Creates, by default, two ``select`` elements (``hour`` and ``minute``) populated +with values for 24 hours and 60 minutes, respectively. +Additionally, HTML attributes may be supplied in ``$options`` for each specific +component. If ``$options['empty']`` is ``false``, the select picker will not +include an empty default option. For example, to create a time range with minutes selectable in 15 minute increments, and to apply classes to the select boxes, you could do the @@ -1254,7 +1763,7 @@ following:: ], ]); -Which would create the following two selects: +Which would create the following two select pickers: .. code-block:: html @@ -1274,23 +1783,23 @@ Which would create the following two selects: -Creating Year Inputs --------------------- +Creating Year Controls +~~~~~~~~~~~~~~~~~~~~~~ .. php:method:: year(string $fieldName, array $options = []) -Creates a select element populated with the years from ``minYear`` -to ``maxYear``. Additionally, HTML attributes may be supplied in $options. If -``$options['empty']`` is ``false``, the select will not include an -empty option: +* ``$fieldName`` - A field name that will be used as a prefix for the HTML + ``name`` attribute of the ``select`` element. +* ``$options`` - An optional array including any of the + :ref:`general-control-options`, of the :ref:`datetime-options`, any applicable + :ref:`date-options`, as well as any valid HTML 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 control. -* ``maxYear`` The max year to appear in the select element. -* ``minYear`` The min year to appear in the select element. +Creates a ``select`` element populated with the years from ``minYear`` +to ``maxYear`` (when these options are provided) or else with values starting +from -5 years to +5 years counted from today. Additionally, HTML attributes may +be supplied in ``$options``. +If ``$options['empty']`` is ``false``, the select picker will not include an +empty item in the list. For example, to create a year range from 2000 to the current year you would do the following:: @@ -1305,25 +1814,33 @@ If it was 2009, you would get the following: .. code-block:: html -Creating Month Inputs ---------------------- +Creating Month Controls +~~~~~~~~~~~~~~~~~~~~~~~ .. php:method:: month(string $fieldName, array $attributes) -Creates a select element populated with month names:: +* ``$fieldName`` - A field name that will be used as a prefix for the HTML + ``name`` attribute of the ``select`` element. +* ``$attributes`` - An optional array including any of the + :ref:`general-control-options`, of the :ref:`datetime-options`, any applicable + :ref:`date-options`, as well as any valid HTML attributes. + +Creates a ``select`` element populated with month names. + +For example:: echo $this->Form->month('mob'); @@ -1332,62 +1849,83 @@ Will output: .. code-block:: html -You can pass in your own array of months to be used by setting the -'monthNames' attribute, or have months displayed as numbers by -passing ``false``. (Note: the default months can be localized with CakePHP -:doc:`/core-libraries/internationalization-and-localization` features.):: +You can pass in, your own array of months to be used by setting the +``'monthNames'`` attribute, or have months displayed as numbers by +passing ``false``. - echo $this->Form->month('mob', ['monthNames' => false]); +E.g. :: -Creating Day Inputs --------------------- + echo $this->Form->month('mob', ['monthNames' => false]); + +.. note:: + + The default months can be localized with CakePHP + :doc:`/core-libraries/internationalization-and-localization` features. + +Creating Day Controls +~~~~~~~~~~~~~~~~~~~~~ .. php:method:: day(string $fieldName, array $attributes) -Creates a select element populated with the (numerical) days of the +* ``$fieldName`` - A field name that will be used as a prefix for the HTML + ``name`` attribute of the ``select`` element. +* ``$attributes`` - An optional array including any of the + :ref:`general-control-options`, of the :ref:`datetime-options`, any applicable + :ref:`date-options`, as well as any valid HTML attributes. + +Creates a ``select`` element populated with the (numerical) days of the month. -To create an empty option with prompt text of your choosing (e.g. -the first option is 'Day'), you can supply the text as the final -parameter as follows:: +To create an empty ``option`` element with a prompt text of your choosing +(e.g. the first option is 'Day'), you can supply the text in the ``'empty'`` +parameter. - echo $this->Form->day('created'); +For example:: + + echo $this->Form->day('created', ['empty' => 'Day']); Will output: .. code-block:: html -Creating Hour Inputs --------------------- +Creating Hour Controls +~~~~~~~~~~~~~~~~~~~~~~ .. php:method:: hour(string $fieldName, array $attributes) -Creates a select element populated with the hours of the day. You can -create either 12 or 24 hour pickers using the format option:: +* ``$fieldName`` - A field name that will be used as a prefix for the HTML + ``name`` attribute of the ``select`` element. +* ``$attributes`` - An optional array including any of the + :ref:`general-control-options`, of the :ref:`datetime-options`, any applicable + :ref:`time-options`, as well as any valid HTML attributes. + +Creates a ``select`` element populated with the hours of the day. + +You can create either 12 or 24 hour pickers using the ``'format'`` option:: echo $this->Form->hour('created', [ 'format' => 12 @@ -1396,35 +1934,73 @@ create either 12 or 24 hour pickers using the format option:: 'format' => 24 ]); -Creating Minute Inputs ----------------------- +Creating Minute Controls +~~~~~~~~~~~~~~~~~~~~~~~~ .. php:method:: minute(string $fieldName, array $attributes) -Creates a select element populated with the minutes of the hour. You -can create a select that only contains specific values using the ``interval`` -option. For example, if you wanted 10 minute increments you would do the -following:: +* ``$fieldName`` - A field name that will be used as a prefix for the HTML + ``name`` attribute of the ``select`` element. +* ``$attributes`` - An optional array including any of the + :ref:`general-control-options`, of the :ref:`datetime-options`, any applicable + :ref:`time-options`, as well as any valid HTML attributes. - echo $this->Form->minute('created', [ +Creates a ``select`` element populated with values for the minutes of the hour. +You can create a select picker that only contains specific values by using the +``'interval'`` option. + +For example, if you wanted 10 minutes increments you would do the following:: + + // In your view template file + echo $this->Form->minute('arrival', [ 'interval' => 10 ]); -Creating Meridian Inputs ------------------------- +This would output: + +.. code-block:: html + + + +Creating Meridian Controls +~~~~~~~~~~~~~~~~~~~~~~~~~~ .. php:method:: meridian(string $fieldName, array $attributes) -Creates a select element populated with 'am' and 'pm'. +* ``$fieldName`` - A field name that will be used as a prefix for the HTML + ``name`` attribute of the ``select`` element. +* ``$attributes`` - An optional array including any of the + :ref:`general-control-options` as well as any valid HTML attributes. + +Creates a ``select`` element populated with 'am' and 'pm'. This is useful when +the hour format is set to ``12`` instead of ``24``, as it allows to specify the +period of the day to which the hour belongs. + +.. _create-label: Creating Labels =============== .. php:method:: label(string $fieldName, string $text, array $options) -Create a label element. ``$fieldName`` is used for generating the -DOM id. If ``$text`` is undefined, ``$fieldName`` will be used to inflect -the label's text:: +* ``$fieldName`` - A field name in the form ``'Modelname.fieldname'``. +* ``$text`` - An optional string providing the label caption text. +* ``$options`` - Optional. String or an array containing any of the + :ref:`general-control-options` as well as any valid HTML attributes. + +Creates a ``label`` element. The argument ``$fieldName`` is used for generating +the HTML ``for`` attribute of the element; if ``$text`` is undefined, +``$fieldName`` will also be used to inflect the label's ``text`` attribute. + +E.g. :: echo $this->Form->label('User.name'); echo $this->Form->label('User.name', 'Your username'); @@ -1436,8 +2012,7 @@ Output: -``$options`` can either be an array of HTML attributes, or a string that -will be used as a class name:: +When you set ``$options`` to a string it will be used as a class name:: echo $this->Form->label('User.name', null, ['id' => 'user-label']); echo $this->Form->label('User.name', 'Your username', 'highlight'); @@ -1452,51 +2027,140 @@ Output: Displaying and Checking Errors ============================== +FormHelper exposes a couple of methods that allow us to easily check for +field errors and when necessary display customized error messages. + +Displaying Errors +----------------- + .. php:method:: error(string $fieldName, mixed $text, array $options) -Shows a validation error message, specified by $text, for the given -field, in the event that a validation error has occurred. +* ``$fieldName`` - A field name in the form ``'Modelname.fieldname'``. +* ``$text`` - Optional. A string or array providing the error message(s). If an + array, then it should be a hash of key names => messages. Defaults to + ``null``. +* ``$options`` - An optional array that can only contain a boolean with the key + ``'escape'``, which will define whether to HTML escape the + contents of the error message. Defaults to ``true``. -Options: +Shows a validation error message, specified by ``$text``, for the given +field, in the event that a validation error has occurred. If ``$text`` is not +provided then the default validation error message for that field will be used. -- 'escape' bool Whether or not to HTML escape the contents of the - error. +Uses the following template widgets:: -.. TODO:: Add examples. + 'error' => '
{{content}}
' + 'errorList' => '
    {{content}}
' + 'errorItem' => '
  • {{text}}
  • ' -.. php:method:: isFieldError(string $fieldName) +The ``'errorList'`` and ``'errorItem'`` templates are used to format mutiple +error messages per field. -Returns ``true`` if the supplied $fieldName has an active validation -error. :: +Example:: - if ($this->Form->isFieldError('gender')) { - echo $this->Form->error('gender'); + // If in TicketsTable you have a 'notEmpty' validation rule: + public function validationDefault(Validator $validator) + { + $validator + ->requirePresence('ticket', 'create') + ->notEmpty('ticket'); } + // And inside Templates/Tickets/add.ctp you have: + echo $this->Form->text('ticket'); + + if ($this->Form->isFieldError('ticket')) { + echo $this->Form->error('ticket', 'Completely custom error message!'); + } + +If you would click the *Submit* button of your form without providing a value +for the *Ticket* field, your form would output: + +.. code-block:: html + + +
    Completely custom error message!
    + .. note:: When using :php:meth:`~Cake\\View\\Helper\\FormHelper::control()`, errors are - rendered by default. + rendered by default, so you don't need to use ``isFieldError()`` or call + ``error()`` manually. + +.. tip:: + + If you use a certain model field to generate multiple form fields via + ``control()``, and you want the same validation error message displayed for + each one, you will probably be better off defining a custom error message + inside the respective :ref:`validator rules`. + +.. TODO:: Add examples. + +Checking for Errors +------------------- + +.. php:method:: isFieldError(string $fieldName) + +* ``$fieldName`` - A field name in the form ``'Modelname.fieldname'``. + +Returns ``true`` if the supplied ``$fieldName`` has an active validation +error, otherwise returns ``false``. + +Example :: + + if ($this->Form->isFieldError('gender')) { + echo $this->Form->error('gender'); + } Creating Buttons and Submit Elements ==================================== +Creating Submit Elements +------------------------ + .. php:method:: submit(string $caption, array $options) -Creates a submit input with ``$caption`` as the text. If the supplied -``$caption`` is a URL to an image, an image submit button will be generated. +* ``$caption`` - An optional string providing the button's text caption or a + path to an image. Defaults to ``'Submit'``. +* ``$options`` - An optional array including any of the + :ref:`general-control-options`, or of the specific submit options (see below) + as well as any valid HTML attributes. + +Creates an ``input`` element of ``submit`` type, with ``$caption`` as value. +If the supplied ``$caption`` is a URL pointing to an image (i.e. if the string +contains '://' or contains any of the extensions '.jpg, .jpe, .jpeg, .gif'), +an image submit button will be generated, using the specified image if it +exists. If the first character is '/' then the image path is relative to +*webroot*, else if the first character is not '/' then the image path is +relative to *webroot/img*. + +By default it will use the following widget templates:: + + 'inputSubmit' => '' + 'submitContainer' => '
    {{content}}
    ' + +**Options for Submit** + +* ``'type'`` - Set this option to ``'reset'`` in order to generate reset buttons. + It defaults to ``'submit'``. + +* ``'templateVars'`` - Set this array to provide additional template variables + for the input element and its container. + +* Any other provided attributes will be assigned to the ``input`` element. + The following:: - echo $this->Form->submit(); + echo $this->Form->submit('Click me'); Will output: .. code-block:: html -
    +
    -You can pass a relative or absolute URL to an image for the -caption parameter instead of caption text:: +You can pass a relative or absolute URL of an image to the +caption parameter instead of the caption text:: echo $this->Form->submit('ok.png'); @@ -1514,16 +2178,29 @@ Creating Button Elements .. php:method:: button(string $title, array $options = []) +* ``$title`` - Mandatory string providing the button's text caption. +* ``$options`` - An optional array including any of the + :ref:`general-control-options`, or of the specific button options (see below) + as well as any valid HTML attributes. + Creates an HTML button with the specified title and a default type -of "button". Setting ``$options['type']`` will output one of the -three possible button types: +of ``'button'``. + +**Options for Button** + +* ``$options['type']`` - You can set this to one of the following three + possible values: -#. submit: Same as the ``$this->Form->submit`` method - (the - default). -#. reset: Creates a form reset button. -#. button: Creates a standard push button. + #. ``'submit'`` - Similarly to the ``$this->Form->submit()`` method it will + create a submit button. However this won't generate a wrapping ``div`` + as ``submit()`` does. This is the default type. + #. ``'reset'`` - Creates a form reset button. + #. ``'button'`` - Creates a standard push button. -:: +* ``$options['escape']`` - Boolean. If set to ``true`` it will HTML encode + the value provided inside ``$title``. Defaults to ``false``. + +For example:: echo $this->Form->button('A Button'); echo $this->Form->button('Another Button', ['type' => 'button']); @@ -1539,9 +2216,7 @@ Will output: -The ``button`` control type supports the ``escape`` option, which accepts -a boolean and defaults to ``false``. It determines whether to HTML encode the -``$title`` of the button:: +Example of use of the ``'escape'`` option:: // Will render escaped HTML. echo $this->Form->button('Submit Form', [ @@ -1554,9 +2229,13 @@ Closing the Form .. php:method:: end($secureAttributes = []) +* ``$secureAttributes`` - Optional. Allows you to provide secure attributes + which will be passed as HTML attributes into the hidden input elements + generated for the Security Component. + The ``end()`` method closes and completes a form. Often, ``end()`` will only output a closing form tag, but using ``end()`` is a good practice as it -enables FormHelper to insert hidden form elements that +enables FormHelper to insert the hidden form elements that :php:class:`Cake\\Controller\\Component\\SecurityComponent` requires: .. code-block:: php @@ -1567,10 +2246,10 @@ enables FormHelper to insert hidden form elements that Form->end(); ?> -The ``$secureAttributes`` parameter allows you to pass additional HTML -attributes to the hidden inputs that are generated when your application is -using ``SecurityComponent``. If you need to add additional attributes to the -generated hidden inputs you can use the ``$secureAttributes`` argument:: +If you need to add additional attributes to the generated hidden inputs +you can use the ``$secureAttributes`` argument. + +E.g. :: echo $this->Form->end(['data-type' => 'hidden']); @@ -1591,47 +2270,118 @@ Will output: :php:class:`Cake\\Controller\\Component\\SecurityComponent` in your application you should always end your forms with ``end()``. -Creating Standalone Buttons and POST links +Creating Standalone Buttons and POST Links ========================================== +Creating POST Buttons +--------------------- + .. php:method:: postButton(string $title, mixed $url, array $options = []) - Create a `` +
    + + + +
    + + +Since this method generates a ``form`` element, do not use this method in an +already opened form. Instead use +:php:meth:`Cake\\View\\Helper\\FormHelper::submit()` +or :php:meth:`Cake\\View\\Helper\\FormHelper::button()` to create buttons +inside opened forms. + +Creating POST Links +------------------- .. php:method:: postLink(string $title, mixed $url = null, array $options = []) - Creates an HTML link, but accesses the URL using method POST. Requires - JavaScript to be enabled in browser. +* ``$title`` - Mandatory string providing the text to be wrapped in ```` + tags. +* ``$url`` - Optional. String or array which contains the URL + of the form (Cake-relative or external URL starting with ``http://``). +* ``$options`` - An optional array including any of the + :ref:`general-control-options`, or of the specific options (see below) as well + as any valid HTML attributes. + +Creates an HTML link, but accesses the URL using the method you specify +(defaults to POST). Requires JavaScript to be enabled in browser. - This method creates a ``
    `` 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 :ref:`view block ` that can be - rendered outside of the main form. +**Options for POST Link** - If all you are looking for is a button to submit your form, then you should - use :php:meth:`Cake\\View\\Helper\\FormHelper::button()` or - :php:meth:`Cake\\View\\Helper\\FormHelper::submit()` instead. +* ``'data'`` - Array with key/value to pass in hidden input. - .. note:: - Be careful to not put a postLink inside an open form. Instead use the - ``block`` option to buffer the form into a :ref:`view-blocks` +* ``'method'`` - Request method to use. E.g. set to ``'delete'`` + to simulate a HTTP/1.1 DELETE request. Defaults to ``'post'``. + +* ``'confirm'`` - The confirmation message to display on click. Defaults to + ``null``. + +* ``'block'`` - Set this option to ``true`` to append the form to view block + ``'postLink'`` or provide a custom block name. Defaults to ``null``. + +* Also, the ``postLink`` method will accept the options which are valid for + the ``link()`` method. + +This method creates a ```` 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 :ref:`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 :php:meth:`Cake\\View\\Helper\\FormHelper::button()` or +:php:meth:`Cake\\View\\Helper\\FormHelper::submit()` instead. + +.. note:: + Be careful to not put a postLink inside an open form. Instead use the + ``block`` option to buffer the form into a :ref:`view block ` Customizing the Templates FormHelper Uses ========================================= Like many helpers in CakePHP, FormHelper uses string templates to format the HTML it creates. While the default templates are intended to be a reasonable set -of defaults. You may need to customize the templates to suit your application. +of defaults, you may need to customize the templates to suit your application. -To change the templates when the helper is loaded you can set the ``templates`` +To change the templates when the helper is loaded you can set the ``'templates'`` option when including the helper in your controller:: // In a View class @@ -1639,8 +2389,8 @@ option when including the helper in your controller:: 'templates' => 'app_form', ]); -This would load the tags in **config/app_form.php**. This file should -contain an array of templates indexed by name:: +This would load the tags found in **config/app_form.php**. This file should +contain an array of templates *indexed by name*:: // in config/app_form.php return [ @@ -1649,6 +2399,7 @@ contain an array of templates indexed by name:: Any templates you define will replace the default ones included in the helper. Templates that are not replaced, will continue to use the default values. + You can also change the templates at runtime using the ``setTemplates()`` method:: $myTemplates = [ @@ -1660,10 +2411,10 @@ You can also change the templates at runtime using the ``setTemplates()`` method .. warning:: - Template strings containing a percentage sign (``%``) need special attention, + Template strings containing a percentage sign (``%``) need special attention; you should prefix this character with another percentage so it looks like ``%%``. The reason is that internally templates are compiled to be used with - ``sprintf()``. Example: '
    {{content}}
    ' + ``sprintf()``. Example: ``'
    {{content}}
    '`` List of Templates ----------------- @@ -1672,11 +2423,14 @@ The list of default templates, their default format and the variables they expect can be found at the `FormHelper API documentation `_. +Using Distinct Custom Control Containers +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In addition to these templates, the ``control()`` method will attempt to use distinct templates for each control container. For example, when creating a datetime control the ``datetimeContainer`` will be used if it is present. -If that container is missing the ``inputContainer`` template will be used. For -example:: +If that container is missing the ``inputContainer`` template will be used. + +For example:: // Add custom radio wrapping HTML $this->Form->setTemplates([ @@ -1684,13 +2438,21 @@ example:: ]); // Create a radio set with our custom wrapping div. - echo $this->Form->radio('User.email_notifications', ['y', 'n']); + echo $this->Form->control('User.email_notifications', [ + 'options' => ['y', 'n'], + 'type' => 'radio' + ]); + +Using Distinct Custom Form Groups +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Similar to controlling containers, the ``control()`` method will also attempt to use distinct templates for each form group. A form group is a combo of label and -control. For example, when creating a radio input the ``radioFormGroup`` will be -used if it is present. If that template is missing by default each set of label -& input is rendered using the ``formGroup`` template. For example:: +control. For example, when creating a radio control the ``radioFormGroup`` will be +used if it is present. If that template is missing by default each set of ``label`` +& ``input`` is rendered using the default ``formGroup`` template. + +For example:: // Add custom radio form group $this->Form->setTemplates([ @@ -1701,7 +2463,9 @@ Adding Additional Template Variables to Templates ------------------------------------------------- You can add additional template placeholders in custom templates, and populate -those placeholders when generating controls:: +those placeholders when generating controls. + +E.g. :: // Add a template with the help placeholder. $this->Form->setTemplates([ @@ -1714,13 +2478,26 @@ those placeholders when generating controls:: 'templateVars' => ['help' => 'At least 8 characters long.'] ]); +Output: + +.. code-block:: html + +
    + + + At least 8 characters long. +
    + .. versionadded:: 3.1 The templateVars option was added in 3.1.0 Moving Checkboxes & Radios Outside of a Label --------------------------------------------- -By default CakePHP nests checkboxes and radio buttons within label elements. +By default CakePHP nests checkboxes created via ``control()`` and radio buttons +created by both ``control()`` and ``radio()`` within label elements. This helps make it easier to integrate popular CSS frameworks. If you need to place checkbox/radio inputs outside of the label you can do so by modifying the templates:: @@ -1735,10 +2512,23 @@ This will make radio buttons and checkboxes render outside of their labels. Generating Entire Forms ======================= +Creating Multiple Controls +-------------------------- + .. php:method:: controls(array $fields = [], $options = []) -Generates a set of controls for the given context wrapped in a fieldset. You can -specify the generated fields by including them:: +* ``$fields`` - An array of fields to generate. Allows setting + custom types, labels and other options for each specified field. +* ``$options`` - Optional. An array of options. Valid keys are: + + #. ``'fieldset'`` - Set this to ``false`` to disable the fieldset. + If empty, the fieldset will be enabled. Can also be an array of parameters + to be applied as HTML attributes to the ``fieldset`` tag. + #. ``legend`` - String used to customize the ``legend`` text. Set this to + ``false`` to disable the legend for the generated input set. + +Generates a set of controls for the given context wrapped in a +``fieldset``. You can specify the generated fields by including them:: echo $this->Form->controls([ 'name', @@ -1756,46 +2546,44 @@ You can customize the generated controls by defining additional options in the 'name' => ['label' => 'custom label'] ]); -When customizing, ``fields``, you can use the ``$options`` parameter to +When customizing, ``$fields``, you can use the ``$options`` parameter to control the generated legend/fieldset. -- ``fieldset`` Set to ``false`` to disable the fieldset. You can also pass an - array of parameters to be applied as HTML attributes to the fieldset tag. If - you pass an empty array, the fieldset will be displayed without attributes. -- ``legend`` Set to ``false`` to disable the legend for the generated control set. - Or supply a string to customize the legend text. - For example:: - echo $this->Form->allControls( + echo $this->Form->controls( [ 'name' => ['label' => 'custom label'] ], - null, - ['legend' => 'Update your post'] - ); - // Or prior to 3.4.0: - echo $this->Form->allInputs( - [ - 'name' => ['label' => 'custom label'] - ], - null, ['legend' => 'Update your post'] ); +If you disable the ``fieldset``, the ``legend`` will not print. -If you disable the fieldset, the legend will not print. +Creating Controls for a Whole Entity +------------------------------------ .. php:method:: allControls(array $fields, $options = []) +* ``$fields`` - Optional. An array of customizations for the fields that will + be generated to generate. Allows setting custom types, labels and other + options. +* ``$options`` - Optional. An array of options. Valid keys are: + + #. ``'fieldset'`` - Set this to ``false`` to disable the fieldset. + If empty, the fieldset will be enabled. Can also be an array of + parameters to be applied as HTMl attributes to the ``fieldset`` tag. + #. ``legend`` - String used to customize the ``legend`` text. Set this to + ``false`` to disable the legend for the generated control set. + This method is closely related to ``controls()``, however the ``$fields`` argument is defaulted to *all* fields in the current top-level entity. To exclude -specific fields from the generated controls, set them to ``false`` in the fields -parameter:: +specific fields from the generated controls, set them to ``false`` in the +``$fields`` parameter:: echo $this->Form->allControls(['password' => false]); // Or prior to 3.4.0: - echo $this->Form->allInputs(['password' => false]); + echo $this->Form->allControls(['password' => false]); .. _associated-form-inputs: @@ -1948,9 +2736,9 @@ dependencies by declaring them:: ] ]); -In the above example, the autocomplete widget would depend on the ``text`` and +In the above example, the ``autocomplete`` widget would depend on the ``text`` and ``label`` widgets. If your widget needs access to the View, you should use the -``_view`` 'widget'. When the autocomplete widget is created, it will be passed +``_view`` 'widget'. When the ``autocomplete`` widget is created, it will be passed the widget objects that are related to the ``text`` and ``label`` names. To add widgets using the ``addWidget()`` method would look like:: @@ -1972,9 +2760,9 @@ Once added/replaced, widgets can be used as the control 'type':: echo $this->Form->control('search', ['type' => 'autocomplete']); -This will create the custom widget with a label and wrapping div just like -``control()`` always does. Alternatively, you can create just the control widget -using the magic method:: +This will create the custom widget with a ``label`` and wrapping ``div`` just +like ``controls()`` always does. Alternatively, you can create just the control +widget using the magic method:: echo $this->Form->autocomplete('search', $options); @@ -1984,7 +2772,7 @@ Working with SecurityComponent :php:meth:`Cake\\Controller\\Component\\SecurityComponent` offers several features that make your forms safer and more secure. By simply including the ``SecurityComponent`` in your controller, you'll automatically benefit from -form tampering features. +form tampering-prevention features. As mentioned previously when using SecurityComponent, you should always close your forms using :php:meth:`~Cake\\View\\Helper\\FormHelper::end()`. This will @@ -1992,17 +2780,26 @@ ensure that the special ``_Token`` inputs are generated. .. php:method:: unlockField($name) - Unlocks a field making it exempt from the ``SecurityComponent`` field - hashing. This also allows the fields to be manipulated by JavaScript. - The ``$name`` parameter should be the entity property name for the input:: +* ``$name`` - Optional. The dot-separated name for the field. + +Unlocks a field making it exempt from the ``SecurityComponent`` field +hashing. This also allows the fields to be manipulated by JavaScript. +The ``$name`` parameter should be the entity property name for the field:: - $this->Form->unlockField('id'); + $this->Form->unlockField('id'); -.. php:method:: secure(array $fields = []) +.. php:method:: secure(array $fields = [], array $secureAttributes = []) - Generates a hidden field with a security hash based on the fields used - in the form. +* ``$fields`` - Optional. An array containing the list of fields to use when + generating the hash. If not provided, then ``$this->fields`` will be used. +* ``$secureAttributes`` - Optional. An array of HTML attributes to be passed + into the generated hidden input elements. +Generates a hidden ``input`` field with a security hash based on the fields used +in the form or an empty string when secured forms are not in use. +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'``. .. meta:: :title lang=en: FormHelper