Drupal 8 : Webform alter change fields labels, hiding fields, custom validate and submit with example

In Drupal we can alter a form using the HOOK, hook_form_alter(). Webforms are used to create forms in interfaces. We can alter webform using hook_form_alter to change field types, label and custom validate or submit for our purposes. The below example will show editing the webform fields and adding custom validate.

Sample Code: 

/**
 * Implements hook_form_alter().
 */
function example_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#form_id'] == 'webform_submission_example_form') {
    // Adding prefix and suffix to the form.
    $form['elements']['name']['#prefix'] = '<div class="example-wrapper">';
    $form['elements']['name']['#suffix'] = '</div>';
 
    // Changing label text.
    $form['elements']['email']['#title'] = 'Enter valid Email';
 
    // Hiding Age field.
    unset($form['elements']['age']);
 
    // Changing default 'Submit' to 'Save'
    $form['actions']['submit']['#value'] = 'Save';
 
    // Custom validate.
    $form['actions']['#validate'] = 'example_webform_example_form_custom_validate';
 
    // Custom submit.
    $form['actions']['#validate'] = 'example_webform_example_form_custom_submit';
  }
}
Category: