Customize Search Block Drupal 7

Public

Add the following code snippet to template.php of your theme and you can:

- change the submit button to an image
- change the text of the submit button to 'Go!' (just remove the // in front of that line of code, and delete the image_button code below it)
- add default 'Search' text in the input form and make it disappear when users click in the input form

</> CopyGet raw version
php
  1. <?php
  2. function YOURTHEME_form_alter(&$form, &$form_state, $form_id) {
  3. if ($form_id == 'search_block_form') {
  4. $form['search_block_form']['#title'] = t('Search'); // Change the text on the label element
  5. $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibilty
  6. $form['search_block_form']['#size'] = 40; // define size of the textfield
  7. $form['search_block_form']['#default_value'] = t('Search'); // Set a default value for the textfield
  8. $form['actions']['submit']['#value'] = t('GO!'); // Change the text on the submit button
  9. $form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/search-button.png');
  10.  
  11. // Use the string as a placeholder, will be hidden on focus
  12. $form['search_block_form']['#attributes'] = array(
  13. 'placeholder' => t('Search'),
  14. );
  15. // Prevent user from searching the default text
  16. $form['#attributes']['onsubmit'] = "if(this.search_block_form.value=='Search'){ alert('Please enter a search'); return false; }";
  17.  
  18. }
  19. }
  20. ?>

Comments

Ivan's picture

Javascript event as attributes? Seriously?

topas's picture

Great work! Is there a way to add alt text to the image?
thanks in advance!

BlackyWhoElse's picture

@cdykstra
Hey cool snipp but you should replace on blur and onfocuse with this

  1. $form['search_block_form']['#attributes'] = array(
  2. 'placeholder' => t('Search'),
  3. );

The reason is simple.
It takes the string and place it in the background so you can write above it.
If you type something in it will be hidden.

@topas:
You can do that with CSS by changing the background of this field.

@Ivan
Why not this is one of the simplest ways to do that and every browser will support it.