Originally this topic was going to be about how I have been banging my head for hours on my desk trying to figure out how to override the Drupal 6 default search box form (search-theme-form.tpl.php), but as I started to type this up I was checking old pages for information and low and behold I found the answer. So instead I decided to write a post which contained many instances of all the keywords I used when searching for the solution to this very problem in hopes that some other people will find it beneficial.

This post applies to overriding all templates of core modules in Drupal 6.

The following links are very beneficial, and are what lead to my salvation in this endeavor.
Overriding the default search box in Drupal 6.
Core templates which can be overridden.

Preamble
In Drupal's previous life, 5.x, overriding a template required a function to notify the core that you wanted to override a template file. This was where template.php came into play. In Drupal 5.x the template.php file would notify the core via a callback function and specify that 'search-theme-form' was to be overridden locally by the theme. Then you could create a file in the theme's directory named 'search-theme-form.tpl.php' and the core would read this one in instead of the default given to it by the module. You can read more about this Drupal 5 search box override. This is no longer the case! I'm sure that the developing community had good reason for not making Drupal 6 backwards-compatible with this method, and in the long run I'm sure it probably saves some processing time as well.

Basic Steps
- Copy the original file from the module's directory into your theme directory
('modules/search/search-theme-form.tpl.php' --> 'themes/wonderbread/search-theme-form.tpl.php')
- Rename the new file in your theme directory by replacing all hyphens with underscores
('search-theme-form.tpl.php' --> 'search_theme_form.tpl.php')
- Make any changes to the theme file and save it
- Rebuild your theme registry
Clear button located at "Administer > Site configuration > Performance".

That's it! And to think I wasted so much time on this...

Note: One reason I had to do this was because I needed to get rid of those starting words before the search box. A simple PHP function you can use in you newly modified search_theme_form.tpl.php file is below.

<div id="search" class="container-inline">
  <?php print str_replace('Search this site:','',$search_form);?>
</div>

Comments

xerod’s picture

It help me a lot, thanks!!

waldmeister’s picture

Yeah..its a shame i can not modify the form-array before processing, as i can do with the user_login_box....

ahsanshahzad’s picture

i agree to waldmaeister.

you may find more reliable and best way on: http://ahsangill.wordpress.com/2009/04/29/drupal-6-custom-search-box/

stongo’s picture

I get a "?" character next to the search box when using the str_replace string used above. I tried using an   like below but still get a question mark.
str_replace('Search this site:','&nbsp;',$search_form);
instead of
str_replace('Search this site:','',$search_form);

stongo’s picture

Here's a better way to remove the text "search this site:"
In template.php, add this code

<?php
// REMOVE "SEARCH THIS SITE" TEXT FROM KEYWORD SEARCH

function phptemplate_form_element($element, $value) {
  if ($element['#title'] == t('Search this site')) {
    unset($element['#title']);
  }
}
?>
WorldFallz’s picture

I'm curious about something-- is it really 'better' to evaluate every single form element on every single page to see if the title is "search this site"? I would think on a large form with lots of elements being filled out by lots of people that could have some performance implications.

===
"Give a man a fish and you feed him for a day. Teach a man to fish and you feed him for a lifetime." - Lao Tzu
"God helps those who help themselves." - Ben Franklin
"Search is your best friend." - Worldfallz

stongo’s picture

Well, firstly, that first method didn't work without leaving a "?" to the left of the input field.
But your question about the implications on performance is interesting. There's some controversy about the performance toll the drupal hook system takes on a site (see http://20bits.com/articles/4-problems-with-drupal). I'm not sure what would be considered the "cleaner" way of removing that text. Maybe I am on the wrong path as well. Anybody else weigh in on this?

jurriaanroelofs’s picture

I think this is a bad way to modify a single form element like this, iterating over all elements on your site, but I think its a brilliant idea nonetheless, because you could use this if you must use image-type submit buttons. You could use this function to look for all submit buttons that have value="submit" and change them to image type, and load submit.gif.

-------------------------------
peach from All Drupal Themes

-------------------------------
http://www.sooperthemes.com/#-Drupal-Themes

myDRU’s picture

Strangely enough, this code in template.php just removes all form elements in my complete website (checkboxes, textareas, radio buttons,... they are all gone). It is a D6 website, multilingual. I do not see why.

matt v.’s picture

A better way would be to use the preprocess functions, as explained in this codegobbler post. Something along the lines of the following should work:

/**
* Override or insert PHPTemplate variables into the search_theme_form template.
*
* @param $vars
*   A sequential array of variables to pass to the theme template.
* @param $hook
*   The name of the theme function being called (not used in this case.)
*/
function phptemplate_preprocess_search_theme_form(&$vars, $hook) {
 
  // Modify elements of the search form
  unset($vars['form']['search_theme_form']['#title']);
}

--
Drupal Theme Developer’s Cheat Sheet | 45 Screencasts to Get You Kicking Ass with Drupal

sioux2007’s picture

I do not see why, this code in my template remove all form elements and after this when i delete the code from my template I get an error that refers to this function:

warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback, 'phptemplate_form_element' was given in C:\xampp\htdocs\drupal\includes\theme.inc on line 617.

Do you have the solution?

Thanks.

lelizondo’s picture

sioux2007’s picture

Yes I use Custom_search and it is the better solution but i wanted to solve the problem that I had come to put this function and in the end I had to reinstall drupal with their modules, etc ...

Thanks.

ahsanshahzad’s picture

sorry, but it appears me so.

dianacastillo’s picture

how do I get rid of this that shows up above the search box

SEARCH

, its not the title.
for drupal 6 please.

Diana Castillo

dianacastillo’s picture

I found the answer you have to write none when you configure the block title .

Diana Castillo

darumaki’s picture

I keep getting a Fatal error: Call to undefined function _phptemplate_callback() in template.php after following the above directions.

ablemike’s picture

I didn't have to rename my file.
My search-theme-form.tpl.php is still the same name.

How does one go about getting rid of the submit button in favor of placing an image or javascript link?

--
Michael Bishop

occupant’s picture

This can be done with css. Something like:

.form-submit {
	background: url(images/button_go.png) no-repeat 0 0;
	border: none;
}

will work (although you'll probably want to add width/height/padding/etc). Then something like:

.form-submit:hover {
	border: 1px solid gray;
}

to change the hover state. This will change ALL of your submit buttons, so if you don't want that, be sure to specify which one you do want (ie. #header .form-submit to get it to only apply to buttons in the header)

btw, I didn't have to change the hyphens to underscores either.

ablemike’s picture

I want to get rid of the submit button all together.

CSS override isn't ideal.

I'd like to be able to put my own markup there. An image background would work if I didn't have to use a custom type face on the button itself.

I tried looking for "unset submit button" to no avail.

Thanks for the reply!

--
Michael Bishop

WorldFallz’s picture

perhaps this might be useful: Theming The Search Submit Button

===
"Give a man a fish and you feed him for a day.
Teach a man to fish and you feed him for a lifetime."
-- Lao Tzu
"God helps those who help themselves." -- Benjamin Franklin
"Search is your best friend." -- Worldfallz

ablemike’s picture

Thanks Word, that link is killer!
I think that is what I will do.

Still looking for a way to effect the markup of the form though.

--
Michael Bishop

WorldFallz’s picture

i just realized you're on d6-- if you go to the modules/search directory, there should be a bunch of tpl files there. Find the one that has the code you want to change, copy it to your theme's directory, and edit away. see http://drupal.org/node/190815 for more info.

===
"Give a man a fish and you feed him for a day.
Teach a man to fish and you feed him for a lifetime."
-- Lao Tzu
"God helps those who help themselves." -- Benjamin Franklin
"Search is your best friend." -- Worldfallz

ablemike’s picture

Yup. Tried that.

The tpl has:

<div class="container-inline">
  <?php print $search_form; ?>
</div>

In the comments it says in the comments

 * - $search['search_block_form']: Text input area wrapped in a div.
 * - $search['submit']: Form submit button.
 * - $search['hidden']: Hidden form elements. Used to validate forms when submitted.

The label is part of the entire ['search_block_form'].
I'd like to remove that (Doing so with the str_replace like above)

I've hard coded:

<input src="myimage.png" ..[form controls].. >

and plugged in the id of the form statically but it just feels hacky.

Also, the tpl is search-theme-form.tpl.php and not search-block-form.tpl.php.

My page.tpl.php is using:

<?php if ($search_box): ?>
 <div id="search-box">
  <?php print $search_box; ?>
 </div> <!-- /#search-box -->
<?php endif; ?>

My assumption was that it would use search-block-form.tpl.php but alas it does not.

--
Michael Bishop

WorldFallz’s picture

You can just manually code the entire form yourself-- then you can alter the markup anyway you want. These are the elements required for the form itself:

<?php
<label for="search_theme_form">Custom Search</label>
<input type="text" name="search_theme_form" id="edit-search-theme-form-l" size="25" value="" title="Enter the terms you wish to search for." class="form-text" />
<input type="submit" name="op" value="GO!"  />
<input type="hidden" name="form_id" id="edit-search-theme-form" value="search_theme_form" />
<input type="hidden" name="form_token" id="a-unique-id" value="<?php print drupal_get_token('search_theme_form'); ?>" />
?>

Then just add whatever other divs/spans/classes/ids you want. This should work in either search-block or search-theme (you just need to change the classes/ids appropriately).

===
"Give a man a fish and you feed him for a day.
Teach a man to fish and you feed him for a lifetime."
-- Lao Tzu
"God helps those who help themselves." -- Benjamin Franklin
"Search is your best friend." -- Worldfallz

STNyborg’s picture

Great simple code... I am also trying to hard code a php search box in the header of a user list view. However, I cannot get it to work properly.

Is it possible with the code to create a combine two-in-one user search looking in both user data and user profile?

Any suggestions?

BradleyT’s picture

Spent half the day yesterday and all of this morning figuring out how to get rid of the "Search this site:" text and use an image for the search button. The str_replace() methods listed in some posts worked but those are bad hacks prone to failure any time Drupal is updated.

Your code made it super easy to get rid of the text and change the submit button to an image, thanks!

search-theme-form.tpl.php

<div id="search" class="container-inline">
  <input type="text" name="search_theme_form" id="edit-search-theme-form-l" size="25" value="" title="Enter the terms you wish to search for." class="form-text" />
  <input type="image" class="form-submit" value="" id="edit-submit" name="op" src="/images/search-fp.gif"/>
  <?php
  print $search["hidden"]; 
   ?>
</div>

I kept the default $search["hidden"] just because...

marco_cruz’s picture

This is the easiest way to customise the search form.
You realy need to use print $search['hidden']; , not ["hidden"], to keep search validations working.

rikimaru0007’s picture

What is the address where I can edit these codes?
/SiteName/sites/all/modules
or
/SiteName/sites/all/themes/ThemeName

My problem is I don't have search_block_form.tpl.php in /SiteName/sites/all/themes/ThemeName
but I have an original search_block_form.tpl.php in /SiteName/modules

khaki’s picture

i also tried this method... it output the search form... but when i try to put some keyword(s), it returns nothing... what could be wrong?

darrellhq’s picture

Easy way to do this is css is simpy to use #search label {display: none;} very easy and no fiddling around with theme functions etc.

avangelist’s picture

Do you have to assign the form an action when you implement it in this way?

If you have your page.tpl for example with just $print search_box; somewhere then you lose the ability to define the search options right? So do you have to then add a form action of say /node/search ?

Web Developer
Music Photographer

webwriter’s picture

I've followed these directions and read many, many posts on this topic and still cannot get my template search to work.

When I remove search-theme-form.tpl.php, the search works correctly but doesn't line up on my page correctly.

When I add it back in, the search term does not get passed to the search form and instead loads a blank search page.

<div id="edit-search-theme-form-1-wrapper" class="form-item">
	<label for="search_theme_form_keys" class="search-labe">Search</label>
				
	<input type="text" maxlength="128" name="search_theme_form_keys" id="edit-search-theme-form-1"  size="25" value="" title="Enter the terms you wish to search for." class="form-text" />
	<input type="submit" name="op" class="form-submit" value="Go" />
<input type="hidden" name="form_id" id="edit-search-theme-form" value="search_theme_form" />
<input type="hidden" name="form_token" id="a-unique-id" value="<?php print drupal_get_token('search_theme_form'); ?>" />
</div>	

Any suggestions?

arnoldc’s picture

Does anyone know how to filter content type or category in the search_theme_box in Drupal 6?

mths’s picture

Hi, for me only copying and editing search-block-form.tpl.php worked. Also I didn't change the - to _. I'm quite new to Drupal though, should I? The developer module also gives as module suggestion 'search-block-form.tpl.php' and nothing with underscores.

Arinaya’s picture

I spent some time searching for this too, and wouldn't have thought of the str_replace trick right away (was trying to find a way to modify the raw search form array).

For anyone who is looking for a simple way to resize the search box in drupal 6 - follow the above instructions and use this code or similar:


<div class="container-inline">
  <?php print str_replace('size="15"', 'size="25"', $search_form); ?>
</div>

IMO this approach is better than hard coding the whole search form, even if you have a few attributes you wish to change. (View source of rendered search form, find the text you wish to change, and call str_replace as needed to produce the desired output.)

Anonymous’s picture

The best way to override a form in the theme layer is imho the method suggested by lullabot.

So to get rid of the title of the search form by just using your template.php, you have first identify the form you want to overide, and then, overide it. Here is the code to drop in your template.php (without the php opening and closing tags, and remember to replace 'mytheme' by your theme name):

<?php
/**
* Override of the Search Box for d6
* first, select the form ID
*/
function mytheme_theme() {
  return array(
    // The form ID.
    'search_theme_form' => array(
      // Forms always take the form argument.
      'arguments' => array('form' => NULL),
    ),
  );
}
  /**
   * Theme override for search form.
   * The function is named themename_formid.
   * more infos : http://www.lullabot.com/articles/modifying-forms-5-and-6
   * Here is where you can modify the selected form
   */
  function mytheme_search_theme_form($form) {
    // deactivate the title of the form
    unset($form['search_theme_form']['#title']);
    $output .= drupal_render($form);
    return $output;
}
?>

You could also remove the submit button by adding unset($form['submit']); to the sencond function (after the first unset).
You can change the size of the input with this : $form['search_theme_form']['#size'] = 25;
or even set a default value like this : $form['search_theme_form']['#value'] = 'search';.

And the best part, if you want a default value, and that default value disapear when typing :

$form['search_theme_form']['#value'] = 'search';
$form['search_theme_form']['#attributes'] = array('onblur' => "if (this.value == '') {this.value = 'search';}", 'onfocus' => "if (this.value == 'search') {this.value = '';}" );

Ok, this is awesome, but to make it perfect, a little bit of css magic to adapt the colors :

#edit-search-theme-form-1{
  color:#ccc;
}
#edit-search-theme-form-1:focus{
  color:#000;
}

There you go!

sources:
http://www.lullabot.com/articles/modifying-forms-5-and-6
http://www.brightcherry.co.uk/scribbles/2008/12/04/html-form-effect-remo...

____________________________________________________________

en: www.couzinhub.com
fr: www.couzinhub.com

darumaki’s picture

Now if you could repeat that in simple "don't have a clue" english, it would save me from beating my head against the wall lol.

Do we have to edit the code or just copy/past to template file. Those extras you gave where in the code are we suppose to list it.

>>>>>>>>>>>>>>>>>>>>>>>
contemplating the meaning of existence, what else would I be doing

Anonymous’s picture

So in "don't have a clue" version:

This snippets should be copy and pasted in the template.php file of your theme, and DON'T copy the php opening and closing tags. In order to make it work, you have to replace every instance of 'mytheme' by the name of your theme. For example, if your theme is called 'basic' :) you have to rename the two functions like this :

function basic_theme()... and function basic_search_theme_form($form)...

This snippet works in two steps, the first one is :

<?php

/**
* Override of the Search Box for d6
* first, select the form ID
*/
function mytheme_theme() {
  return array(
    // The form ID.
    'search_theme_form' => array(
      // Forms always take the form argument.
      'arguments' => array('form' => NULL),
    ),
  );
}

?>

Then, the second step is where you define the modifications to the search box. I commented each line so it makes more sense

<?php

  /**
  * Theme override for search form.
  * Paste this in the template.php file of your theme
  * more infos : lullabot.com/articles/modifying-forms-5-and-6
  * Here is where you can modify the selected form
  */
  
  function mytheme_search_theme_form($form) {
    
    // this line deactivate the 'search this site' label - you can change/delete this
    unset($form['search_theme_form']['#title']);
    
    // remove the submit button - you can change/delete this
    unset($form['submit']);
    
    // Change the size of the search box (you can change the value '25 to whatever you want) - you can change/delete this
    $form['search_theme_form']['#size'] = 25;
    
    // Set a default value in the search box, you can change 'search' to whatever you want - you can change/delete this
    $form['search_theme_form']['#value'] = 'search';
    // Additionnaly, hide the text when editing - you can change/delete this
    // Remember to change the value 'search' here too if you change it in the previous line
    $form['search_theme_form']['#attributes'] = array('onblur' => "if (this.value == '') {this.value = 'search';}", 'onfocus' => "if (this.value == 'search') {this.value = '';}" )
    
    // Don't change this
    $output .= drupal_render($form);
    return $output;
}


?>

Additionally, you can use a little bit of css to make the text gray when it's not active, and black when the user is typing in the search box. Copy and paste this in the css file of your theme (usually style.css)

#edit-search-theme-form-1{
  color:#ccc;
}
#edit-search-theme-form-1:focus{
  color:#000;
}

Hope this makes more sense :)

____________________________________________________________

en: www.couzinhub.com
fr: www.couzinhub.com

darumaki’s picture

I get an error message,

Parse error: syntax error, unexpected T_VARIABLE

>>>>>>>>>>>>>>>>>>>>>>>
contemplating the meaning of existence, what else would I be doing

Anonymous’s picture

Woups, my bad, forgot a semi-colon at the end of the attributes line, here it is :

(again, replace 'mytheme' by your theme name and don't copy the php opening and closing tags)

<?php

/**
* Override of the Search Box for d6
* first, select the form ID
*/
function mytheme_theme() {
  return array(
    // The form ID.
    'search_theme_form' => array(
      // Forms always take the form argument.
      'arguments' => array('form' => NULL),
    ),
  );
}

 /**
  * Theme override for search form.
  * Paste this in the template.php file of your theme
  * more infos : lullabot.com/articles/modifying-forms-5-and-6
  * Here is where you can modify the selected form
  */
 
  function mytheme_search_theme_form($form) {
   
    // this line deactivate the 'search this site' label - you can change/delete this
    unset($form['search_theme_form']['#title']);
   
    // remove the submit button - you can change/delete this
    unset($form['submit']);
   
    // Change the size of the search box (you can change the value '25 to whatever you want) - you can change/delete this
    $form['search_theme_form']['#size'] = 25;
   
    // Set a default value in the search box, you can change 'search' to whatever you want - you can change/delete this
    $form['search_theme_form']['#value'] = 'search';
    // Additionnaly, hide the text when editing - you can change/delete this
    // Remember to change the value 'search' here too if you change it in the previous line
    $form['search_theme_form']['#attributes'] = array('onblur' => "if (this.value == '') {this.value = 'search';}", 'onfocus' => "if (this.value == 'search') {this.value = '';}" );
   
    // Don't change this
    $output .= drupal_render($form);
    return $output;
}

?>

And if you're overiding the BLOCK search form and not the theme on, use this:

<?php


/**
* Override of the Search Box for d6
* first, select the form ID
*/
function mytheme_theme() {
  return array(
    // The form ID.
    'search_block_form' => array(
      // Forms always take the form argument.
      'arguments' => array('form' => NULL),
    ),
  );
}

 /**
  * Theme override for search form.
  * Paste this in the template.php file of your theme
  * more infos : lullabot.com/articles/modifying-forms-5-and-6
  * Here is where you can modify the selected form
  */
 
  function mytheme_search_block_form($form) {
   
    // this line deactivate the 'search this site' label - you can change/delete this
    unset($form['search_block_form']['#title']);
   
    // remove the submit button - you can change/delete this
    unset($form['submit']);
   
    // Change the size of the search box (you can change the value '25 to whatever you want) - you can change/delete this
    $form['search_block_form']['#size'] = 25;
   
    // Set a default value in the search box, you can change 'search' to whatever you want - you can change/delete this
    $form['search_block_form']['#value'] = 'search';
    // Additionnaly, hide the text when editing - you can change/delete this
    // Remember to change the value 'search' here too if you change it in the previous line
    $form['search_block_form']['#attributes'] = array('onblur' => "if (this.value == '') {this.value = 'search';}", 'onfocus' => "if (this.value == 'search') {this.value = '';}" );
   
    // Don't change this
    $output .= drupal_render($form);
    return $output;
}

?>

note for Katbailey: I know, javascript inline isn't the best practice... sorry!
____________________________________________________________

en: www.couzinhub.com
fr: www.couzinhub.com

jweberg’s picture

I want to use this feature in a module. In the following line instead of text 'Search...' I want to use a php variable. How would I go about this?

$form['search_block_form']['#attributes'] = array('onblur' => "if (this.value == '') {this.value = 'search';}", 'onfocus' => "if (this.value == 'search') {this.value = '';}" );
stevekerouac’s picture

This code is great, really easy to adapt. But I'd like to add some div's in there so I can get the layout perfect. In the past I've found that easier to do by using tpl.php files than adding loads of functions in template.php... Can I alter the <?php print $search_form; ?> in search-block-form.tpl.php to something else so that I can use BOTH this snippet AND search-block-form.tpl.php??

lameei’s picture

This works like charm. Actually i've got mytheme_theme() function in my template.php so i added the the following section to that func:

<?php
return array(
    // The form ID.
    'search_block_form' => array(
      // Forms always take the form argument.
      'arguments' => array('form' => NULL),
    ),
  );?>

but the mytheme_theme() function has a return value of $hooks, now my function looks like this

<?php
unction mytheme_theme(&$existing, $type, $theme, $path) {
  $hooks = zen_theme($existing, $type, $theme, $path);
   return array(
    // The form ID.
    'search_theme_form' => array(
      // Forms always take the form argument.
      'arguments' => array('form' => NULL),
    ),
  );
 
  return $hooks;
}
?>

And it works. is it OK with the code. i mean tow return values? or is there a better coding practice here?

drupalfever’s picture

I would like to suggest a little variation to the code provided by "couzinhub".

<?php
$form['search_theme_form']['#attributes'] = array(	'onblur' => "if (this.value == '') {this.value = 'search here'; this.style.color = '#ccc';}", 'onfocus' => "if (this.value == 'search here') {this.value = '';  this.style.color = '#000';}" );
?>

With this little change, there will be no need to change the style.css file.

There is another advantage for using this code variation. With the previous code, whenever the search box lost focus, the text would become gray no matter what it was. With this little code change, the text on the search box will only become gray if the text in it is the default text 'search here'.

Somebody may complain that the code now has inline CSS. But in my defense I wanted to point out that the code already had inline JavaScript! :)

aethynyc’s picture

Thanks!
[code]
print str_replace('size="15"', 'size="75"', $search_form);
[/code]

This worked perfectly, all i wanted was a longer search bar, and not have to go through all the complicated stuff like the posts below.

BoarK’s picture

Hi All,

Here's another way of doing the same thing. It's based on overriding preproccess functions. Add this function to the template.php file of your theme. Remember to remove the ...

function {theme_name}_preprocess_search_theme_form(&$variables) {
  $variables['form']['search_theme_form']['#title'] = '';
  $variables['form']['search_theme_form']['#size'] = 25;
  $variables['form']['search_theme_form']['#value'] = 'search';
  $variables['form']['search_theme_form']['#attributes'] = array('onblur' => "if (this.value == '') {this.value = 'search';}", 'onfocus' => "if (this.value == 'search') {this.value = '';}" );
  unset($variables['form']['search_theme_form']['#printed']);
  
  $variables['search']['search_theme_form'] = drupal_render($variables['form']['search_theme_form']);
  
  $variables['search_form'] = implode($variables['search']);
}

Nathan.

savvov’s picture

It's working perfectly! Drupal 6.10

kobocms’s picture

Thank you Nathan, this works best for me. I have made an update to your code snippet to work on blocks as well as adding the php variable into the javascript to eliminate the need to re-enter the same thing multiple times.

function sareen_preprocess_search_block_form(&$variables) {
  $variables['form']['search_block_form']['#title'] = '';
  $variables['form']['search_block_form']['#value'] = 'Search';
  $variables['form']['search_block_form']['#attributes'] = array('onblur' => "if (this.value == '') {this.value = '".$variables['form']['search_block_form']['#value']."';}", 'onfocus' => "if (this.value == '".$variables['form']['search_block_form']['#value']."') {this.value = '';}" );
  unset($variables['form']['search_block_form']['#printed']);
 
  $variables['search']['search_block_form'] = drupal_render($variables['form']['search_block_form']);
 
  $variables['search_form'] = implode($variables['search']);
}

Joe

doublejosh’s picture

great snippet.

jweedman’s picture

Spent about an hour on this before I found your snippet. Thanks for saving me a load of time!

-jweedman

dalegrebey’s picture

In my opinion, this is definitely the Best Practice way of doing this: http://drupal.org/node/224183#comment-1229386

...reading the comment below though, he is correct. This only works if you use your theme name theme_

Considering that I tend to re-use and re-use my code, I prefer not to use theme_ in my template.php; for most of my sites I have a site module enabled. I just moved the code into there site_preprocess_search_theme_form(&$variables) and simply include it along with whatever theme I may use.

GBain22’s picture

Hi guys,

I cant get my theme to change using any of these methods above, im using drupal 6 and the clean theme. Ive tried simple stuff like changing the div name and clearing the cache but nothing seems to be working. Anyone experienced similar?

Cheers.

Garry Bain, sdesign1
Drupal Experts

zhangx1a0’s picture

Just check this pdf doc:
http://drupal.org/files/theme_flow_6_1.pdf

It shows obviously that engineName_preprocess_hook() will be called after template_preprocess_hook(). That means in this case, the form has already been generated when it goes into engineName_preprocess_hook() which is defined in template.php. Because it's form, you cannot render it twice and expect second round overrides first round.

In this thread this one works for me. I think this is the best approach:
http://drupal.org/node/224183#comment-1223234

BoarK’s picture

xell,

It's working fine for me. I'm using Drupal 6.9 if that makes any difference.

Nathan.

stongo’s picture

If you want to want your search box to be able to filter the search by content types, modify this code as needed in page.tpl.php or possibly in search-theme-form.tpl.php (haven't tested it here).

<form action="<?php echo $base_path; ?>search/node" method="post" id="search-theme-form">
<div id="search">
      <input type="text" class="form-text" id="edit-search-theme-form-1" value="search..." size="15" onclick="this.value = ''" onblur="if (!this.value) this.value = 'search...'" name="keys" />
      <input type="submit" value="GO" name="op" title="Search" class="form-submit" alt="Search" />
      <input type="hidden" value="<?php print drupal_get_token('search_form'); ?>" name="form_token" />
      <input type="hidden" value="search_form" id="edit-search-form" name="form_id" />
      <br />
      <div class="checks">
        <input type="checkbox" name="type[ContentType1]" id="edit-content-type-1" value="ContentType1" /> ContentType1
        <input type="checkbox" name="type[ContentType2]" id="edit-content-type-2" value="ContentType2" /> ContentType2
      </div>
   </div>
</form>

You can add as many content types as you want of course. This example has no title, has a default value in the text input box of "search..." and uses the word "go" on the submit button, while displaying 2 checkboxes underneath to filter the search by those content types. Replace ContentType1 and 2 with whatever content type you want to filter by.

z33k3r’s picture

If you're not planning on having the search box be toggled per taxonomy or other variable, this is the easiest way to do it. You get exactly what you want without any fuss or overhead.

Thanks Markku!

stongo’s picture

If you just want to be able to add a simple search block for only one content type without the checks, you can throw this code in to a block with php input format. Replace ContentType1 with the machine readable name of the content type in the last hidden input field. I find this very useful for having a search box for different sections of a content heavy site.

<form action="<?php echo $base_path; ?>search/node" method="post" id="search-theme-form">
<div id="search">
      <input type="text" class="form-text" id="edit-search-theme-form-1" value="search..." size="15" onclick="this.value = ''" onblur="if (!this.value) this.value = 'search...'" name="keys" />
      <input type="submit" value="GO" name="op" title="Search" class="form-submit" alt="Search" />
      <input type="hidden" value="<?php print drupal_get_token('search_form'); ?>" name="form_token" />
      <input type="hidden" value="search_form" id="edit-search-form" name="form_id" />
      <input type="hidden" name="type[ContentType1]" id="edit-content-type-1" value="ContentType1" /> 
      </div>
   </div>
</form>
oeklesund’s picture

thanks a lot !!!
I've spend a lot of time trying to understand how overriding works, and with the different processes (according to the versions) it was very confusing. Even if not everything is perfect, it helps!

dman’s picture

This seems like a really common feature on a lot of sites, and I thought it would just be a matter of adding the selctor in hook_form_alter and the rest would just happen. Wrong. search_block and search advanced have nothing in common.

Apparently it can also be done with views etc, but I just wanted a selector added to the normal search block. NOT EASY.
But done.
My version is at : http://cvs.drupal.org/viewvc.py/drupal/contributions/sandbox/dman/search...

It may make a project unless someone points out that it's really a lot easier than I thought....

dietrying0’s picture

WOW!! You guys are awesome. I have been looking all over for this, and those links are very helpful. I do have a couple of issues that are keeping me from applying this and testing this method out. I do not have a template.php file. Of coarse I had to choose the theme (dreamy) that does not have one. Grrr... Is this still going to work for me? If so, where to I place the code? I am assuming I just need to put it in my page.tpl.php file? I dunno. Also, I am not trying to completely get ride of the "search this site" text, rather I want to place it inside of the search box, and have it disappear once you click on it. If anyone has suggestions on how to make that work, or lead me in the right direction that would be great! Right now I am working with the only other information I have found that might be of help to you guys here. I am using drupal 6.10 if that makes a difference. Thanks.

WorldFallz’s picture

There's a few of snippets on this page-- they go in different places. Read the individual comment and/or it's parents to see what goes where.

As for the template.php file-- if your theme is a phptemplate engine based theme (and most are these days) you can just create one if it doesn't exist yet.

jweberg’s picture

For those of you still having trouble. I have created a module to do this. It allows you to change the settings. It is still in dev but should be stable enough for production. Just awaiting some testing.

http://www.drupal.org/project/custom_search_box

lelizondo’s picture

subscribing

Luis

dietrying0’s picture

Nothing easier! Thanks!

jweberg’s picture

I'd like to hide the search button altogether. I want only the text box displayed and when you type in terms and hit enter it forwards to the search results.

I have tried #type hidden with no luck. Any help is appreciated.

Anonymous’s picture

Read the thread, it's already all in there

gustavson’s picture

I need to remove the space between the text box and search button.

Basically the text box and submit button "image" should be touching each other.

Is this possible? Do I need to over ride the search box and/or button?

Can anyone here help me with the code.

I'm using D6 with theme.

Thanks for any help...

z33k3r’s picture

@ Gustavson: You will be wanting to do some CSS modifications/additions to your theme's style.css file to make that happen.

@ Everybody: interested in a simple module for this type of customization, there is a new module called Custom Search Box and I have found it very helpful. It's not finished yet, but it works for most people's needs in this thread. I have implemented it quite successfully and the module will only get better as it grows older. :)
EDIT: Just saw Jweberg's post on March 19, 2009

kateashby’s picture

.form-item label
display:none;
}

Anonymous’s picture

That's a really bad way, not only you forgot to open a bracket, making your code wrong, but if you do this, you won't have any form label, not only in the search box, but in the entire site...
Be just more specific with you selector :

#search label {
  display:none;
}

And again, it is always better to remove the html from the output than hide it with CSS. Display :none; is not the best friend of search engines.

Sunshiney’s picture

I'm trying to figure out how to delete the word "search" that is directly about the Search This Site (default) [ box 4 search term] and submit button. Using the custom search module I can modify everything except the word Search which seems to be a title, e.g.

Search
search this site [ box 4 search term] submit button

It's that first "Search" I'm wanting to delete. Anybody done this? Know how? I read all of the search files in the module for search. My failure to understand php at the needed level left me empty-handed...couldn't find the text I want to be rid of.

Help?

( EDIT ... ADDITION: From Firebug, this is the code in template.php:

<div id="block-search-0" class="block block-search">
<h2>Search</h2>
<div class="content">
<form id="search-block-form" method="post" accept-charset="UTF-8" action="/">
dman’s picture

Do you mean like what happens when you enter <none> in the search block administer screen?

Sunshiney’s picture

of me. I've been so focused on the modifying the search settings through the Administer/By Module/Search/Search Settings page that I completely overlooked the search-form block configuration setting. Agggh. I'm embarrassed! I typed in on the latter page and voila, I got what I wanted. Now I have to remember, though, that I change that settinig on the search-form block configuration page while I change the search box label and default text inside the search form on the Search Settings page.

Thank you so very much for this advice!!!

dman’s picture

As usual with Drupal, it's knowing where to look...

vikramy’s picture

Well, It works when I use simply call as a block.

But when I use module_invoke, it still appears. I mean, I am trying to use this search-block using magic tabs,

Search

appears.

Any suggestions?

Anonymous’s picture

This 'search' is the title of the block, so it simply controled by thr block template (block.tpl.php).
You can create a copy of this template, and call it 'block-search-0.tpl.php' or block-search.tpl.php and in this template, remove the title.

gausarts’s picture

If one reason you need, like the original poster, is to remove or customize the label "Search this site:", drupal 6 arrived with the hidden gem on your settings.php, find and activate the last section, String overrides:

$conf['locale_custom_strings_en'] = array(
#   'forum'      => 'Discussion board',
#   '@count min' => '@count minutes',
   'Search this site' => '',
 );

Your label will be wiped out even from the source, or change it to something else. Or else use stringoverrides.module, especially if you are still on drupal 5.

Another good example is to simplify everything you imagine:

   'Create new account' => 'Join',
   'Request new password'      => 'Lost?',
   'Add new comment'      => 'Discuss',// perhaps Review
   'Comments'      => 'Discussions',
   'Post new comment'      => 'Discuss', //perhaps What do you think?
   'Submit'      => 'Post',
   'Enter the terms you wish to search for.' => 'Search my awesome site',
   'There is currently %members and %visitors online.' => '%members &amp; %visitors',
   'There are currently %members and %visitors online.' => '%members &amp; %visitors',

   'Spaces are allowed; punctuation is not allowed except for periods, hyphens, and underscores.' => '',
   'A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.' => '',

Another approach might be CSS as mentioned somewhere above or with jQuery, jquery.example plugin is the shortest way. The approach may vary depends on your intention and familiarity.

love, light n laughter

Sunshiney’s picture

Thank you Gusarats. I'm changing the Search This Site label easily by using the Custom Search Box module. It appends settings to the Search Settings page where you can leave a field box blank, for example, and remove the Search This Site verbiage, with just one click. It's a nice module.

Karlheinz’s picture

Sorry, I didn't actually see this covered above...

To simply hide items from the Search block, just include this CSS in styles.css (or another CSS file your theme includes):

/* Don't display block title */
div.block-search h2 {
    display: none;
  }

/* Don't display search label */
div.block-search label {
    display: none;
  }

/* Don't display search button */
div.block-search .form-submit {
    display: none;
  }

You could also use CSS to e.g. put a picture of a magnifying glass inside the search input.

With this method, there's no need to use function overrides or custom template files. You would not be able to change any text of course, just hide or show it.

-Karlheinz

seutje’s picture

for accessibility reasons, I'd advise you people not to str_replace the title, and not to unset the title altogether since this will either lead to an empty label or no label

labels are important to blind people and others that use a screen reader, so please do not remove them

also using display:none; causes most screen readers to entirely drop the element, therefor I'd advise you to use position:absolute;left:-9999px; or something like it, so the label is still in the document (and still considered to be in the document) without bothering any users

same goes for the text on the button, don't remove it, just use text-indent:9999px; or something

jonthomas83’s picture

seutje, I totally agree with your accessibility advice. In reference to the text on the button, using "text-indent" doesn't work on input buttons so how would I go about removing the text visually but keeping it there so that it is an aid to other users that may not be looking at the site visually?

patoux’s picture

Hi guys,

I managed to customize/theme my search box the way I wanted using mytheme_search_theme_form() function in template.php + CSS
Now I try to create a different style/CSS for my search box on a different page using the same function...Is it possible? How can I override the search form id/class tags and use my own?

Thanks in advance

valk’s picture

It's amusing how this thread grew so large!

Adding [another] search box is easy:
Just do it the 'Drupal' way.

<?php print theme_get_setting('toggle_search') ? drupal_get_form('search_theme_form') : '' ?>

Of course you may want to alter the form in yourthemename_preprocess_search_theme_form().

cosomo’s picture

I cant override the search module. And I dont know what the problem is.

I tried search_theme_form.tpl.php and also search-theme-form.tpl.php, but always the same result, the standard search form...

I would like to know, where I can search for the bug? Is it a problem of my theme (newsflash)?

WorldFallz’s picture

Go to the /modules/search directory, grab the desired tpl.php file from there, put it in your theme's subdirectory, add some distinct text to it for testing, and clear the cache (admin/settings/performance).

cosomo’s picture

That's excatly what I did, but it didn't work.

I used called the overriding file search_theme_form.tpl.php and also search-theme-form.tpl.php (in my theme directory), cleared the cache, but it didn't work.

Do I have to add phptemplate_preprocess-functions or something else?

WorldFallz’s picture

Nope, shouldn't have to. What theme are you using? If not garland, try it with garland.

cosomo’s picture

Thx for your fast answer.

Didnt work with garland....

I copied search-theme-form.tpl.php (also tried search_theme_form.tpl.php) into the theme-directory, flushed the cache (settings -> performance).

Then I reloaded http://site/search - still the same.

It would be enough to get a point, how to debug it correctly...is there somekind of debug-mode of the search-module? I

WorldFallz’s picture

AH HA! IC said the blind man ;-)

That form template is not for the search page or search block (from the template file):

 * @file search-theme-form.tpl.php
 * Default theme implementation for displaying a search form directly into the
 * theme layout. Not to be confused with the search block or the search page.

To test it in garland, go to admin/build/themes/settings/garland and check the "search box" feature of the theme, save it, and clear the cache.

cosomo’s picture

Ok. Thx WF. After hours of testing I really thought that that could be my mistake, thats why I posted, that I tried to reload the search-page ;-).

So another question: Where can I modify the search-page? That's actually the think I wanted to change ;)

WorldFallz’s picture

so we don't waste any more time, lol -- what exactly are you trying to do?

cosomo’s picture

:-)

Nothing special... I just want to add/modify some text on the search-site (/search). I tried the module custom_search but at first glance I could only change the labels/text for search boxes...

WorldFallz’s picture

It really does depend on what you want to modify. If you want to change something in the search form, you need to use hook_form_alter on the search form in a custom module. If you want to modify the results you can use the search-results.tpl.php file and if you want to modify the individual result you would use the search-result.tpl.php file. If you want to change something else in the drupal page itself, you can create a page-search.tpl.php (just copy the page.tpl.php file for your theme and alter as desired). And there's probably some other search related api goodies you can use as well.

cosomo’s picture

WF,

thanks for the answer. page-search.tpl.php is the solution I want. That's actually the thing I tried with the search-theme-form.tpl.php ;-)

WorldFallz’s picture

lol, glad we figured it out.

Wolfflow’s picture

Hi @All, I cannot avoid to chip in in this incredible post. My consideration from the point of view of a beginner should not be misunderstood considering that I'm almost 4 years on Drupal.org and tried with my modest efforts to make Drupal Documentation, easy to consult and help many user to find solution to their problems configuring Drupal. This post demonstrate how big is the love to Drupal and also how big is the fear to speak out what may irritate the great and many code and developer of Drupal.

I really understand the passion and dedication of all of them that developed Drupal, finding way to make it faster, reliable and secure but most important to develop and add many new features that reflect the modern way of implementing dynamic web sites. Though, a small piece of text Search this Site: above a search form field, coded in a core module, can cause so much discussion and action.

IMHO I naturally and instinctively think that is almost clear to almost all people using web-sites that when hovering in this field and seeing the alt text Search ... or what ever text that indicate that you can fill with your searched item the field and clicking the Search Buttom you will get a search result.

So excuse me my long chip in on this post and also for my following question to the Drupal 6 Maintainers without being able to explain why:

  • Is it really to hard to add a small piece of code to make that text disappear in the core search.module and configurable in the admin/settings/search and support and help finally the numerous web designer to gain more time for other design task?
  • I really have to stop here because there are many other really small aspects where Drupal 6 i found it would have being applied for the sake of gaining some time to go through the still heavy Drupal learning curve like per example: admin/build/modules page that is really annoying to have it open always with $collapsed => FALSE in core, and you do really have no simple solution to change that without hacking CORE. But this is off topic naturally!!

    ...and apology for, but to end, please build a team or group that may have a lot of follower and volunteers that may pay attention to this very small code proposal to make learning not a

    ... banging my head for hours on my desk trying to figure out how to override ...

    as the author process91 and many may many other went trough.

    Best Regards

    Contact me for drupal projects in English, German, Italian, Drupal Hosting Support.

    WorldFallz’s picture

    You've been a part of this community long (including being a site maintainer) to know how things work. There is no secret cabal of core developers-- all that is needed is for someone to take the time to make a patch, submit it to the drupal issue queue, and follow it up occasionally.

    Whining and complaining in forum threads doesn't get anything implemented core and never will. If someone cared enough about this to actually do something about it, instead of merely complaining, it would have been taken care of already.

    Wolfflow’s picture

    @WorldFallz

    I guess you misunderstood, as you did many times about my "Try to explain some point of views". I just toke position and tried to represent the opinion of many many many
    newbie Drupal Users. That is very evident from my chip in. I know how to hack core and also how to build small custom modules for including may many little helpfully features to make better UI for newbies. Yes you are right underlining that I was for a short time Site Maintainer on Drupal.org but I did not find enough audience for helping in the efforts of approach the Drupal.org usability as also approach those small improvements that would really help newbies to start and test intensively Drupal. I was aware that for sure I would again pointed as someone that "Whining and complaining" and I thank you for pointing it out again, this demonstrate and testify that you again misunderstood my genuine efforts to gain the attention of other user for such efforts. You can for sure follow the history of my postings on Drupal.org and may be that one Day you will understand that I always try to help and try to contribute but contribute code is really still very very difficult in this time, Drupal.org redesign, transfer from cvs to git, Drupal 7 development and some more development aspects, so I understand that it is not the right time to try to ask to join and help out and specially when I continue to be misunderstood.

    Regards

    Contact me for drupal projects in English, German, Italian, Drupal Hosting Support.

    Anonymous’s picture

    Hi all,

    After creating many callouses upon my forehead, I finally was able to get my themed search block how I wanted, and I thought I would pass on my wisdom, it was only after that I found this god-awful page. It's full of good info, but the thread of this page is worse than finding dust-mice under my bed! Bleck!

    Would anyone like to work with me to tidy this page up?

    I'm a year-old newbie to Drupal, but happy to help with documentation! I'd just like to have a veteran coder spot me to make sure I do it right.

    It seems that people have reoccurring common requests, and I thought to reorganize it based upon that.

    Something like:
    -how do I remove the search label string?
    -how do I replace the default search submit button text?
    -how do I replace the default search submit button with an image button?
    -how do I replace the default textfield string?
    -how do I learn what vars are in $search?

    Let me know!

    dman’s picture

    Please, really please, feel free to add what you think is worthwhile from here, even if just copy&paste, to a new page in the handbook, Over near http://drupal.org/node/45295 or somewhere

    ellanylea’s picture

    There is a Handbook page that summarizes how to theme the BLOCK Search Form:

    How to Customize the Block Search Form - http://drupal.org/node/154137

    yoinclude’s picture

    Thank you so much for knowlage.

    dOwen-1’s picture

    You can also use CSS to hide the label tag inside the search object.

    .class label { visibility: hidden; }

    Dan

    drupalfever’s picture

    I would like to suggest a little variation to the code provided by "couzinhub".

    $form['search_theme_form']['#attributes'] = array(	'onblur' => "if (this.value == '') {this.value = 'search here'; this.style.color = '#ccc';}", 'onfocus' => "if (this.value == 'search here') {this.value = '';  this.style.color = '#000';}" );
    

    With this little change, there will be no need to change the style.css file.

    There is another advantage for using this code variation. With the previous code, whenever the search box lost focus, the text would become gray no matter what it is. With this little code change, the text on the search box will only become gray if the text in it is the default text 'search here'.

    jpruizs’s picture

    Hi
    I was able to add and customize the search box. Now I've created a new template for my home page (page--front.tpl.php). The problem is that I can't see the search box in this template.
    When I add the following code:

    <?php if($search_box): ?>
            <?php echo $search_box; ?>
    <?php endif; ?>
    

    This error appear:

    Notice: Undefined variable: search_box in include() (line 95...

    My template code is:

    <?php
    /* Shows the search form */
    function mytheme_form_alter(&$form, &$form_state, $form_id) {
      if ($form_id == 'search_block_form') {
        $form['search_block_form']['#title'] = t('Search'); // Change the text on the label element
        $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibilty
        $form['search_block_form']['#size'] = 40;  // define size of the textfield
        $form['search_block_form']['#value'] = t('Search'); // Set a default value for the textfield
        $form['actions']['submit']['#value'] = t(''); // Change the text on the submit button
        $form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/bg-btn-seach-sup.png');
    
    // Add extra attributes to the text box
        $form['search_block_form']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'Product Search';}";
        $form['search_block_form']['#attributes']['onfocus'] = "if (this.value == 'Search') {this.value = '';}";
      }
    } 
    ?>
    

    What could I do to make the form appear in all template files?

    lelizondo’s picture

    @jpruizs be aware that you're theming two different search forms, in D6 there is a search_block and a search_box.

    Search Block is used in a block, so if you change that one you need to use the blocks administration area to display the search block. If you want to use $search_box in your template file then you need to theme Search Box.

    Perhaps a little code will make this easier to understand. The $search_box variable you use in page.tpl.php comes from:

    function template_preprocess_page(&$variables) {
     $variables['search_box']        = (theme_get_setting('toggle_search') ? drupal_get_form('search_theme_form') : '');
    }
    

    As you can see, the actual form used to display the search box is 'search_theme_form'. In D7 all this confusion is gone since $search_box is dead now. (You can still use it but you have to implement it in a preprocess_page function).

    I usually do this to theme it the $search_box

    function myetheme_preprocess_search_theme_form(&$variables) {
      // Input
      $variables['form']['search_theme_form']['#title'] = '';
      $variables['form']['search_theme_form']['#value'] = t('Search');
      $variables['form']['search_theme_form']['#attributes'] = array('onblur' => "if (this.value == '') {this.value = '".$variables['form']['search_theme_form']['#value']."';}", 'onfocus' => "if (this.value == '".$variables['form']['search_theme_form']['#value']."') {this.value = '';}" );
      unset($variables['form']['search_theme_form']['#printed']);
      
      // Button
      $variables['form']['submit']['#type'] = 'image_button';
      $variables['form']['submit']['#src'] = drupal_get_path('theme', 'mytheme') . '/images/search.png';
      $variables['form']['submit']['#attributes']['class'] = 'btn';
      $variables['form']['submit']['#prefix'] = '<div class="search-button">';
      $variables['form']['submit']['#suffix'] = '</div>';
      unset($variables['form']['submit']['#printed']);
    
      // Render the form
      $variables['search']['search_theme_form'] = drupal_render($variables['form']['search_theme_form']);
      $variables['search']['submit'] = drupal_render($variables['form']['submit']);
    
      $variables['search_form'] = implode($variables['search']);
    }
    

    As for

    Notice: Undefined variable: search_box in include() (line 95...

    maybe something like:

    <?php if(isset($search_box)) : ?>
    

    might solve the problem.

    I hope this explanation was useful and not confusing. Last thing, when in doubt, clear the cache.

    Luis

    Dripman’s picture

    my solution for D6 in template.php :

    function mytheme_search_block_form($form) {
       // print_r($form);
       unset($form['search_block_form']['#title']);
    
       return drupal_render($form);
    }