Custom submit handler

Adding custom submit handler in Drupal 8 form

In this example we are showing how to add a custom button to user edit form with its own function submission handler.

We are disabling user from loading FormStateInterface using entity, setting field value and saving it.

Create custom module (in this example: ws_custom) and use namespaces:

  • use Drupal\Core\Form\FormStateInterface;
  • use Drupal\Core\Form;

In custom module you will need to implement Drupal hook: hook_form_alter():

  1. Create new form action (in this example: 'disable')
  2. Set form '#type' as submit to create button or link handler
  3. Set '#limit_validation_errors' as empty array to skip required fields in this altered form (or add your own validation for this submission)
  4. Add array of form functions to form '#submit'
  5. Use '#value' to set button (link) title
  6. Optional set '#button_type' as danger to add 'button--danger' class on html element
  7. By setting '#weight' value to form we are changing order of fields while displaying form (in this example, field will be added last, because of 999 weight)
<?php
/**
 * Implements hook_form_alter().
 */
function ws_custom_form_alter(&$form, FormStateInterface $form_state, $form_id) {
	switch ($form_id) {
	  case 'user_form':
		$form['actions']['disable'] = array(
			'#type' => 'submit',
			'#weight' => 999,
			'#limit_validation_errors' => array() ,
			'#button_type' => 'danger',
			'#submit' => array(
				'ws_custom_disable_account_form'
			) ,
			'#value' => t('Disable account') ,
		);
	  break;
}

Call function form alter and pass $form and $from_state. Load entity using function getFormObject on FormStateInterface and get its entity using getEntity function. Now change field with set('field', 'value') function (in this case we are setting 'status' field to '0' to disable or block user) and save this entity with save() function:

function ws_custom_disable_account_form(&$form, FormStateInterface $form_state) {
    $entity = $form_state->getFormObject()->getEntity();
    $entity->set('status', '0');
    $entity->save();
}

If you run into a problem - we are here to help. Or maybe in additon to this example you may leave us feedback.

Share this post