Description
This describes how to override the default BLOCK Search Form* theme, button and features in template.php.
* The BLOCK Search Form is the search form available through 'Blocks' and it can be placed in any block region. This is DIFFERENT from the THEME Search Form (see notes below for overriding THEME Search Form.
Assumptions:
- Search Module is turned on.
- You are printing the search box from your 'Blocks' and have enabled/placed it in a region.
Drupal 7
Add the following code snippet to template.php in your theme and you can:
/**
* hook_form_FORM_ID_alter
*/
function YOURTHEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
$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']['#default_value'] = t('Search'); // Set a default value for the textfield
$form['actions']['submit']['#value'] = t('GO!'); // Change the text on the submit button
$form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/search-button.png');
// Add extra attributes to the text box
$form['search_block_form']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'Search';}";
$form['search_block_form']['#attributes']['onfocus'] = "if (this.value == 'Search') {this.value = '';}";
// Prevent user from searching the default text
$form['#attributes']['onsubmit'] = "if(this.search_block_form.value=='Search'){ alert('Please enter a search'); return false; }";
// Alternative (HTML5) placeholder attribute instead of using the javascript
$form['search_block_form']['#attributes']['placeholder'] = t('Search');
}
Note: When you copy the above snippet to an existing template.php in your theme - you need to replace YOURTHEME with the name of your theme.
You also have to pay attention to the use of the php brackets - <?php and ?>
. The first one <?php
should already be at the top of an existing template.php file and the closing one might not be useful if you later add more snippets, etc.
Alternatively and probably better practice is to add the brackets to each snippet individually - this would mean you may have to add a closing bracket ?>
to an existing template.php file before adding the above snippet.
Change drupal default search input type Format:
type="text" to type="search"
It's works well in D6 and D7:
/**
* Changes the search form to use the "search" input element of HTML5.
*/
function YOURTHEME_preprocess_search_block_form(&$vars) {
$vars['search_form'] = str_replace('type="text"', 'type="search"', $vars['search_form']);
}
This snippet goes into the template.php file of your theme. In my case it's tao, that is why the function starts with "tao_". You have to rename it to match it your theme name.
Drupal 6
Add the following code snippet to template.php 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 this site' text in the input form and make it disappear when users click in the input form
- change input form text color from #888888 (grey) to #000000 (black) when user starts typing search words in the input form
function yourtheme_preprocess_search_block_form(&$vars, $hook) {
// Modify elements of the search form
unset($vars['form']['search_block_form']['#title']);
// Set a default value for the search box
$vars['form']['search_block_form']['#value'] = t('Search this site');
// Add a custom class to the search box
// Set yourtheme.css > #search-block-form .form-text { color: #888888; }
$vars['form']['search_block_form']['#attributes'] = array(
'onblur' => "if (this.value == '') {this.value = '".$vars['form']['search_block_form']['#value']."';} this.style.color = '#888888';",
'onfocus' => "if (this.value == '".$vars['form']['search_block_form']['#value']."') {this.value = '';} this.style.color = '#000000';" );
// Modify elements of the submit button
unset($vars['form']['submit']);
// Change text on the submit button
//$vars['form']['submit']['#value'] = t('Go!');
// Change submit button into image button - NOTE: '#src' leading '/' automatically added
$vars['form']['submit']['image_button'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/search-button.png');
// 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 print entire form
$vars['search_form'] = implode($vars['search']);
}
--------------------------------------------------
(Original post kept for archive.)
Step 1 of 2
In a text editor like notepad.exe, create a file called template.php using the the following snippet. If you already have a template.php file, simply add it to your existing one.
function phptemplate_search_block_form($form) {
/**
* This snippet catches the default searchbox and looks for
* search-block-form.tpl.php file in the same folder
* which has the new layout.
*/
return _phptemplate_callback('search-block-form', array('form' => $form));
}
Upload your new/edited template.php file to your active theme folder.
Step 2 of 2
The template.php snippet catches the default search box layout before it's displayed and looks in the same folder for a search-block-form.tpl.php file which determines the new layout.
A very simple example of a search-block-form.tpl.php file maybe illustrated as follows....
for use with Drupal 4.7.x
<label for="edit[search_block_form_keys]">Search</label>
<input type="text" maxlength="128" name="edit[search_block_form_keys]" id="edit-search_block_form_keys" size="25" value="" title="Enter the terms you wish to search for." class="form-text" />
<input type="submit" name="op" value="Search" />
<input type="hidden" name="edit[form_id]" id="edit-search-block-form" value="search_block_form" />
<input type="hidden" name="edit[form_token]" id="a-unique-id" value="<?php print drupal_get_token('search_block_form'); ?>" />
Snippet updated and tested with Drupal 4.7.x Feb 24th 2007
for use with Drupal 5.x
<label for="search_block_form_keys">Custom Search</label>
<input type="text" maxlength="128" name="search_block_form_keys" id="edit-search_block_form_keys" size="25" value="" title="Enter the terms you wish to search for." class="form-text" />
<input type="submit" name="op" value="Search" />
<input type="hidden" name="form_id" id="edit-search-block-form" value="search_block_form" />
<input type="hidden" name="form_token" id="a-unique-id" value="<?php print drupal_get_token('search_block_form'); ?>" />
Snippet updated and tested with Drupal 5.x Feb 24th 2007
Note: You don't need the opening and closing form action
tags in your search-block-form.tpl.php file. Drupal automatically does that for you when it's rendering the form.
Upload your search-block-form.tpl.php file to your active theme folder.
example: changing the Search button text
Simply change the following line in the search-block-form.tpl.php snippet from this:
<input type="submit" name="op" value="Search" />
to this:
<input type="submit" name="op" value="GO!" />
Which changes the button text from "SEARCH" to "GO!". You can obviously edit the Value="GO!"
field to whatever text string you want.
example: changing the Search button to an image
This can be done using CSS, but, if you want to change the button to an image using your search-block-form.tpl.php, you can simply change the following line:
from this:
<input type="submit" name="op" value="Search" />
to this:
<input type="image" src="images/go-button.gif" name="op" value="Search" />
This replaces the SUBMIT button with an image called go-button.gif
. Edit the path and filename to suit).
Comments
The code for 5.x didn't carry
The code for 5.x didn't carry my search term to the search page.
I'm not sure exactly why... but here's the code I used that works instead.
Try not to use phptemplate in function names
Note on Step 1 above:
It's always a good idea to use your theme name as a prefix to any function names in
template.php
. This helps avoid conflicts with sub-themes. PHP will fail with an error if there are two functions with the same name; if a theme and a sub-theme both have functions with aphptemplate
prefix, your site will crash.So, step 1 should be:
(Replace YOURTHEMENAME with your theme name, in lower case.)
Note that
_phptemplate_callback
is a function call, not a function definition, so it should NOT be changed.Also, closing PHP tags are NOT recommended by Drupal coding standards. (I included the tag so this page would format the code as PHP, but I thought I should mention it just the same.)
-Karlheinz
code not processed
Adding this file as template.php (inside my theme folder), results in an ugly flash of the code before the theme loads up, leaves the code as such at the head of the page, and adds none of the desired functionality.
PHP tags?
It sounds an awful lot like you saved this file without adding the opening PHP tag. I'm assuming that your theme did not already have a
template.php
file to modify?If that's not the problem, then I'm not sure what to tell you.
-Karlheinz
You are right, my theme did
You are right, my theme did not include a 'template.php',
nor did it include a 'search-block-form.tpl.php',
I added this and was able to gain a hold of form output!
How do you change the Submit text in Drupal 7?
I used to use the method in this article for Drupal 6, but this must have changed in Drupal 7. Any ideas on what I should change the code too? Or where to look to figure it out myself?
Drupal 7 is easy!
Just add this to your theme template.php
(change YOURTHEME to your theme name)
for more information on form api check here http://api.drupal.org/api/drupal/developer--topics--forms_api_reference....
hide outline
in addition to the above code you can also dim little bit the text in the filed on focus by placing this to css:
Outlines give visual feedback
By hiding outlines from links, which is perhaps a desired thing cosmetic-wise, you make your pages hardly-accessible and unfriendly. For an hour, try to use your computer utilizing keyboard only and you'll understand.
Thanks so much
Thanks so much for that deep-silver. A real great help. Drupal 7 seems both easier and harder than 6.
Cheers
deep-silver, The above code
deep-silver,
The above code always searches for keyword "Search". Whatever keywords you enter in the search field it get replaced by "Search" on pressing the GO! button. The problem is that '$form['search_block_form']['#value'] = t('Search');' line always replaces entered keywords. If I remove that line, search functions properly, but without onblur, onfocus effects, which I really wanted to use. How this can be fixed?
change #value to #default_value
This should work
Using Deep Silver's code
Using Deep Silver's code works, but your code I get a nasty message from Drupal.
How to display search in page--front.tpl
Hi All,
Actually i have created a front page page--front.tpl and when i tried to display search box in front page it is not showing and i used the code which i got like below in template.php
But still i am not able to show this in front page. So can anybody help me...
Different template (front page)
Hi!
This code works perfect in my drupal 7 site. But now I'm having some problems because I created a different template (page--front.tpl.php) for my front page, but the search box doesn't appear at all.
What should I do to make it work in all template files I create?
Thanks!
#default_value
May want to use $form['search_block_form']['#default_value'] instead of $form['search_block_form']['#value']. The latter permanently sets the form element's value if I'm not mistaken. Thus when you search above you would always be searching for 'GO!' or 'Search' instead of the form element's value.
* neve mind somehow missed the thousands of comments above. Apologies.
Search box in sitebar similar to wibiya
I am designing a site bar similar to wibiya (or drupal taskbar), in the site bar I want to include drupal default site search box. I have searched a lot and not able to find the exact code.
Please help me, the sitebar html code is in a new block. This site bar is fixed at the bottom of your windows screen. I need the code to print the search box, user can able to search the site using this.
put search bar in a block
you have to put the search bar in the block you want on the block admin page
Diana Castillo
I have a (maybe stupid)
I have a (maybe stupid) question!
I'm trying to toggle the visibility of the label so in my template.php I put:
replacing THEMENAME with my theme obviously... but I don't know how to make the label visible. Changing invisible to "visible" just breaks it?
After some search on
After some search on http://api.drupal.org/api/drupal/developer--topics--forms_api_reference....
you can test with :
$form['search_block_form']['#title_display'] = 'after';
$form['search_block_form']['#title_display'] = 'before';
Not really clear on the new doc , it can be useful !
_________________
www.twitter.com/mngoe
Also, if you can't make the
Also, if you can't make the label show in THEME_form_alter try this:
I couldn't get this particular value to change with THEME_form_alter but the above finally did the trick.
the code bellow work
the code bellow work perfectly... but how do i add(.class or #id) or remove tags (ex: divs)... basically i want to do some theming... :)
Excellent Code
This code was helpful.
d6 version inserts no id or class into search button
The d6 version of this code (can't vouch for the others) inserts no class or id into the search image button. In fact, the image path is hard coded into html, instead of being controlled via the css- probably because there is no way to isolate that button in the css.
I need to get some kind of identifier into the image button so that I can select it, but I've been trying for hours and I have no idea how. Also, wouldn't it be in best practices to allow the search button image to be controllable through css instead of inline?
Worked like a charm in D6...
Nice. Clean. Thanks!
Drupal 6
For D6, in addition to removing (or commenting out) the image_button code, you must change the unset($vars['form']['submit']); code above the 'go!' code to include ['#value'], like so:
Hi, The code works okay, but
Hi,
The code works okay, but I'm having trouble when using an image as my search-icon. It's this piece of code that gives me trouble:
The image shows up fine, but apparently this piece of code creates an ID-tag which is empty. Because of this my pages does not validate as valid XHTML.
So how do I remove this ID-tag?
The standard form does not validate
Hello,
i'm using Drupal 6.20 and simply using the standard search form block in one of my regions. The form is rendered with an html code that does not validate:
<form action="/istc/"accept-charset="UTF-8" method="post" id="search-block-form">
I am afraid the problem is actually some rendering function as the space between two html attributes isn't added in some other occasions...
does anyone have a clue?
Sorry, i found out it was a module called "beautify" the author of this non valid code... :)
thanks!
Some changes to the D6 code
I needed to make some changes to the code to get this to work for me. The main problem I was having was that the base_path() . path_to_theme() for the image button src was pointing to the search module rather than the active theme. I have used drupal_get_path instead.
One of the other comments refers to a validation failure due to not having an id. This code fixes that as well. I have also added places for custom classes for both the search box and and the submit button.
This is working for me but if others can check the code and comment that would be great.
How do I get rid of <h2>SEARCH</h2>
the code above worked to change everything except there is still a big SEARCH above the search box , it's not the #title, that I can change . what is the name of the variable for that H2 label above?
Diana Castillo
remove search box title
I found the answer you have to write none when you configure the block title .
Diana Castillo
IE does not display the text value
Hi,
I used the code you gave to put 'OK' on my submit button with the following line:
$form['actions']['submit'] = array('#type' => 'image_button', '#value' => t('OK'));
This piece of code is doing fine in Mozilla but IE displays a blank square with a red cross in it instead of 'OK', although the generated html code is fine (
<input id="edit-submit" class="form-submit" type="image" src="http://dev-drupal/" value="OK" name="submit">
)Where does the problem come from?
Regards,
image source missing
Hi.
Just went over these posts...
--> src="http://dev-drupal/"
Are you defining a image_button without a source ?
It looks like you did not define your source path to your image. Or it is wrong.
Thats why IE comes with the cross.. He cannot find the image.
Do you want an image, or do you want only text button ?
Look on the example,it should be like these lines :
If you do not want an image, try it without the line "image_button"...
Problem solved
Hi,
Thanks for your answer but the problem did not come from the image path, it came from the fact that IE does not like the array(...) part...
Here is how I finally got what I wanted :
Note: You don't need the
What if you really need to change the form action tags? How would one do that?
- Craig Vanderlinden @cvanderlinden
Position submit button
Thanks for this tutorial. One question I have is how would I move the Search submit button to the left side of the field, rather than the right? Drupal 7.
Repositioning Submit Button
Possibly the easiest way would be to increase the weight of SEARCH_BLOCK_FORM (or decrease the weight of ACTIONS SUBMIT button). For example:
This function would be located within your theme's template.php file (or more correctly - your subtheme's template.php). You will likely also need to tweak your theme's CSS.
I hope this helps someone.
Chris Luther
advanced / refine search
I would like to make a search box similar to the one on drupal.org where you can refine the search and limit it to certain content type eg modules. Would there be a way to add php code to the template file to do this for the block search form? (I've tried to use views but I can't get one text box for all content types).
How do you align the textfield with the search button image?
How do you align the textfield with the search button image?
What parameters should I use? Or is it through CSS? The CSS doesn't seem to want to override either divs for the textfield and submit buttons.
Thank you very much!
Thank you very much!
Best regards.
image button
Hello,
I have applied the technique outlined above to add "type=image" to the button in my search form. I am using drupal 7, with zen theme. I have done a lot of CSS styling on my site.
My problem: there is some additional padding being added to the bottom of the image, so that it is not lining up properly with the text field. I have exhausted myself with firebug and searching the web. If anybody has any idea what this could be please let me know. When I look at the markup for both the image button (used in template file, copied from above) and the regular submit button they seem to be exactly the same, classes included.
thanks for the help,
James
Hi jhemsley30 , Not sure if I
Hi jhemsley30 ,
Not sure if I used the correct way but I managed to get them aligned by modifying the forms.css
.container-inline div,
.container-inline label /* Inline labels and form divs */ {
display: inline;
}
to
.container-inline div,
.container-inline label /* Inline labels and form divs */ {
display: block;
}
And then I added the following css
#edit-submit {
float:right;
margin: -50px - 35px 0 0
}
The margin depends on your image size.
If anyone has a cleaner way of doing this please share.
I used the template.php file
I used the template.php file for drupal 7 theming Seen Here, and added the following:
So now it is aligned, and looks pretty nice. Still have to hardcode it, per theme. But seems a bit easier, and won't have to fool with the negative margins in container classes w/ respect to image width.
The above could be put into a css file in the theme, and just add the respective class to the ['search_block_form'] and ['actions']['submit'] instead, but the above code was good 'nuff for myself.
how to line up submit image to search box
great, that helped! thanks
Diana Castillo
CSS customization of the search box + button
So no one has been able to figure out to do more fancy CSS3 customization of the search box? Hard coding seems counter intuitive these days.
Also
Also include:
$form['#attributes']['onsubmit'] = "if(this.search_block_form.value=='Search'){ alert('Please enter a search'); return false; }";
This prevents users from performing searches on the default text - pretty annoying when you have tons of "Search" keywords in your analytic's
What worked for me was to add
What worked for me was to add an onclick event to the button:
This prevents the form from being submitted if the search box holds the default value
Multilingual Search button
How to make it multilingual on Drupal 7 ?
This part have problem with this...
// Add extra attributes to the text box
$form['search_block_form']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'Search';}";
$form['search_block_form']['#attributes']['onfocus'] = "if (this.value == 'Search') {this.value = '';}";
// Prevent user from searching the default text
$form['#attributes']['onsubmit'] = "if(this.search_block_form.value=='Search'){ alert('Please enter a search'); return false; }";
}
FOR multilingual
FOR multilingual use
Or you can try this
Undefined index error!
Hi!
I have applied the steps to modify search form in D7. But it gives me this Notice:
Notice: Undefined index: #type in template_preprocess_search_block_form() (line 1070 of C:\wamp\www\awesomeadguy\modules\search\search.module).
Plus, the image is showing for the submit button but the submit button is also showing.
Here is my code:
Please, help!
Regards!
Solved!
I had to write:
$form ["actions"]["submit"]
Instead wrote:
$form ["action"]["submit"]
Anyhow, thanx!
FOR multilingual use
change the label/caption from “Tickets” to “Cases”
Hi Drupal community! Please help me with an urgent project that needs to be submitted within this month.
I’m using Drupal 6, custom_search-6.x-1.11, and support-6.x-1.8 for the Support Ticketing System module. I have a question about the Search block. Please let me know on how I can change the label/caption from “Tickets” to “Cases” as this is what the client wants. Screen capture: http://screencast.com/t/XfWy2qpE4
Thanks!
Alt parameter
I have a problem with W3C validation (Drupal 7)
Element input is missing required attribute alt.
How can i add the alt parameter ?
I have test :
$form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/search-button.png', '#alt' => 'myAlt');
and it's still not working
I too have this issue
I'm looking around for a solution.
I'll post a reply to this comment when I figure it out!
Got it to Validate HTML5
Ok, first off, I'm using the Framework theme version 3.6 for Drupal 7
This is what I have for my search block form located in the template.php file
I commented the two lines that addressed my validation problems with the Alt attribute and removing the value attribute.
I also saw a nice snippet to keep people from searching the default text.
I hope this helps!
Also, in using the image as button, webkit puts a cancel button on the field that makes it look weird, this CSS code will make that go away.
Thanks for the alt attribute code
Very helpful indeed - appreciate your taking the time to post this information
Is it possible to change <input> to <button>
I want to change the standard input element into the button element because the input element does not allow for CSS pseudo-elements. Everything I read is in reference to changing the attributes, but not the main element. Is this possible?
Changed the Drupal 7 code to work with multiple languages
The onblur effect didn't work in different languages, so I changed the code a bit:
I replaced:
with:
and it works fine.
Template.php
The code in template.php worked like a charm for me.
I have made a custom search
I have made a custom search block in custom module. I also made a new template to show search results. The problem is that how to render variable element in new template???
Proper 508 complant Labels for Search Block
This issue is important for 508 compliance and accessibility and doesn't seem to be resolved on the most recent Drupal core updates. I am using the standard/default search block placed into one of my theme regions. Is there a way I can place the code in template.php file to get the proper form label like the following? Looking at the code after using the snippet in my template.php, I still do not see the "label" code.
You cannot use the labels or
You cannot use the labels or other input tags directly into template.php, you should have to use hook_form_alter() for this purpose.
This was helpful. Thanks a
This was helpful. Thanks a mil!!
Since this information is
Since this information is explained here, we can put the code directly in our file. But what is the flow-chart of determining- which hook, which code I should use?
For example, If I do not have this drupal.org information page, And I decided to change the title of search box. So from literature I know, Hook is there in Drupal on api.drupal.org. But How I decide, that this particular hook I have to use for this particulate purpose. And to that this code I have to add in that.
Why I am asking this, because this all has already been defined, I am not suppose to make my own, something like I have to use this
$form['search_block_form']['#title']
only, I cannot use,$form['my_generated_name']['#something']
So, what should be my decision and thinking process, and from where shall I take all pieces and generate this?, Because all pieces has already been defined.
Customize the search block form in Drupal 8
Leaving this here In case anybody is looking for a preprocess function to customize the search block form in Drupal 8.
Customize the search block form in Drupal 8
I need your help for it to work in drupal 8.
1. Where do i place the template.php and do i need prefix with theme name, like Theme.template.php?
2. How do i increase the size of the text field?
3. I need my search bar to look like the one in gmail..where they attach a blue glyphicon next to the large search bar.Or even in youtube . Any Idea how i could achieve this? I know bootstrap just in case you may need to explain using some of those classes. Thanks in advance.
1. In Drupal 8 the template
1. In Drupal 8 the template.php file has been been replaced with a YOUR_THEME_NAME.theme file and it's placed at the root of you custom theme.
2. The text size can be increased with CSS.
3. There are couple ways you could do this, the easiest way would be with CSS. You could use a background image on the submit button and negative indent the button text so it's out of view. This is a common front-end technique that you should be able to find reference to.
Thanks for the code
@b0b