How to remove the preview button on a Drupal 8 contact form

This howto shows you 2 ways how you can easily remove the preview button from a Drupal 8 contact form (included in core).

Option 1. Use hook_form_alter()

One proposal is to utilize hook_form_alter() to strip out the preview button form element in any form. We did not test this solution, but according to the feedbacks on https://drupal.stackexchange.com it seem to work.

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, $form_state, $form_id) {

  // Look for any form provided by the contact module.
  // If you want to target a specific form you'll use the whole form ID
  // (e.g. Website feedback = 'contact_message_feedback_form').
  if (strpos($form_id, 'contact_message_') !== FALSE) {
    $form['actions']['preview']['#access'] = FALSE;
  }
}

Source: https://drupal.stackexchange.com/questions/209078/how-can-i-remove-previ...

Option 2: Modify MessageForm.php

Another not so elegant solution, because it is a hack to Drupal core, is to edit the MessageForm.php in /core/modules/contact/src.

Change:

  public function actions(array $form, FormStateInterface $form_state) {
    $elements = parent::actions($form, $form_state);
    $elements['submit']['#value'] = $this->t('Send message');
    $elements['preview'] = [
      '#type' => 'submit',
      '#value' => $this->t('Preview'),
      '#submit' => ['::submitForm', '::preview'],
    ];
    return $elements;
  }

To:

 public function actions(array $form, FormStateInterface $form_state) {
    $elements = parent::actions($form, $form_state);
    $elements['submit']['#value'] = $this->t('Send message');
    return $elements;
  }

Important note: Because it is a hack use it at your own risk. Being a hack to Drupal core might make it complicated to apply site updates , it will make it difficult for those that come after to maintain the site and you could possibly leave your site vulnerable to exploits. For us it worked perfectly and we don't see problems associated with this simple modification.

Drupal 8 work
Taxonomy: 

Drupal themes to be compared