Tips for Form API of Drupal 8

Submitted by editor on Fri, 08/26/2016 - 14:01
Question

Some Tips of the drupal 8 form API.

  • How to add something just after a input ?
  • How to make a collapsible field set ?
  • How to Add a custom Validator / Submitter?
  • How to use multiple submit buttons ?

Add html after a field

(#field_prefix and #field_suffix).

Example:
$form['fieldname'] = array(
  '#type' => 'input',
  '#title' => t('The Label'),
  '#prefix' => '<span>Your HTML Just Before</span>'
  '#suffix' => '<span>Your HTML Just After</span>'

);

Add HTML just after a input, select, textarea ... (#field_prefix and #field_suffix)

Example:
$form['fieldname'] = array(
  '#type' => 'input',
  '#title' => t('The Label'),
  '#field_prefix' => '<span>Your HTML Just Before input</span>'
  '#field_suffix' => '<span>Your HTML Just After input</span>'

);

Make a collapsible field set

Drupal 8 use HTML5  details tag and "OPEN" attribute to make a collapsible fieldset.  Example:
$form['filters'] = array(
  '#type' => 'details',
  '#title' => 'Filters',
  '#open' => FALSE,
);

Add a custom Validator / Submitter

Step 1. Create your Validator method

public function validateFormCustom(array &$form, FormStateInterface $form_state) {
  //Your validation codes
}

Step 2. Add this validator to your form.

$form['#validate'][] = '::validateFormCustom';

Handle multiple submit buttons

Step 1. Create several submit buttons and add custom submitter to each buttons (If you add nothing, it use the default submit method):

$form['actions']['submit_apply'] = [
  '#type' => 'submit',
  '#value' => t('Apply'),
];
$form['actions']['submit_reset'] = [
  '#type' => 'submit',
  '#value' => t('Reset'),
  '#submit' => array('::submitFormReset'),
];

Step 2. Then create your custom submit functions like:

public function submitForm(array &$form, FormStateInterface $form_state) {
  drupal_set_message("Apply");
  $form_state->setRebuild(TRUE);
}
public function submitFormReset(array &$form, FormStateInterface $form_state) {
  drupal_set_message("Reset");
  $form_state->setRebuild(FALSE);
}

Add new comment