How can I add the same CSS class (form__text) to form elements in Drupal 8?


You can do it using template_preprocess_form_element something like:

use Drupal\Component\Utility\Html;
function [YOURTHEME]_preprocess_form_element(&$variables) {
  $input_types = ['search', 'textfield', 'password'];
  $type = $variables['element']['#type'] ?? NULL;
  if (in_array($type, $input_types)) {
    $variables['element']['#attributes']['class'][] = Html::cleanCssIdentifier('form__text');

Update If the below doesn’t work try the following using hook_preprocess:

 * Implements hook_preprocess().
function [YOURTHEME]_preprocess(&$variables, $hook) {
  if ($hook == 'input') {
    $variables['attributes']['class'][] = Html::cleanCssIdentifier('form__text');

To exclude submit button ?
change the condition to $hook == 'input' && $variables['element']['#type'] !== 'submit' instead of $hook == 'input'

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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