27

How can I insert search box(search block) in my theme programmatically?

39

According to your tag, you're looking for a D7 solution. The Drupal 7 page.tpl.php doesn't have the $search_box variable anymore. However you can add it in a preprocess function in your template.php:

<?php
/*
 *  Preprocess page.tpl.php to inject the $search_box variable back into D7.
 */
function MYTHEME_preprocess_page(&$variables){
  $search_box = drupal_render(drupal_get_form('search_form'));
  $variables['search_box'] = $search_box;
}

Then you just need to print the variable in your page.tpl.php:

<?php print $search_box; ?>

You could also use module_invoke, but you shouldn't have php logic in template files:

<?php
  $block = module_invoke('search', 'block_view', 'search');
  print render($block); 
?>
3
  • Thanks, Where should I place the third code block?(directly in page.tpl.php OR in template.php and then access it from page.tpl?) – Nick.h Aug 31 '11 at 9:19
  • 1
    The third block should be placed in page.tpl.php. As a shorthand you can also use: "print render(module_invoke('search', 'block_view', 'search'));" – Bala Clark Oct 18 '12 at 12:31
  • 2
    To avoid the "Strict warning: Only variables should be passed by reference in [theme-name]_preprocess_page() (line xx of [theme-name]/template.php)." warning your theme_preprocess_page should be as follows: /* * Implements theme_preprocess_page(). */ function [theme-name]_preprocess_page(&$variables){ $search_form = drupal_get_form('search_form'); $search_box = drupal_render($search_form); $variables['search_box'] = $search_box; } – kbrinner Jan 21 '16 at 18:30
7

Do it the right way instead and use the block.
Hardcoding elements inside the page.tpl, is IMHO one of the things that still floats around since the "good old days."

Use the block system instead; it gives you way more flexibility further down the road. You may also want to check out the Blockify module.

This module exposes a number of core Drupal elements as blocks.

2

You can use the $search_box variable that is available for the page.tpl.php file.

2
  • 1
    Thanks, But $search_box is removed in D7 – Nick.h Aug 31 '11 at 8:31
  • Oops, didn't notice this was about D7. – Nikola Kotur Sep 23 '11 at 15:25
1

You can also use the block system and add the search form block to the page in

Admin > Structure > Blocks : Search form

e.g to place in navigation menu, put the block in the region

"Navigation"

and then align with CSS.

e.g to put in right of navigation menu:

#navigation #block-search-form{
  position: absolute;
  right: 10px;
  top: 0;
}
1
  • This would work, but the question was referencing to a programatic solution. – timofey.com Dec 12 '14 at 13:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.