Customizing Search Block Form in Drupal 6.0
ardarvin - March 11, 2008 - 17:02
I'm wondering if anyone has customized their search block form in Drupal 6.0 yet, and if so...could they provide sample code of what they did.
I know about this article: http://drupal.org/node/154137
...but I'm not sure if it'll work for drupal 6.0

Nope...the code from the
Nope...the code from the aforementioned doc didn't work in Drupal 6.
Anyone?
take a look at a d6 theme already doing it..
there are several themes for d6 with search built into header (for example) - i think 'internet center' (or something like that) has it in upper right...but i know that several do it - perhaps visit their code and see what they're calling. my guess is that the field name was changed for d6 and a simple edit will fix it...
I've found a couple themes
I've found a couple themes that use CSS to change the look of the search block, but nobody who is actually changing the search template.
I did some research and came up with this:
Make a search-block-form.tpl.php file in the theme directory, based off the one found in the drupal core. In the comments of the core file they state:
* Available variables:
* - $search_form: The complete search form ready for print.
* - $search: Array of keyed search elements. Can be used to print each form
* element separately.
*
* Default keys within $search:
* - $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, in the custom theme template.php, I make the following function:
function mytheme_preprocess_search_block_form(&$variables) {
$variables['search']['some key'] = "some value";
....
}
Unfortunately I have no idea what all the $search[] keys are, or what their values can/should be.
How do I go about seeing the contents of this variable, or any drupal variables in general?
Again, in the search-block-form.tpl.php core file it states:
* To check for all available data within $search, use the code below.
*
*
<?phpprint '<pre>'. check_plain(print_r($search, 1)) .'</pre>';
?>
Only I'm not sure where to put this code to display the data.
Sorry, I'm new to drupal / php...just trying to figure this out, and ultimately change the "submit" button to a custom icon.
How I changed the Search Box in Drupal 6
ardarvin - you are on the right track.
Here's what I did:
1. copy search-theme-form.tpl.php from the core into my theme directory
2. Ran this (see notes in search-theme-form.tpl.php) to see what was available:
<?phpprint '<pre>'. check_plain(print_r($search, 1)) .'</pre>';
?>
3. In theme copy of search-theme-form.tpl.php, removed
<div id="search" class="container-inline"><?php print $search_form; ?>
</div>
and replaced it with
<div id="search" class="container-inline">
<?php
/* remove ' this site' - probably should try more surefire way using </label> */
$search["search_theme_form"]= str_replace(" this site", "", $search["search_theme_form"]);
/* Replace button input type with image */
$search["submit"]=str_replace('input type="submit"', 'input type="image" src="yoursite-path-to-your-search.png" ', $search["submit"]);
print $search["search_theme_form"];
print $search["submit"];
print $search["hidden"];
?>
</div>
Notes:
1. At first glance, it looks easier to just hardcode the changes to $search["submit"] and $search["search_theme_form"] but each instance of the search form gets a unique ID - naturally. More than one instance usually occur after the first search.
2. Obviously, you need to put in the correct image src to find your search image
3. I have decades of programming experience, but little in Drupal/PHP so this fix may not be Druapesque.
Kayaker
________________________________________________________________
Aweigh - not all who wander are lost.
http://www.aweigh.com
Yup, that code works.
Yup, that code works. Thanks.
I've added default text to the search field:
$search["search_theme_form"] = str_replace('value=""', 'value="Search mysite.com"', $search["search_theme_form"]);
However I'd like to add some javascript to get the text to disappear when a user clicks on it, as explained at: http://www.yourhtmlsource.com/forms/clearingdefaulttext.html
I've added the *.js files (as provided from the above link) into my theme directory, with a slight mod so the script searches for the "form-text" class, as opposed to the "cleardefault" class.
I've added the lines:
To the head of the page.tpl.php page.
However, I can't get it to work. Any suggestions?
btw, did you see the safari search module for d6?
it puts rounded corners on the search box according the to =search tag (changes it) works in safari, IE, ff, etc...
So I got the javascript to
So I got the javascript to work...I just needed to absolutely link to the files in the head.
ie:
<script type="text/javascript" src="http://mysite/themes/mytheme/util-functions.js"></script><script type="text/javascript" src="http://mysite/themes/mytheme/clear-default-text.js"></script>
Using str_replace to alter
Using str_replace to alter the vars seems to be setting things up for a failure if Drupal should ever change the default values of things.
Does anyone know how to hard code the vars, i.e. what their full values should be?
$vars['search']['search_block_form'] = ???
$vars['search']['submit'] = ???
Modifying Forms
I find a great article about modifiying forms:
http://www.lullabot.com/articles/modifying-forms-5-and-6
I updated the code you had
I updated the code you had (which works great, THANK YOU!) with a changed line to simply replace the "Search" string on the submit button to just "Go!" below.. And I left the image replacement technique code you have in there just commented out so that people in the future can pick and choose either method easily. This template will definitely be going in my Drupal theming code snippets...
-=- christopher
<div id="search" class="container-inline">
<?php
// * Remove "Search this site: " * ////
$search["search_theme_form"]= str_replace("Search this site: ", "", $search["search_theme_form"]);
// * Replace button input type with image * ////
// $search["submit"]=str_replace('input type="submit"', 'input type="image" src="yoursite-path-to-your-search.png" ', $search["submit"]);
// * "Search" button with "Go!" * ////
$search["submit"]=str_replace('value="Search"', 'value="Go!"', $search["submit"]);
print $search["search_theme_form"];
print $search["submit"];
print $search["hidden"];
?>
</div>
I too am a Drupal newb, but
I too am a Drupal newb, but no stranger to programming. Before beginning, I read almost all of the theming documentation on the site. After reading countless worthless responses about going to this page (http://drupal.org/node/173880) to find the solution, I had almost given up on trying to figure out the "Drupal way" to change the "Search this site:" (and also the "Read more") default text. I found the point of origination for the text easily enough (TextMate -> Find in Project), but figuring out how to override the functions that house the text was beyond me. It seemed like the Drupal way of doing things would necessitate copying the original function into my theme's template.php file, then renaming with greater specificity to override. I know the home for "Search this site" is search_box() in search.module, and likewise for "Read more" in node_link() in node.module. But, as these functions don't begin with theme_, I couldn't figure out any way to override them directly.
All that to say, you're simple use of str_replace() has saved me from insanity (I was moments from just throwing my hands up and changing the text in core). I am appalled that a seemingly simple operation (changing basic, persistent text across one's entire website) requires such a roundabout solution. If anyone can share the proper, "Drupalesque" solution to this issue, please do tell. Otherwise, it's str_replace() for now...
BTW, a simpler, though not as foolproof, way of making the change is to run the str_replace() directly on the $search_form (since it's just a big string anyway). That way you don't have to break down the search array and mess with printing the individual parts. Obviously, this can cause trouble though if you want to replace something generic that may show up in more instances than your desired target.
How I used your method to change the "Search this site:" text:
<?php
/* edit 'this site:' */
$tweaked_search_form = str_replace("this site:", "name of site", $search_form);
print $tweaked_search_form;
?>
And also, in the same manner, for "Read more":
<?php if ($links): ?>
<?php
/* edit 'Read more' */
$tweaked_links = str_replace("Read more", "[ more... ]", $links);
?>
<div class="links"><?php print $tweaked_links; ?></div>
<?php endif; ?>
Hope that helps someone as much as you've helped me. And maybe we can find the "Drupal" answer to this, if there is one, sooner or later...
Replace Multi Lingual String
I use the follow Code to replace a Multi Lingual String;
<?php
$search["search_theme_form"]= str_replace(t('Search this site').':', "<you new stringt or leave it blank for none>", $search["search_theme_form"]);
...
...
?>
Can you give me the code
Can you give me the code that needs to go in template.php please?
Thanks!
Thanks a lot - the code works fine!
.
.
It works.
Many thanks to Kayaker.
One thing needs to be mentioned: You NEED to clear the cached data (admin->site configuration->permance). It wasted more than hour before I realized this.
Brandon
The simplest "Drupal" way I found
I was looking to change the "Search this site" and discovered the simplest thing was to create this function in my theme's template.php file. I referenced that lullabot article mentioned above to find this.
/**
* Override the search block form so we can change the label
* @return
* @param $form Object
*/
function phptemplate_search_block_form($form) {
$output = '';
// the search_block_form element is the search's text field, it also happens to be the form id, so can be confusing
$form['search_block_form']['#title'] = t('some crazy search title');
$output .= drupal_render($form);
return $output;
}
Using preprocess functions...
As you pointed out in a later comment, this actually replaces the use of the search-block-form.tpl.php file. A better way IMHO is to use the preprocess function mechanism newly introduced in D6: A preprocess function can be put in template.php and is able to modify template variables before they are passed into the template files. In this case, one would modify the form structure of the search box and then re-render the html. The above example would then become
/**
* Override or insert PHPTemplate variables into the search_block_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_block_form(&$vars, $hook) {
// Modify elements of the search form
$vars['form']['search_block_form']['#title'] = t('some crazy search title');
// Rebuild the rendered version (search form only, rest remains unchanged)
unset($vars['form']['search_block_form']['#printed']);
$vars['search']['search_block_form'] = drupal_render($vars['form']['search_block_form']);
// Collect all form elements to make it easier to print the whole form.
$vars['search_form'] = implode($vars['search']);
}
A local copy (in the same directory of template.php) of the search-block-form.tpl.php must also be provided, even if it isn't different from the one in the core distribution; otherwise the preprocess function isn't executed.
I've tried your method here
I've tried your method here and have moved the search-block-form.tpl.php from the core module to my local theme directory. I've added the preprocess function as well to template.php, yet I'm still seeing no changes on the site. It continues to use the default "Search this site" search block?
Any ideas? This is DP 6.4
Doing it on Drupal 6 for the search_theme_form
Thanks for sharing Marquardt. I needed to change the title of the input text of the search form for the search_theme_form, that's the one added by the theme, not the block, and used this in my template.php:
function phptemplate_preprocess_search_theme_form(&$variables) {$variables['form']['search_theme_form']['#title'] = t('some crazy search title');
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']);
}
I'm using $variables instead of $vars because that's how is called in all contributed modules and core but anyway, it's just the same variable that is passed by reference.
Also, if you want to completely get rid of the title (that's the label in your HTML) replace the first line of the function above with this:
unset($variables['form']['search_theme_form']['#title']);For everybody else, don't forget clearing your theme registry at /admin/settings/performance after adding a preprocess function in your theme.
Also you need to copy search-theme-form.tpl.php from /modules/search to your theme directory.
Alexis Bellido
Ventanazul: web development and Internet business consulting shouldn't be boring
Issues with preprocess
I tried the preprocess function in Drupal 6.6, and ran into an issue. I started out using the examples here, and first just tried changing the title to make sure I got everything right. After clearing cached data, I found that I had indeed successfully changed my title attribute. However, when I actually performed a search, I got unexpected results - namely, a blank, white screen. Does anyone know why this might have happened? Note that I'm trying (hard) to alter the *theme* search box, not the *block* search box. Does this matter?
Also, I read another comment about using form_alter, but one comment said this was not for themes, but for modules only. Is that right? If so, is it possible to replace my theme's search box with my own module? This method is probably overly complex for a simple change to the theme's search box, but I wanted to check anyway.
How to change Value of Submit Button
Can you tell me please how to change the default text of submit button ("Search").
Like "Find" instead of "Search" on button.
Changing the class?
I went with this method, not as simple as the 'display: none' style choice, but it was a chance to learn something new at any rate, so this was much appreciated.
I'd like to take it a step further, and it seems like I might be able to continue to leverage the preprocess function to do it, but I'm not exactly sure how to get a handle on all the available elements of search_block_form.
Specifically, I'd like to change the 'class' name of the search button element. I suppose I could create a style for 'form-submit' that matches an existing style, but I thought a more elegant solution would be to preprocess the search form(s) so their submit buttons used my style, and then I'd only have to update that style one time if it ever needed to change.
Thoughts on how I might go after that using the preprocess method?
Update: I figured it out, with a bit of stepping through some arrays and perusing the API. This is what the inside of my preprocess function looks like.
// Modify elements of the search form
//$vars['form']['search_block_form']['#title'] = t('replaced search title');
$vars['form']['search_block_form']['#title'] = t('');
$vars['form']['submit']['#attributes'] = array('class' => 'search_btn');
// Rebuild the rendered version (search form only, rest remains unchanged)
unset($vars['form']['search_block_form']['#printed']);
$vars['search']['search_block_form'] = drupal_render($vars['form']['search_block_form']);
// Rebuild the rendered version (submit button, rest remains unchanged)
unset($vars['form']['submit']['#printed']);
$vars['search']['submit'] = drupal_render($vars['form']['submit']);
// Collect all form elements to make it easier to print the whole form.
$vars['search_form'] = implode($vars['search']);
Simple way?
I just went into modules/search.module and edited the string output to suit my needs. What would be so wrong about that?
security issues? works fine on my page.
I was just offering the "Drupal way," but I found a better way
Your way works fine, but changing the core modules is not recommended as discussed earlier in this thread. If you go to update your Drupal version, that change will get wiped out.
However, I also just ran into some problems with my way, it overrides the whole .tpl.php file, so any other markup has to be duplicated in the function too.
But, I was just pointed to the stringoverrides module and am switching to use it instead of the function:
http://www.lullabot.com/articles/replace-any-string-drupal-5-6-without-l...
Definitely recommend that for replacing strings easily.
string override
lullabot.com offers some great advice on various drupal topics. I'm still going to use the non-drupal way :)
String Overrides
String Overrides
http://drupal.org/project/stringoverrides
----
Darly
Drupal 6: how to remove "Search this site"
Go to: /modules/search/search.module
Edit out the line "Search this site" from the below the lines:
function search_box(&$form_state, $form_id)
Search this site
@ allanx, you are creating your own version of Drupal thru this process. NOT recommended.
----
Darly
Not really affecting the code
Just removing the text.
eg:
function search_box(&$form_state, $form_id) {
$form[$form_id] = array(
'#title' => t('Search this site'),
function search_box(&$form_state, $form_id) {
$form[$form_id] = array(
'#title' => t(''),
Doesn't seem to affect the function, just the text displayed in the search block.
cheers
allanx
Not really affecting the code
yes! But remember to change the line again if planning to upgrade to a new version later. Actually changing core files would require submitting a patch for that module.
----
Darly
Why not just 'style' it away
#search-block-form label{
visibility: hidden;
}
I believe it's the only label used in that block.
EDIT: Actually, this is not a great solution. the tag can still cause some styling problems. It may be a quick fix for some though.
display: none to "style it away"
#topbar label,#topbar #edit-submit,
#topbar #edit-submit-1,
#topbar #edit-submit-2
{
display: none;
}
(of course replace or omit
#topbarsince this is special to my theme). This also removes any label in the topbar region plus all submit buttons. Also there isdiv#edit-search-block-form-1-wrapper label {}to get this very label tag "Search this site:".You can play around with it but the important bit is using
display: none;instead ofvisibility: hidden;since the later reserves space even though it's not been shown but the former doesn't even reserve space in browser's view port.Btw. thanks all you people for advices on the D6 way of creating once own search form!
P.S. I you use Opera 9.5 go to Tools -> Advanced ->Developer Tools a.k.a. Dragonfly; ng web developer (read: "themers") tool (and yes, I'm familiar with Firebug and Web Developer extensions to firefox).
Much better
Sheesh-> /me such a noob. thanks thomas. This gets my vote as the best way to omit the label until the label becomes a module configurable item. (not that it needs to be)
thanks, this worked
this worked great, thanks jackreacher
Different template name with kayaker's method
Using the template overwrite method I had to use a different file name, search-block-form.tpl.php
as documented here:
http://api.drupal.org/api/file/modules/search/search-block-form.tpl.php/6
And update all references from search_theme_form to search_block_form
<?php
/* remove ' this site' - probably should try more surefire way using </label> */
$search["search_block_form"]= str_replace("Search this site:", "", $search["search_block_form"]);
/* Replace button input type with image */
$search["submit"]=str_replace('input type="submit"', 'input type="image" src="/search.gif" ', $search["submit"]);
print $search["search_block_form"];
print $search["submit"];
print $search["hidden"];
?>
Form Alter?
Guys, I'm not sure what the problem is. Can't you do this with a simple form alter in 6.0?
Ie, to change the title from 'Search this site' to 'Search' on the search_theme_form for example:
<?php
/**
* Implementation of hook_form_alter().
*
* The function is named search_form_alter.
*/
function search_form_alter(&$form, $form_state, $form_id) {
switch ($form_id) {
case 'search_theme_form':
$form['search_theme_form']['#title'] = t('Search');
break;
}
}
?>
The Drupal Way (tm)
Using hook_form_alter is The Drupal Way to change your search form, IMO.
To do so, create your own module and define your own function mymodule_form_alter() with the sample code that denizengt posted. A few important notes:
function mymodule_form_alter(&$form, $form_state, $form_id) {switch ($form_id) {
case 'search_theme_form':
$form['submit']['#value'] = 'Go';
break;
}
}
Brandon
Brandon Bowersox
brandon@ojctech.com
OJC Technologies, Inc.
www.ojctech.com, 217.344-0444 ext. 14
also nice to have is the
also nice to have is the jQuery 'example' plugin where we can add a default value to the search box which will then react on focus (removing the default value). you must have jquery-plugins module and the jquery.example plugin (which has to be dropped into the jquery_plugin directory): then you add the plugin and define the preprocess as follows:
jquery_plugin_add('example');
// ...
function phptemplate_preprocess_search_block_form(&$variables) {
// delete title and use jquery for default value
unset($variables['form']['search_block_form']['#title']);
drupal_add_js('$(document).ready(function(){ $("#edit-search-block-form-1").example("keyword search"); });', 'inline');
// apply
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']);
}
Multilingual version
Thanks to all of you. Here you are the multilingual version of the same code:
<?php
/* Remove "Search this site: " */
$prefix_string = 'Search this site';
$transl_prefix_string = t($prefix_string). ':';
$search['new_search_theme_form'] = str_replace($transl_prefix_string, "", $search["search_theme_form"]);
/* Replace button input type with image */
// $search["submit"]=str_replace('input type="submit"', 'input type="image" src="yoursite-path-to-your-search.png" ', $search["submit"]);
/* "Search" button with "Find" */
//$search['submit'] = str_replace('value="Search"', 'value="Find"', $search["submit"]);
print $search['new_search_theme_form'];
print $search['submit'];
print $search['hidden'];
?>
I've only set it to the "Search this site" string. If you wish changing the rest take the same path :-)
I just open search.module and
I just open search.module and removed the title search this site... worked perfectly...
Yes it does, but then you'll
Yes it does, but then you'll have to re-do it every time you upgrade Drupal. It is generally not recommended to alter the core code because of this.
The Drupal Way™ of doing this simpel label remover is ridiculously complicated, so I'll just stick with the display:none way.
when multiligual
$search['submit'] = str_replace('value="'. t('Search') .'"', 'value="'. t('Find') .'"', $search["submit"]);
Thanks people...
This code works!!!
Step by step example
My way of doing that is big, it works and is highly configurable though.
What I did was:
I will give all the code you need with comments. By commenting/uncommenting some lines you can vary between all these features.
Ok, now step by step explanation:
.
1. Preparing files
Necessary step.
Make sure you have 'template.php' file in your theme directory. If not - create one.
Copy 'search-theme-form.tpl.php' file to yout theme directory (usualy from '/modules/search').
.
2. Preparing javascript
Not necessary step, unless you want some js funcionality.
In this case I use http://www.yourhtmlsource.com/forms/clearingdefaulttext.html#theJavascript to make default value of search field dissapear when user focuses input field. You can download both needed files from the link above ('util-functions.js' and 'clear-default-text.js'). This js needs class 'cleardefault' to be added to wanted input field (we'll do that later in template.php file).
now we upload both .js files to /mytheme/js/ folder and load them in mytheme.info file:
scripts[] = js/util-functions.jsscripts[] = js/clear-default-text.js
.
3. template.php file
Necessary step.
Add this function to your template.php file:
<?php
/**
* Override or insert PHPTemplate variables into the search_theme_form template.
*
* @param $variables
*/
function phptemplate_preprocess_search_theme_form(&$variables) {
/**
* Changes to submit button
*/
// change submit button's text
$variables['form']['submit']['#value'] = t('Go!');
// define path to image which replaces submit button
$search_icon = base_path() . path_to_theme() .'/images/search-icon.gif';
// add 'src' attribute to submit button
$variables['form']['submit']['#attributes'] = array('src' => $search_icon);
// change submit input type. Line below does not work! instead I added changes to 'search-theme-form.tpl.php' file
// $variables['form']['submit']['#type'] = 'image';
// rebuild the rendered version (submit button, rest remains unchanged)
unset($variables['form']['submit']['#printed']);
$variables['search']['submit'] = drupal_render($variables['form']['submit']);
/**
* Changes to input field and it's label (title)
*/
// add default value to input field
$variables['form']['search_theme_form']['#value'] = t('Search...');
// add class name to input field so javascript could deal with it (javascript loaded in mytheme.info)
$variables['form']['search_theme_form']['#attributes'] = array('class' => 'cleardefault');
// change label (title) of input field
// $variables['form']['search_theme_form']['#title'] = t('some crazy search title');
// remove label (title) of input field
unset($variables['form']['search_theme_form']['#title']);
// rebuild the rendered version (search form, rest remains unchanged)
unset($variables['form']['search_theme_form']['#printed']);
$variables['search']['search_theme_form'] = drupal_render($variables['form']['search_theme_form']);
/**
* Additional
*/
// collect all form elements to make it easier to print the whole form.
$variables['search_form'] = implode($variables['search']);
}
?>
.
4. search-theme-form.tpl.php file
Not necessary step, unless you want to change submit button to custom image.
Replace code in your search-theme-form.tpl.php file with this one:
<div id="search" class="container-inline">
<?php
// change submit input type.
$search_form = str_replace('type="submit"', 'type="image"', $search_form);
print $search_form;
?>
</div>
Custom image already defined in template.php file.
.
5. Input field style
Not necessesary at all.
If you want to customize border of your input field edit your .css file. In my case it looks like:
#wrapper #container #header #header-top #search input.form-text {border: 1px solid #bebebe;
}
.
6. Notes
Please pay attention.
First of all thanks for many of you who commented above - I used a lot of your code :)
To configure everything read carefully comments in template.php file - it just looks big actualy its really simple. Experiment a little and you'll get the result you want.
Sorry for my english .)
and if you noticed any errors or have an improvement - share it with others below!
Removing only the wrapper DIVs
Ho to all
considering all above...
How to remove ONLY the wrapper DIV inside the FORM Tag, using template.php...??
These are the rendered DIV by a
<?phpprint $search_box
?>
<div><div id="search" class="container-inline">
<div class="form-item" id="edit-search-theme-form-1-wrapper">
How can I "destroy" them permanetly? ;)
I need Only FORM + LABEL + INPUT(s) TAGS without unusefull, nasty container!
Thanks!
Bye!
Done
Done this:
<?php
$search["search_theme_form"]=str_replace('value=""', 'value="Search..." onblur="setTimeout(\'closeResults()\',2000); if (this.value == \'\') {this.value = \'\';}" onfocus="if (this.value == \'Search...\') {this.value = \'\';}" ', $search["search_theme_form"]);
?>
Mohd Sakib
http://www.worthapost.com/
Email & GTalk - sakib.live [at] gmail.com
YIM - mohd.sakib
AOL - mohd.sakib