1

I want to add a class to the <form> element on the form_id 'search_block_form'

this is my current code

function THEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
  $form['#attributes']['class'][] = 'form-inline ';

}

2 Answers 2

1

You can use the template_preprocess_form

function THEMENAME_preprocess_form(&$vars) {
  // Add class to your specific form
  if ($vars['attributes']['id'] == 'search-block-form') {
    $vars['attributes']['class'][] = 'form-inline ';
  }
}

NOTE: the preprocessor you are using adds class to the block element

4
  • I am confused about: function THEMENAME_preprocess_form(&$vars) and function THEMENAME_preprocess_form(&$variables) What is the difference?
    – brody
    Commented Mar 26, 2018 at 10:38
  • What is confusing ? ... please be more specific.
    – GiorgosK
    Commented Mar 26, 2018 at 10:41
  • $vars VS $variables
    – brody
    Commented Mar 26, 2018 at 10:42
  • 1
    Its a local variable to your function so you can name it anything you want ... but have to use the same name throughout your function
    – GiorgosK
    Commented Mar 26, 2018 at 10:54
-1

Try this code..

/*
* Implement hook_form_alter()
*/
function custom_form_search_block_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['#attributes']['class'][] = 'test';
}
1
  • hook_form_alter adds the classes to the block/wrapper element, not the form tag. hook_preprocess_form is what allows you to add attributes directly to the form tag.
    – gcalex5
    Commented Oct 6, 2020 at 13:04

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.