2

I have a Drupal 8 User registration form that has several text fields to gather information about the user.

I'd like to write a custom hook that examines the values in those fields and then either proceeds with the registration or 'cancels' it, like perhaps redirecting to a static page or displaying some static content.

What are the hooks I need to make this happen? Do I alter the form? Or do I hook an entity_presave function?

What do I need to do to cancel the default form processing or default entity presave/save routines?

thanks,

1 Answer 1

1

Forms have a validate and submit function(s). Submit never runs unless all validation passes.

So all you have to do is add a custom validation

/*
 * Implements hook_form_FORM_ID_alter
 */
function mymodule_form_user_register_form_alter(&$form, FormStateInterface $form_state) {

  $form['#validate'][] = 'mymodule_registration_validate';

}

/*
 * Custom Validation
 */
function mymodule_registration_validate(&$form, FormStateInterface $form_state) {

  $field_name = $form_state->getValue('field_name'); // Gets the value entered by the user
  // Note: depending on your field type & settings sometimes this value is an
  // array, so you may have to keep drilling down.
  if($field_name != 'Hello World') { // perform check
    $message = t('Only Hello World is allowed'); // message to display
    $form_state->setErrorByName('field_name', $message); // set error
  }

}

$form_state->setErrorByName will display an error message and highlight the offending field in red.

If you want to redirect use $form_state->setRedirectUrl($url);

3
  • 1
    I'm tempted to try to post another answer using the DEV version of the Rules module ... nevertheless: this one is not so bad either ... Jan 20, 2019 at 13:25
  • I initially thought of this, but what if I wanted to register the user but keep them blocked? In this case I think I wouldn't want to do it in validation hooks, because the validation is meant to permit or deny further form processing, right?
    – meecect
    Jan 28, 2019 at 16:01
  • @meecect Correct. That would require a totally diff aproach.
    – No Sssweat
    Jan 28, 2019 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.