guus van de wal
Menu

Drupal 8 form styling

26 February 2023

Styling forms in Drupal 8 has changed a bit since Drupal 7 đŸ€Ż. For instance, if you'd want to alter a form you now use the YOURTHEMENAME.theme file instead of the old template.php file. For reference see: https://www.drupal.org/docs/8/theming

In this example I'd like to create a contact form (from core, admin/structure/contact/add) and call it contact.

You can now override that form by using the hook_form_FORM_ID_alter() function. The form id of this specific form would be "contact_message_contact_form" so I use a form alter to overwrite the form.

The form id can be found by using xdebug or by using kint() or devel, using the (more generic) hook_form_alter function

php

/**
 * Implements hook_form_FORM_ID_alter().
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function YOURTHEMENAME_form_contact_message_contact_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['#attributes']['class'][] = 'webform-client-form';
}
If you'd like to change the submit button from an input to a button element (for this form only) you can let Drupal know you'd like to change this specific element by using a data-attribute for instance: 

php

/**
 * Implements hook_form_FORM_ID_alter().
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function YOURTHEMENAME_form_contact_message_contact_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['#attributes']['class'][] = 'webform-client-form';
  $form['actions']['submit']['#attributes']['data-twig-suggestion'] = 'contact_submit';
}
You could then use a hook_theme_suggestions_alter to add a template for this specific submit button in twig.

php

/**
 * @param $suggestions
 * @param array $variables
 */
function YOURTHEMENAME_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];

  if (isset($element['#attributes']['data-twig-suggestion'])) {
    $suggestions[] = 'input__' . $element['#type'] . '__' . $element['#attributes']['data-twig-suggestion'];
  }
}
Then you have a new suggestion available called: input--submit--contact-submit.html.twig

twig

{#
/**
 * @file
 * Theme override for an 'input' #type form element.
 *
 * Available variables:
 * - attributes: A list of HTML attributes for the input element.
 * - children: Optional additional rendered elements.
 *
 * @see template_preprocess_input()
 */

#}

{% set classes = [
    'btn',
    'rounded',
    'form-submit'
] %}

<button{{ attributes.addClass(classes) }} />{{ "Send" | t }}</button>
Happy theming! đŸ€©