[Drupal-8] How to handle multiple submission buttons in Drupal 8 form?

July 21, 2016 - 06:24

I had a requirement to handle multiple buttons in a custom form in Drupal 8. In Drupal 7 we can add multiple submissions using the button definition ['#submit'] => array('my_submit_function'). In drupal 8, same process is possible with slight changes as, ['#submit'] => array('::newSubmissionHandler') in button definition. Also we can get the form values to the custom submit handler as same as default handler. Just see the sample code below for more explanation. Note that the form should be saved in src/Form/MyForm.php.

<?php
namespace Drupal\myModule\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\FormBase;

/**
 * My form class.
 */
class MyForm extends FormBase {

  /**
   * Returns a unique string identifying the form.
   *
   * @return string
   *   The string to identifying the form.
   */
  public function getFormId() {
    return 'my_form';
  }

  /**
   * Form constructor.
   *
   * @param array $form
   *   An associative array of form structure.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array $form
   *   The form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['sample_field'] = array(
      '#type' => 'textfield',
      '#title' => t('Subject'),
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save'),
    );

    $form['sample1'] = array(
      '#type' => 'submit',
      '#value' => t('Sample Button1'),
      '#submit' => array('::newSubmissionHandlerOne'),
    );
    
    $form['sample2'] = array(
      '#type' => 'submit',
      '#value' => t('Sample Button2'),
      '#submit' => array('::newSubmissionHandlerTwo'),
    );
    return $form;
  }

  /**
   * Form main submission handler.
   *
   * @param array $form
   *   An array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Current state of the form.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Get the form values here as $form_state->getValue(array('sample_field')) 
    // and process it.
  }

  /**
   * Custom submission handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function newSubmissionHandlerOne(array &$form, FormStateInterface $form_state) {
    // Get the form values here as $form_state->getValue(array('sample_field')) 
    // and process it.
  }
  
  /**
   * Custom function.
   */
  public function newSubmissionHandlerTwo() {
    // Do any other process for the button click without form values.
  }

}

Hope you get the idea for form creation too. Please feel free to get in touch with us if any queries.