0

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?

0

2 Answers 2

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"
}
4
  • 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
    – Tarto
    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
    – Tarto
    Dec 12, 2019 at 13:11
0

To get form id , create a custom module and in .module write a hook which is given below:

/**
* Implements hook_form_alter();
*/
function custom_form_form_alter(&$form, 
\Drupal\Core\Form\FormStateInterface $form_state, $form_id){
 dd($form);  
}

Then you have to go to the particular route for the form. You will find this

Form ID

Then you can follow benftwc's answer: use the hook_form_FORM_ID_alter() to add css class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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