Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Adding custom submit handler in Drupal 8 form

Parent Feed: 

In this example we show how to add a custom button to a user edit form with its own function submission handler. What needs to be done is to disable a user from loading FormStateInterface using entity, set the field value and save it.

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

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

In the 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)
 '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 want to provide another example or add to this one, post a comment. ;)

If you run into a problem - we are here to help.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web