2

How do I add a class to the form element of the search block form?

I mean, add a class to this element:

<form action="/search/node" method="get" id="search-block-form" accept-charset="UTF-8" data-drupal-form-fields="edit-keys"></form>

I've tried:

function mytheme_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['#attributes'] = array('class' => array('abc'));
  }
}

and

function mytheme_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['#attributes']['class'][] = 'abc';
  }
}

I've tried:

function mytheme_preprocess_form(&$variables) {
  if ($variables['element']['#form_id'] == 'search_block_form') {
    $variables['element']['#attributes'] = array('class' => array('xyz'));
  }
}

I've looked into altering core/modules/system/templates/form.html.twig, which does not look like the way to go.

I'm using the Bootstrap theme as my base.

0

you can use the prefix and suffix tag like

$variables['element']= ['#prefix' => '<div class ="abc">',
                        '#suffix' => '</div>']
0

Use a preprocess hook to add class to a specific form:

function THEME_preprocess_form(&$variables) {
  if ($variables['element']['#id'] === 'views-exposed-form-search-page-1') {
    $variables['attributes']['class'][] = 'your-custom-class';
  }
}

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.