Drupal - How to replace the search submit button with a Font Awesome character?

In order to add the new form button, I used hook_form_FORM_ID_alter in my template.theme file in my theme folder (Notice:replace ThemeName with the name of your theme in below code):

ThemeName.theme:

**
 * Replace the Search Submit Button with a Font Awesome Character.
 */
function ThemeName_form_search_block_form_alter(&$form, &$form_state) {
  $form['keys']['#attributes']['placeholder'][] = t('Search');
  $form['actions']['submit']['#value'] = html_entity_decode('');
  $form['actions']['submit']['#attributes']['class'][] = 'search-button';
}

Remeber use html_entity_decode() to parse the Unicode code.
and CSS:

.search-button input[type="submit"]{
    font-family: FontAwesome;
    color: #fff !important;
    display: inline;
    font-size: 18px;
}

  1. To convert the label to a placeholder text, you need to use hook_form_alter in your custom theme in Drupal. The form id for the search box is seach_block_form, so you can use the following code to do this:

    /**
     * Implements hook_form_alter().
     */
    function hook_form_search_block_form_alter(&$form, &$form_state) {
      $form['keys']['#attributes']['placeholder'][] = t('Search');
    }
    
  2. To change the look and feel of the search button, you can simply use CSS. What I usually do is to set the background to an the icon and use text-indent to hide the text.


I've done the following in a preprocess function to add font-awesome icons. It's a bit difficult with the search input because the only thing that identifies the search button is the label. Then hide the element with the selector .button--text in CSS.

function MYTHEME_preprocess_input(&$variables) {
  $element = &$variables['element'];
  // Ugh :(
  if ($element['#type'] === 'submit' && $element['#value']->__toString() === 'Search') {
    $variables['children'] = $element['#children'];
    $variables['children'][] = [
      '#theme' => 'html_tag',
      '#tag' => 'i',
      '#attributes' => ['class' => ['fa', 'fa-search']],
    ];
  }
}

Tags:

Forms

Search

8