1. Home
  2. Docs
  3. Application Framework
  4. Classes & Patterns
  5. Forms

Forms

MWP\Framework\Helpers\Form

The MWP Framework facilitates building forms through code via a form helper. The basic steps for creating and processing a form are:

  • Call the createForm($name, $options) method on your plugin instance to create an empty form.
  • Call the addField($name, $type, $options) method on the form object to add appropriate fields.
  • Call the isValidSubmission() method on the form object to check if the form has been submitted.
  • Call the getValues() method on the form object to get submitted values for processing.
  • Call the render() method on the form object to generate the form output.

@Example Code

use VendorName\PackageName\Plugin;

/* Create a form and add some fields */
$form = Plugin::instance()->createForm('user_questions');
$form->addField('name', 'text', ['label' => 'Enter Your Name', 'required' => true]);
$form->addField('age', 'number', ['label' => 'Age', 'attr' => ['min' => 5]]);

/* Process form if it was just submitted */
if ( $form->isValidSubmission() ) {
    $values = $form->getValues();
    update_user_meta( get_current_user_id(), 'name', $values['name'] );
    update_user_meta( get_current_user_id(), 'age', $values['age'] );
    $form->processComplete( function() {
        wp_redirect( home_url() );
        exit;
    });
}

/* Output the form, indicating errors if form was incorrectly submitted */
echo $form->render();

@Field Options

$form->addField( $name, $type, $options );

/**
 * Add a field to the form
 *
 * @param   string          $name               The field name
 * @param   string          $type               The field type (registered shorthand or a class name)
 * @param   array           $options            The field options
 * @param   string|NULL     $parent_name        The parent field name to add this field to
 * @param   string|NULL     $insert_name        The name of a field to insert this field by
 * @param   string          $insert_position    The position ('before' or 'after') to insert this field at
 * @return  object                              The added form element
 */
public function addField( $name, $type='text', $options=array(), $parent_name=NULL, $insert_name=NULL, $insert_position='after' )

Depending on the $type of field being added to the form, different $options may be available. However, every $type of field supports the following standard $options:

label (string) : The label of the field / Default: Guessed from the field name > doc
data (mixed) : The current value for the field / Default: Default data > doc
required (bool) : If a value is required for the field > doc
disabled => (bool) : Indicates if field should be disabled when rendered doc
attr (array) : Associative array of html attributes to add to the field widget > doc
toggles (array) : An associative array of html elements to show/hide based on field value
constraints (array) : An array of constraints to use when validating the field value > doc
empty_data (mixed) : The data to use if the field was left empty on submission > doc
label_attr (array) : Associative array of html attributes to add to the label > doc
label_prefix (string) : HTML to prefix to the label element
label_suffix (string) : HTML to suffix to the label element
field_prefix (string) : HTML to prefix to the input element(s)
field_suffix (string) : HTML to suffix to the input element(s)
row_attr (array) : Associative array of html attributes to add to the form row
row_prefix (string) : HTML to prefix to the form row
row_suffix (string) : HTML to suffix to the form row
prefix (string) : HTML to prefix to the form row contents
suffix (string) : HTML to suffix to the form row contents
error_bubbling (bool) : Indicate if errors should display as generic form errors > doc

@Field Toggles

The toggles option for form fields allows you to toggle the visibility of other form elements according to the value of the field being added. The visibility toggles are automatically handled via javascript when the form is rendered.

$options = array( 
    'toggles' => array(
        /* Value for which a visibility change is triggered */
        'some_value' => array(
            /* List of form elements to show */
            'show' => array(
                /* Each array element is a jQuery selector */
                '#form_element_id1',
                '#form_element_id2',
            ),
            /* List of form elements to hide */
            'hide' => array(),
        ),
    ),
);

@Field Constraints

Field constraints can be assigned to fields in their options in order to validate submitted data. If form data is submitted that does not satisfy the constraint, then the form will not validate.

You can use any of the documented Symfony constraints, or optionally just use your own custom function.

    $form->addField( 'number', 'integer', array(
        'label' => 'Number',
        'description' => 'Choose a number from 1 to 3',
        'attr' => [ 'min' => 1, 'max' => 3, 'step' => 1 ],
        'required' => true,
    ));

    $form->addField( 'number_name', 'choice', array(
        'label' => 'Number Name',
        'description' => 'Choose the name of the number you selected above.',
        'choices' => [ 'One' => 1, 'Two' => 2, 'Three' => 3 ],
        'required' => true,
        'constraints' => [ function( $data, $context ) {
            $form_values = $context->getRoot()->getData();
            if ( $data !== $form_values['number'] ) {
                $context->addViolation( __( 'You did not select the correct name for the number you picked.' ) );
            }
        }],
    ));

@Field Types

Text

text : $form->addField( $name, 'text', $options )

The text field represents the most basic input text field.


Text Area

textarea : $form->addField( $name, 'textarea', $options )

Renders a textarea HTML element.


Email

email : $form->addField( $name, 'email', $options )

The email field is a text field that is rendered using the HTML5 <input type="email" /> tag.


Integer

integer : $form->addField( $name, 'integer', $options )

Renders an input “number” field. Basically, this is a text field that’s good at handling data that’s in an integer form. The input number field looks like a text box, except that – if the user’s browser supports HTML5 – it will have some extra front-end functionality.

This field has different options on how to handle input values that aren’t integers. By default, all non-integer values (e.g. 6.78) will round down (e.g. 6).


Money

money : $form->addField( $name, 'money', $options )

Renders an input text field and specializes in handling submitted “money” data.

This field type allows you to specify a currency, whose symbol is rendered next to the text field. There are also several other options for customizing how the input and output of the data is handled.

Additional Options

currency (string) Specifies the currency that the money is being specified in > doc
divisor (integer) Divide your starting value by a number before rendering it > doc


Number

number : $form->addField( $name, 'number', $options )

Renders an input text field and specializes in handling number input.


Password

password : $form->addField( $name, 'password', $options )

The password field renders an input password text box.

Additional Options

always_empty (bool) Set to FALSE to render your password field with the password in it > doc


Percent

percent : $form->addField( $name, 'percent', $options )

This field renders an input text field and specializes in handling percentage data. If your percentage data is stored as a decimal (e.g. .95), you can use this field out-of-the-box. If you store your data as a number (e.g. 95), you should set the type option to integer.

This field adds a percentage sign “%” after the input box.

Additional Options

type (string) ‘fractional’ or ‘integer’ > doc


Search

search : $form->addField( $name, 'search', $options )

This renders an <input type="search" /> field, which is a text box with special functionality supported by some browsers.

Read about the input search field at DiveIntoHTML5.info


URL

url : $form->addField( $name, 'url', $options )

The url field is a text field that prepends the submitted value with a given protocol (e.g. http://) if the submitted value doesn’t already have a protocol.

Additional Options

default_protocol (string) Default protocol to use if not entered, i.e. ‘http’ > doc


Number Range

range : $form->addField( $name, 'range', $options )

The range field is a slider that is rendered using the HTML5 <input type="range" /> tag.


Telephone Number

tel : $form->addField( $name, 'tel', $options )

The telephone field is a text field that is rendered using the HTML5 <input type="tel"> tag. Following the recommended HTML5 behavior, the value of this type is not validated in any way, because formats for telephone numbers vary too much depending on each country.

Nevertheless it may be useful to use this type in web applications because some browsers (e.g. smartphone browsers) adapt the input keyboard to make it easier to input phone numbers.


Color Picker

color : $form->addField( $name, 'color', $options )

The color field is a text field that is rendered using the HTML5 <input type="color"> tag. Depending on each browser, the behavior of this form field can vary substantially. Some browsers display it as a simple text field, while others display a native color picker.

The value of the underlying <input type="color"> field is always a 7-character string specifying an RGB color in lower case hexadecimal notation. That’s why it’s not possible to select semi-transparent colors with this element.


Multiple Choice

choice : $form->addField( $name, 'choice', $options )

A multi-purpose field used to allow the user to “choose” one or more options. It can be rendered as a select tag, radio buttons, or checkboxes.

To use this field, you must specify choices.

Additional Options

choices (array) The key is the item’s label and the value is the item’s value > doc
choice_attr (array)(callable)(string) Add additional HTML attributes to each choice > doc
choice_label (string)(callable)(false) Customize the title for choices > doc
expanded (bool) Show radios or checkboxes instead of a select list > doc
multiple (bool) Allow multiple selections of options > doc
group_by (array)(callable)(string) Group choices in optgroups > doc
placeholder (string) Customize a special “empty” option > doc
preferred_choices (array)(callable) Move certain choices to the top of your list > doc


Date/Time Select

datetime : $form->addField( $name, 'datetime', $options )

This field type allows the user to modify data that represents a specific date and time (e.g. 1984-06-05 12:15:30).

Can be rendered as a text input or select tags. The underlying format of the data can be a DateTime object, a string, a timestamp, or an array.

Additional Options

date_format (integer)(string) Defines the format option that will be passed down to the date field. > doc
date_widget (string) How to render the date widget. (‘choice’,’text’,’single_text’) > doc
time_widget (string) How to render the time widget. (‘choice’,’text’,’single_text’) > doc
placeholder (string)(array) Placeholder values for select fields > doc
format (string) Format of input if the widget option is single_text > doc
hours (array) List of hours available to the hours field > doc
minutes (array) List of minutes available to the minutes field > doc
seconds (array) List of seconds available to the seconds field > doc
days (array) List of days available to the day field > doc
months (array) List of months available to the month field > doc
years (array) List of years available to the year field > doc
html5 (bool) Use HTML5 type if this is set to true (the default) > doc
input (string) The data format (‘string’,’datetime’,’array’,’timestamp’) > doc
model_timezone (string) Timezone that the input data is stored in > doc
view_timezone (string) Timezone for how the data should be shown to the user > doc
widget (string) Defines the default type for both the date and time widgets > doc
with_minutes (bool) Include minutes in the form widget. > doc
with_seconds (bool) Include seconds in the form widget. > doc


Date Select

date : $form->addField( $name, 'date', $options )

A field that allows the user to modify date information via a variety of different HTML elements.

This field can be rendered in a variety of different ways via the widget option and can understand a number of different input formats via the input option.

Additional Options

days (array) List of days available to the day field > doc
months (array) List of months available to the month field > doc
years (array) List of years available to the year field > doc
placeholder (string)(array) Placeholder values for select fields > doc
format (string) Date format > doc
html5 (bool) Use html5 to render the field > doc
input (string) The format of the input data (‘string’,’datetime’,’array’,’timestamp’) > doc
model_timezone (string) Timezone that the input data is stored in > doc
view_timezone (string) Timezone for how the data should be shown to the user > doc
widget (string) The basic way in which this field should be rendered (‘choice’,’text’,’single_text’) > doc


Time Select

time : $form->addField( $name, 'time', $options )

A field to capture time input.

This can be rendered as a text field, a series of text fields (e.g. hour, minute, second) or a series of select fields. The underlying data can be stored as a DateTime object, a string, a timestamp, or an array.

Additional Options

placeholder (string)(array) Placeholder values for select fields > doc
hours (array) List of hours available to the hours field > doc
minutes (array) List of minutes available to the minutes field > doc
seconds (array) List of seconds available to the seconds field > doc
html5 (bool) If this is set to true (the default), it’ll use the HTML5 type > doc
input (string) The data format (‘string’,’datetime’,’array’,’timestamp’) > doc
model_timezone (string) Timezone that the input data is stored in > doc
view_timezone (string) Timezone for how the data should be shown to the user > doc
widget (string) Defines the default type for both the date and time widgets > doc
with_minutes (bool) Include minutes in the form widget. > doc
with_seconds (bool) Include seconds in the form widget. > doc


Date Interval Select

dateinterval : $form->addField( $name, 'dateinterval', $options )

This field allows the user to select an interval of time. For example, if you want to allow the user to choose how often they receive a status email, they could use this field to choose intervals like every “10 minutes” or “3 days”.

The field can be rendered in a variety of different ways (see widget) and can be configured to give you a DateInterval object, an ISO 8601 duration string (e.g. P1DT12H) or an array (see input).

Additional Options

days (array) List of days available to the days field type. > doc
hours (array) List of hours available to the hours field type. > doc
minutes (array) List of minutes available to the minutes field type. > doc
months (array) List of months available to the months field. > doc
years (array) List of years available to the years field. > doc
seconds (array) List of seconds available to the seconds field. > doc
weeks (array) List of weeks available to the weeks field. > doc
input (string) The format of the data. (‘string’,’dateinterval’,’array’) > doc
labels (array) The labels displayed for each of the elements of this type. > doc
placeholder (string)(array) Placeholder used to add “blank” entries to select boxes. > doc
widget (string) How to render the widget. (‘choice’,’text’,’integer’,’single_text’) > doc
with_days (bool) Include days in the form widget. > doc
with_hours (bool) Include hours in the form widget. > doc
with_invert (bool) Include invert option in the form widget. > doc
with_minutes (bool) Include minutes in the form widget. > doc
with_seconds (bool) Include seconds in the form widget. > doc
with_months (bool) Include months in the form widget. > doc
with_weeks (bool) Include weeks in the form widget. > doc
with_years (bool) Include years in the form widget. > doc


Birthday

birthday : $form->addField( $name, 'birthday', $options )

A field that specializes in handling birthday data.

Can be rendered as a single text box, three text boxes (month, day and year), or three select boxes.

This type is essentially the same as the date type, but with a more appropriate default for the years option. The years option defaults to 120 years ago to the current year.


Checkbox

checkbox : $form->addField( $name, 'checkbox', $options )

Creates a single input checkbox. This should always be used for a field that has a boolean value: if the box is checked, the field will be set to true, if the box is unchecked, the value will be set to false.

Additional Options

value (mixed) The value that’s actually used as the value for the checkbox > doc


File Upload

file : $form->addField( $name, 'file', $options )

This add a file input to your form.

Additional Options

multiple (bool) Allow uploading multiple files > doc


Radio Option

radio : $form->addField( $name, 'radio', $options )

Additional Options

value (mixed) The value that’s actually used as the value for the radio > doc


Field Collection

collection : $form->addField( $name, 'collection', $options )

$form->addField( 'options_signers', 'collection', [
    'label' => __( 'Signers' ),
    'allow_add' => true,
    'allow_delete' => true,
    'required' => true,
    'entry_options' => [
        'label' => 'Signer Details',
        'fields' => array(
            array( 
                'name' => 'options_signer_email',
                'type' => 'text',
                'options' => [
                    'label' => __( 'Email Address' ),
                    'constraints' => 'email',
                    'required' => true,
                ],
            ),
            array( 
                'name' => 'options_signer_name',
                'type' => 'text',
                'options' => [
                    'label' => __( 'Name' ),
                    'required' => true,
                ],
            ),
        ),
    ],
]);

Repeated Field

repeated : $form->addField( $name, 'repeated', $options )


Hidden Field

hidden : $form->addField( $name, 'hidden', $options )

The hidden type represents a hidden input field.


Button

button : $form->addField( $name, 'button', $options )

A simple, non-responsive button.


Reset Button

reset : $form->addField( $name, 'reset', $options )

A button that resets all fields to their original values.


Submit Button

submit : $form->addField( $name, 'submit', $options )

A submit button.


Field Group

fieldgroup : $form->addField( $name, 'fieldgroup', $options )

Add a container for a group of fields to the form. To add fields to a fieldgroup, specify the name of the fieldgroup as the $parent_name when adding new fields to it.


@Custom Fields

The MWP Framework form builder is a facade of the Symfony Forms library. Therefore, to add a new form field type you need to create a class which represents the field and dictates how it will behave and be rendered, as documented here.

For the MWP form builder to recognize your form field type, return your custom field class from the mwp_form_field_class WordPress filter. Or simply use your full class name as the $type parameter when using addField().

/**
 * Get the class to use for an unrecognized form field $type
 *
 * @param   string   $type    The form field type
 * @return  string
 */
apply_filters( 'mwp_form_field_class', $type );

Any custom template for your form field should be placed in the /templates/form/symfony folder of your plugin.

@Instance Methods

$form->addField( $name, $options, $parent_name, $insert_name, $insert_position )

Add a new field to a form.

/**
 * Add a field to the form
 *
 * @param   string          $name               The field name
 * @param   string          $type               The field type (registered shorthand or a class name)
 * @param   array           $options            The field options
 * @param   string|NULL     $parent_name        The parent field name to add this field to
 * @param   string|NULL     $insert_name        The name of a field which this field should be inserted by
 * @param   string          $insert_position    The position ('before' or 'after') to insert the field 
 * @return  object                              The added form element
 */
public function addField( $name, $type='text', $options=array(), $parent_name=NULL, $insert_name=NULL, $insert_position='after' )

$form->addTab( $name, $options, $parent_name, $insert_name, $insert_position )

This adds a tab to the form with the given $name. To add fields to the tab, specify the tab $name as the added field’s $parent_name.

/**
 * Add a form tab
 * 
 * @param   string          $name               The tab name
 * @param   array           $options            The tab options
 * @param   string          $parent_name        The parent element to add to
 * @param   string|NULL     $insert_name        The name of a field around which this field should be inserted
 * @param   string          $insert_position    The position at which to insert this field if using $insert_name 
 * @return  object                              The added form element
 */
public function addTab( $name, $options, $parent_name=NULL, $insert_name=NULL, $insert_position='after' )

$form->addHeading( $name, $heading, $parent_name, $insert_name, $insert_position )

This adds a heading row to the form.

/**
 * Add a form heading
 *
 * @param   string        $name             The field name
 * @param   string        $heading          The heading html
 * @param   string        $parent_name      The parent element to add to
 * @param   string|NULL   $insert_name      The name of a field around which this field should be inserted
 * @param   string        $insert_position          The position at which to insert this field if using $insert_name 
 * @return  object                      The added form element
 */
public function addHeading( $name, $heading, $parent_name=NULL, $insert_name=NULL, $insert_position='after' )

$form->addHtml( $name, $html_content, $parent_name, $insert_name, $insert_position )

This adds some arbitrary html markup to the form.

/**
 * Add some arbitrary html to the form
 *
 * @param   string          $name               The field name
 * @param   string          $html_content       The html content to add
 * @param   string          $parent_name        The parent element to add to
 * @param   string|NULL     $insert_name        The name of a field around which this field should be inserted
 * @param   string          $insert_position    The position at which to insert this field if using $insert_name 
 * @return  object                              The added form element
 */
public function addHtml( $name, $html_content, $parent_name=NULL, $insert_name=NULL, $insert_position='after' )

$form->csrf( $bool )

Protect the form from csrf attacks using a wp_nonce.

/**
 * Enable or disable csrf protection
 *
 * @param   bool            $bool           Either true for ON or false for OFF
 * @return  this                            Chainable
 */
public function csrf( $bool )

$form->isSubmitted()

Check if a form has been submitted in the current request. This does not validate that it is a valid submission, only that a submission attempt has been made.

/**
 * Check if form was submitted
 *
 * @return  bool
 */
public function isSubmitted()

$form->isValidSubmission()

Check if a form has a valid submission state in the current request. This will return false if the form contains validation errors, or if the form has not been submitted.

/**
 * Check for valid form submission
 *
 * @return  bool
 */
public function isValidSubmission()

$form->getSubmissionData()

Get the submission data for the form in the current request. This returns the current submission data regardless of if it is valid or not.

Use getValues() to return submission data only if it is valid.

/**
 * Get the form submission data
 *
 * @return  array|false
 */
public function getSubmissionData()

$form->getValues()

Get the current submitted values in the form if the form is a valid submission. If the form contains validation errors, or if the form has not been submitted, then this method will return any empty array.

/**
 * Get submitted form values
 *
 * @return  array
 */
public function getValues()

$form->getErrors()

Get an array of the fields that contained validation errors if the form was an invalid submission.

/**
 * Get form submission errors
 *
 * @return  array[Symfony\Component\Form\AbstractType]      Fields that had errors
 */
public function getErrors()

$form->render()

Generate the HTML markup needed to render the form.

/**
 * Get form output
 *
 * @return  string
 */
public function render()

$form->onComplete( $callback )

Register a callback function to be executed when the processComplete() method is called on the form.

/**
 * Add a form processing complete callback
 *
 * @param   callback|NULL       $callback          {
 *     A callback to execute before any final callback on the form is executed.
 *
 *     param   object       $form       The form
 *     return  void
 * }
 * @return  void
 */
public function onComplete( $callback )

$form->processComplete( $final_callback )

Signal to other callbacks that the processing of the form has been completed, allowing other registered onComplete() callbacks to run.

/**
 * Signal that the processing of a form is complete, allowing other callbacks to run
 *
 * @param   callback|NULL       $final_callback        {
 *     A callback to execute. Usually to do a redirect.
 *
 *     param   object       $form       The form
 *     return  void
 * }
 * @return  mixed
 */
public function processComplete( $final_callback=NULL )
Was this article helpful to you? Yes No

How can we help?