I try to add a custom css class to a form element inside my address field for e.g the postal_code field and another class to the given_name and family_name field.

I tried it with a my_theme_theme_suggestions_form_element_alter. But then I have to extend all the twig files like form-element--equal-width-column.html.twig, for just adding the css class.

function my_theme_theme_suggestions_form_element_alter(array &$suggestions, array $variables, $hook) {

  if (in_array($variables['element']['#attributes']['class']['0'], ['family-name', 'given-name'])) {
    $suggestions[] = $hook . '__equal_width_column';

Is it possible to just add a css class to specific form-elements div's, so I don't have to extend all those twig files?


1 Answer 1


You can use the hook_form_FORMID_alter in order to add classes to the fields you want to.

* Implements hook_form_FORM_ID_alter();
function hook_form_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['my_custom_field']['#attributes']['classe'][] = "my-custom-class"
  • ok but how do I find the ID and the right array's? I have to target the property fields of the Address field..
    – meez
    Dec 6, 2019 at 20:41
  • With var_dump, kint or any other debug tool I guess
    – benftwc
    Dec 10, 2019 at 13:35
  • yes I know. But with e.g. var_dump I cannot get into the address field array? In other words I can't find/debug the variables of the properties (company, given_name, family_name etc) inside the address field
    – meez
    Dec 11, 2019 at 11:41
  • var_dump isn't well designed to dump objects, use kint instead. I've told you to use var_dump on the $form_id variable, which is a string
    – benftwc
    Dec 12, 2019 at 13:11

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.