Advanced Search within a Vocab / node type

SparkyUK - June 12, 2006 - 09:56

I would like to set up a node specific search within my site. All content in this node also have a specific vocab. If I go to the advanced search page I see it makes the search by simply adding type:samplenodetype to the search term.

If I just want to add ta simple search to my page I see from the boards that I add this code

<?php
  $block
= module_invoke('search', 'block', 'view', 0);
 
$output = $block['content'];
  print
$output;
?>

Is there a way to prepopulate the field to include a type:bookreview, or even better to have this hidden.

As a side note, I will be removing the advanced search option from the search page as well as I don't want the user to see all my tax terms.

thanks

duplicate search module

SparkyUK - June 12, 2006 - 14:44

or perhaps is there a way to do this by duplicating the search module - "searchnode" for instance - where this setting is embedded?

Any Progress?

emackn - June 26, 2006 - 14:26

I'm also looking to do a node type specific search. I think the only way to do this is by using a bare bones advanced search instead of trying to make the basic search take more parameters. At least thats what I'm gonna try next ;)

I would like

Rosamunda - July 1, 2006 - 03:16

To know how to do that too!

I need the same as you´ve say here.... hope somebody can give us a clue about how to configure it :-)

Rosamunda

Anyone?

Rosamunda - July 6, 2006 - 03:29

:´-(

Tweaking Normal Search to search by Node type

emackn - July 6, 2006 - 19:49

Create a module with the following

<?php

function yourModuleName_custom_form_alter($form_id, &$form) {
   
// only alter content_seach_form
   
if(strpos(request_uri(), 'path_to_form') !== false && $form_id == 'content_search_form'){
       
// for me, path_to_form was the url of the page contiaing my search block.
       
$content_type = 'content_type_to_filter_on';
       
$form['content-type']= array(
               
'#value' => $content_type,
               
'#type' => 'hidden');
       
$form['#validate'] = array('content_search_form_validate' => array());
       
$form['#submit'] = array('content_search_form_submit' => array());
    }
}

/**
* Drupal calls this processing.. but all we are doing is building the
* search url to only look for a certain content type.
* The module name is not prefixed to the function, this name has to match
* the name set as the #validate function on $form
*/
function content_search_form_submit($form_id, $form_values){
   return
"/search/node/" . $form_values['content_search_form_keys'] .
           
"+type:" . $form_values['content-type'];

}
?>

Then I called this from my search block

<?php
print search_box('content_search_form');
?>

Your results should come out looking just like you did an advanced search with the search box containing "any keywords" and "type:some_content_type" as the final argument.

Hope this helps.

It helps a lot indeed!

Rosamunda - July 6, 2006 - 22:02

Thank you VERY much emackn!!
I´m gonna implement it RIGHT NOW!
Thanks!!!!!!!!!!!!!!!!!!!!!!!!!!

Rosamunda
Buenos Aires | Argentina
www.ligadelconsorcista.org

error...

Rosamunda - July 7, 2006 - 22:05

chuif!
Fatal error: Call to undefined function: search_box() in /home/rosamunda/public_html/drupal/includes/common.inc(1158) : eval()'d code on line 2

I´ve installed this on a test server, but I cannot enter to the "blocks" menu to undo that...

search.module enabled?

emackn - July 10, 2006 - 19:59

try /admin/modules

Also make sure the access rights are set correctly if you are using a different user other than admin (user 1).

thanks you - I'm not implementing this right though

SparkyUK - July 10, 2006 - 16:41

Hi,

thanks for this. I see in my very limited php knowledge what you are making the code do, but I think I am missing something when I implement it. I wasn't quite sure what some of your commetns meant.

Here is my new module "searchlibrary.module".

<?php
function searchlibrary_custom_form_alter($form_id, &$form) {
   
// only alter content_seach_form
   
if(strpos(request_uri(), 'node/9') !== false && $form_id == 'content_search_form'){
       
// for me, path_to_form was the url of the page contiaing my search block.
       
$content_type = 'bookreview';
       
$form['content-type']= array(
               
'#value' => $content_type,
               
'#type' => 'hidden');
       
$form['#validate'] = array('content_search_form_validate' => array());
       
$form['#submit'] = array('content_search_form_submit' => array());
    }
}

/**
* Drupal calls this processing.. but all we are doing is building the
* search url to only look for a certain content type.
* The module name is not prefixed to the function, this name has to match
* the name set as the #validate function on $form
*/
function content_search_form_submit($form_id, $form_values){
  return
"/search/node/" . $form_values['content_search_form_keys'] .
           
"+type:" . $form_values['content-type'];

}
?>

and then, on the library page I call up the code with the following:

<?php
print search_box('content_search_form');
?>

The search just comes out like any other search. It doesn't seem to notice the whole resrict-by-type thing. Can you help me to figure out where I'm gonig wrong?

Thanks!

Check content-type

emackn - July 10, 2006 - 19:56

I would check the content type to make sure it is just 'bookreview'. You can do this by doing an advanced search and selecting the content type you want to search on. Hit submit and the results should display on the regular search page with something like
'keyword type:content-bookreview' in the keywords text box. Whatever is after 'type:' is the content type, and $content_type should be set to that.

content type is correct - what about cusotm form alter

SparkyUK - July 11, 2006 - 10:58

The content type is definitely bookreview. Works in advanced search or if I manually add type:bookreview to my search.

Could the problem be possibly in what I have named the function? I have only the most basic understanding of PHP, but I don't see where here I am call up the function. Also, what do you mean by "only alter content_seach_form"?

function searchlibrary_custom_form_alter($form_id, &$form) {
    // only alter content_seach_form

Your module function

emackn - July 11, 2006 - 15:46

Your module function searchlibrary_custom_form_alter is overridding the hook_form_alter function provided by Drupal. This "hook" is called automatically by drupal.

What I mean by "only alter content_search_form" is that we only want to add the content type to searches from that particular form.

by calling search_box('content_search_form'); you are building the search form and naming it 'content_search_form'.

To debug your issue, I would first take everything out of searchlibrary_custom_form_alter and do something simple like this

function searchlibrary_custom_form_alter($form_id, &$form) {
  print("Altering Form $form_id");
  //can also use
  //error_log("Altering Form $form_id", 0);
  // if you are on a live site.
}

This should print something for every form. If you dont see anything, then some module isn't enabled.
Now add something to only print your message when that form is being built. That's where the 'only alter content_search_form' line goes to work.

Again, the form name should be whatever you set it to when calling search_box(...).

Good luck ;)

not activated

SparkyUK - July 12, 2006 - 10:40

Okay, Sorry for missing the small steps. I hadn't activated the searchlibrary module. It is now activated and so when I do a search from my library it still searches all types, but now it at least is including "type:" in the search bar. Unfrotunately though it still isn't inserting the actual type (i.e. book review) into the search parameters. any ideas? (i haven't implemented your suggestions above as I wasn't sure if it was the same issue or not...) thanks

Not a problem, we all miss

emackn - July 12, 2006 - 12:20

Not a problem, we all miss the small stuff at times. ;)

Try this, remove request_uri(), 'node/9') !== false && from the if statement and just use the form_id check on the conditional.

hard-code content-type

CvB - July 18, 2006 - 10:23

SparkyUK,

I may be missing out on something here, but if you're hard-coding your content-type anyway (you assign it to the variable $content_type), then
why not hard-coding the content-type in the content_search_form_submit function as well? If you need more node-specific searches, can't you just make
a node-specific search module for every node?

You may want to try this:

function content_search_form_submit($form_id, $form_values){
return "/search/node/" . $form_values['content_search_form_keys'] .
"+type:bookreview";

Hope this helps.

Actually, It's probably

emackn - July 21, 2006 - 16:41

Actually, It's probably better to move all the text out of _form_submit. So, In _form_alter change
$content_type = 'bookreview'; to $content_type = '+type:bookreview';

Also remove '+type:' from _form_submit. That's more maintainable and no changes to _form_submit are needed if you want to replace the hidden form field with a select box.

_custom?

kingandy - February 20, 2007 - 13:37

I tried implementing this today and it failed to invoke the custom function at all, at any point.

In the end I tried removing the "_custom" from the _form_alter function (so my function is now called magicsearch_form_alter). That seems to have got it, in that the extra content-type field is now appearing.

Now it just seems to be failing to actually interact with the search module ...

EDITED TO ADD: Huh, it's retaining its $form['#submit'] value of array('search_box_form_submit' => array()) despite the blatant alteration. Wtf.

Which version of Drupal are

emackn - February 23, 2007 - 22:57

Which version of Drupal are you using? and maybe post some of the code that you are having trouble with.

Easier in Drupal 5.1

emackn - June 29, 2007 - 21:41

This gets even easier in 5.1

put this in your template OR module

function product_vendor_search_form() {
    $form['pv_keywords'] = array(
        '#type' => 'textfield' 
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'submit',
    );
    return $form;
}

function product_vendor_search_form_submit($form_id, $form_values) {
    return "search/node/" . $form_values['pv_keywords'] . " type:product,vendor";
}

And wherever you want your search form add this:

print drupal_get_form('product_vendor_search_form');

Search Form Drupal 5.1

coupet - October 5, 2007 - 01:40

subscribe.

----
Darly

subscribe - thx

scottrigby - October 22, 2007 - 20:02

limiting search by content type

Drupalzilla.com - October 25, 2007 - 20:53

I'm using Drupal 5.2 and want to have a search box on the front page of a site that limits the results only to a content type called business.

I put this in template.php:

<?php // turning on PHP syntax highlighting on drupal.org...

function business_search_form() {
   
$form['pv_keywords'] = array(
       
'#type' => 'textfield'
   
);
   
$form['submit'] = array(
       
'#type' => 'submit',
       
'#value' => 'submit',
    );
    return
$form;
}

function
business_search_form_submit($form_id, $form_values) {
    return
"search/node/" . $form_values['pv_keywords'] . " type:business";
}
// this closing tag is just for syntax highlighting on drupal.org ?>

I created a page and added this code:

<?php
print drupal_get_form('business_search_form');
?>

The HTML output is this -- no visible search form:

<form action="/test"  method="post" id="business-search-form">
<div><input type="hidden" name="form_token" id="edit-business-search-form-form-token" value="b51412de485cdc3e3d9e842cf336293f"  />
<input type="hidden" name="form_id" id="edit-business-search-form" value="business_search_form"  />

</div></form>

What am I missing?

I'm not sure.. It all looks

emackn - October 26, 2007 - 12:16

I'm not sure.. It all looks right. Have you checked your server logs and the watchdog? Maybe something else is going on. Is your account set to use the correct theme that contains the right template.php?

I checked Drupal's logs and

Drupalzilla.com - October 26, 2007 - 20:51

I checked Drupal's logs and saw the following error:

call_user_func_array() [<a href='function.call-user-func-array'>function.call-user-func-array</a>]: First argumented is expected to be a valid callback, 'business_search_form' was given in /home/****/public_html/****/includes/form.inc on line 217.

Any ideas?

Rename the form?

emackn - October 29, 2007 - 12:20

Try renaming the form to something that you know is unique. I checked drupal_retrieve_form in form.inc and this is whats there

<?php
 
// If $callback was returned by a hook_forms() implementation, call it.
  // Otherwise, call the function named after the form id.
 
$form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);
?>

$callback is set for some reason.

form?

Drupalzilla.com - October 30, 2007 - 19:41

Thanks for the reply.
Sorry, I'm not sure exactly which part to change:

<?php // turning on PHP syntax highlighting on drupal.org...

function business_search_form() {
   
$form['pv_keywords'] = array(
       
'#type' => 'textfield'
   
);
   
$form['submit'] = array(
       
'#type' => 'submit',
       
'#value' => 'submit',
    );
    return
$form;
}

function
business_search_form_submit($form_id, $form_values) {
    return
"search/node/" . $form_values['pv_keywords'] . " type:business";
}
// this closing tag is just for syntax highlighting on drupal.org ?>

search form

Drupalzilla.com - November 3, 2007 - 23:51

I'm sure that the form has a unique name. I've even changed it again. Is there anything else that it could be?

PLEASE Help. What am I missing?

ADMarshall - July 25, 2006 - 02:05

First, thanks tonnes, emackn. This is exactly what I desperately need. But I think I implemented it wrong. Can anyone please suggest what I should do next? I've vim-diffed my version of the module with the modules' code in this thread and can't find any significant differences other than the function name and content type used.

If you want to see where I'm trying to implement this, please seach the "Search eVents" block at either http://eventsvietnam.com/uee/food_beverage_home or http://eventsvietnam.com/uee/services/food_beverage or

(Please note: I did try this with the pathauto module deactivated as well and the CCK node type I'm trying to limit the search to is called "content-service", according to Drupal's Advanced Search.)

As soon as I add and activate my version of this module, "searchfnb.module" (code below), via Save Changes under admin/modules, it simply returns a blank screen. Then, when i hit the back button it shows searchfnb as activated but displays this warning message:

warning: Cannot modify header information - headers already sent by (output started at /home/eventsviet/www/www/uee/modules/searchfnb/searchfnb.module:28) in /home/eventsviet/www/www/uee/includes/common.inc on line 139.

I still tried to test it after that message, with the exact PHP code above inserted into my added search block (with input format type "PHP" selected), but it only again blanks the screen, and hitting the Back button reveals these warnings:

* warning: Cannot modify header information - headers already sent by (output started at /home/eventsviet/www/www/uee/modules/searchfnb/searchfnb.module:28) in /home/eventsviet/www/www/uee/includes/common.inc on line 139.
* warning: Cannot modify header information - headers already sent by (output started at /home/eventsviet/www/www/uee/modules/searchfnb/searchfnb.module:28) in /home/eventsviet/www/www/uee/includes/common.inc on line 266.

Re. the code related to these warnings:

01. I'm not sure what the "searchfnb.module:28" above means. My searchfnb.module is only 27 lines long.

02. In includes/common.inc,

02.a line 139 refers to header($header); in this function (comments removed):

function drupal_set_header($header = NULL) {
  static $stored_headers = array();

  if (strlen($header)) {
    header($header);
    $stored_headers[] = $header;
  }
  return implode("\n", $stored_headers);
}

02.b line 266 refers to header('Location: '. $url); in this function (blank lines and some comments removed):

function drupal_goto($path = '', $query = NULL, $fragment = NULL) {
  if (isset($_REQUEST['destination'])) {
    extract(parse_url($_REQUEST['destination']));
  }
  else if (isset($_REQUEST['edit']['destination'])) {
    extract(parse_url($_REQUEST['edit']['destination']));
  }
  $url = url($path, $query, $fragment, TRUE);
  // Before the redirect, allow modules to react to the end of the page request.
  module_invoke_all('exit', $url);
  header('Location: '. $url);
  exit();
}

My version of this module, "searchfnb.module" follows. Please note that I removed strpos(request_uri(), 'node/9') !== false &&, as emackn kindly suggested, because I have to use this search block on many pages, not just one -- though that is more than emackn suggested above because only removing request_uri(), 'node/9') !== false && is incomplete, no?.

searchfnb.module

<?php
function searchfnb_custom_form_alter($form_id, &$form) {
   
// only alter content_seach_form
   
if($form_id == 'content_search_form'){
   
// for me, path_to_form was the url of the page containing my search block.
       
$content_type = 'content-service';
       
$form['content-type']= array(
               
'#value' => $content_type,
               
'#type' => 'hidden');
       
$form['#validate'] = array('content_search_form_validate' => array());
       
$form['#submit'] = array('content_search_form_submit' => array());
    }
}

/**
* Drupal calls this processing.. but all we are doing is building the
* search url to only look for a certain content type.
* The module name is not prefixed to the function, this name has to match
* the name set as the #validate function on $form
*/
function content_search_form_submit($form_id, $form_values){
  return
"/search/node/" . $form_values['content_search_form_keys'] .
           
"+type:" . $form_values['content-type'];

}
?>

Just in case, here's a copy of the PHP code I plugged into my added search block:

<?php
print search_box('content_search_form');
?>

Total shot in the dark, but

emackn - July 25, 2006 - 12:44

Total shot in the dark, but do you by chance have an extra line at the end of your module file outside the closing bracket?

Or after the closing ?>?

UnBElievable!

ADMarshall - July 26, 2006 - 07:50

emackn, you are a freakin' GOD! If you're ever in Saigon, let me know and i'll show you the time of your life! Want a mail-order bride with none of the paperwork? (Just kidding -- about the latter, not the former. ;))

There was indeed a blank line after the final ?> Is PHP supposed to work that way?!? No need to answer that. It obviously does... Sheesh...

Correction: Here's My (ERRONEOUS) Solution

ADMarshall - July 28, 2006 - 08:37

Correction: This is WRONG, WRONG, WRONG... While the search box this returns will retain the type or category hard-coded in when the results display, a subsequent search will use the Drupal search.module defaults and ignore the type or category. Sorry for any inconvenience... - ADM

[some previous text cut - ADM]

Now, I've got to be as much of a PHP moron as anyone, but, so far (knock wood), this is all I had to plug into my added search block to get exactly what I wanted, without affecting the default Drupal search block:

<?php
function content_search_form_submit($form_id, $form_values) {
  return
"search/node/" . trim($form_values[$form_id . '_keys'] . '+category:160');
}
print
'<div class="fnbsearchblock">' . search_box('content_search_form') . '</div>';
?>

No fuss, no muss, no module needed. And it can be put on any page and customized to each page's particular search needs, and other text or links can be added to the block via HTML or PHP.

But, even more importantly, for me at least, this search box can be specifically styled and its results can even be specifically themed by search type or category using the taxonomy_theme module's extended features (in this case, by plugging *category%3A160* into the "Extended" box for the theme to be used).

[previous additional text cut - ADM]

:((((((((

pielgrzym - January 23, 2007 - 23:08

The latest and simpliest solution doesn't work for Drupal. 4.7 :( It simply redirects to /search/node :(

Could anyone help?

Still stuck?

emackn - January 24, 2007 - 13:18

Did you get it worked out?

Nope. But it seems to affect

pielgrzym - February 2, 2007 - 17:21

Nope. But it seems to affect every search using 'search box' or 'search block' :(

does this work for 5.1

agusain - April 26, 2007 - 15:05

dose the solution given, works for drupal 5.1?

when I use

<?php
print search_box('content_search_form');
?>

I get the 'Array' printed on my screen.I even used

<?php
print drupal_render(search_box('content_search_form'));
?>

but it thowns a "warning: implode() [function.implode]: Bad arguments. in /var/www/loki/includes/form.inc on line 618."

Can someone throw some light on it

For 5.1, I'm guessing you

emackn - May 2, 2007 - 17:35

For 5.1, I'm guessing you would do this:

<?php
print drupal_form_render('content_search_form', search_box('content_search_form'));
?>

Hi,

Luneh - May 4, 2007 - 12:09

Hi,

I tried your solutions but unfortunately get an error with your last proposition just above:

Fatal error: Call to undefined function: drupal_form_render() in c:\program files\easyphp1-8\www\includes\common.inc(1342) : eval()'d code on line 2.

Hope we can sort this out, I would be really glad to use this on my website.

subscribing, thank you.

lsabug - May 4, 2007 - 20:00

subscribing, thank you.

Sorry, i used the wrong

emackn - May 8, 2007 - 17:19

Sorry, i used the wrong function name, should be "drupal_render_form".

http://api.drupal.org/api/5/function/drupal_render_form

Close, very close...

NiklasM - July 31, 2007 - 09:13

Hi, I've been at this for a while now and would like some help. This is what I thought would work:

I created a new block and entered the following

<?php
function content_search_form_submit($form_id, $form_values) {
  return
"search/node/" . trim($form_values[$form_id . '_keys'] . '+category:160');
}
print
'<div class="fnbsearchblock">' . drupal_render_form('content_search_form', search_box('content_search_form')) . '</div>';
?>

As you can see this is ADMarshall's code with one modification. I got the same problem as agusain with 'Array' being printed in the block and therefore exchanged search_box('content_search_form') for drupal_render_form(search_box('content_search_form')). This still gives me an error:

warning: implode() [function.implode]: Bad arguments. in /home/FA06-27-05-02_d42rb7xdb76wrb3hwc7p/blogg.niklasmork.se/public_html/includes/form.inc on line 618.

My guess is that I am calling the drupal_render_form wrongly somehow. Anyone out there to give me a hand?

try drupal_get_form

emackn - August 1, 2007 - 14:10

Try using

<?php
print drupal_get_form('content_search_form');
?>
instead of drupal_render_form();

Unfortunately...

NiklasM - August 1, 2007 - 15:53

Thanks for your answer. Unfortunately I didn't get it to work. I got the following php error report:
Fatal error: Cannot unset string offsets in httpd.www/includes/form.inc on line 319

I then tried to cut out the function and place it in a template.php file leaving only print drupal_get_form('content_search_form'); in the box. Then the page would load, but I got this error message in drupal admin: warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback, 'content_search_form' was given in /customers/3t6design.com/3t6design.com/httpd.www/includes/form.inc on line 218.

Any other ideas?

what version of Drupal are

emackn - August 1, 2007 - 16:20

what version of Drupal are you on?

And you do have a content_search_form function to go along with your content_search_form_submit right?

Got it to work, but...

NiklasM - August 6, 2007 - 11:51

I decided to go about it another way and used your code (http://drupal.org/node/68571#comment-247141). This worked very well. The reason I didn't use it straight away is that "type:contenttype" is then printed out in the node's search field above the search results. Anyway, now I've decided to try to hide that entire search field (since I already have a search field in a block.) Just for the record I am using Drupal 5.1. Thanks emackn for your help!

Great

emackn - August 7, 2007 - 18:18

If you are able to hide the "type:contentype" from the search field, update the post with it. Been thinking about that just haven't had the time to look at it. Seems like that should be possible.

How to theme the code

Xabi - August 21, 2007 - 23:40

How to theme the code published on http://drupal.org/node/68571#comment-247141 for showing a link under the search block, reduce the search box rows and replacing the submit button with an image?

hiding "type:contenttype"

pixael - August 16, 2007 - 11:39

This code works great for me, it would be great to hide the "type:contenttype" though, any other ideas?
Thanks all!

type: = yuk!

sylvie_n - October 9, 2007 - 20:46

if anyones found out how to get rid of the "type:" text when a type is selected in the advanced search options then please let us know! - cheers

Removing content type from search

alfredd - November 14, 2007 - 15:59

Hi,

Does any one know how to do the opposite of including a content type in the search. So what I am basically trying to do is the equivalent to search for all content types, except one. So I would like to do something like this "mykeyword -type:blog"
Don't include blog, but give me everything else.

Other options

emackn - November 27, 2007 - 00:09

not the best looking solution, but you could add all the content types except blog to the search.

Another way would be to alter the search results before they are displayed with the search theming hooks. Problem with this is that you get an inconsistent amount of items per page since the the search themes deal with 10 items at a time.

Your timing is rewarded

emackn - November 28, 2007 - 14:48

Check it out.. a lullabot article about exactly what you want to do. Now how often does that happen ;)

http://www.lullabot.com/articles/hiding-content-drupals-search-system

Subscribing - thanks

baronmunchowsen - November 15, 2007 - 17:29

Subscribing - thanks

Tracking.

Zoologico - November 30, 2007 - 19:29

Thanks.

how did everyone do on this one?

pbgswd - December 14, 2007 - 20:54

Hi People,
it seems like a lot of problems were stated here but not the correct solution. I am definitely getting the same errors as everybody else here.

I had some success finally with the example for 5.2.

Its still odd that the information was being output as 'Array' or without any visible elements in the other examples.

This posting on the Drupal.org forum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Search limited by vocabulary term and content type

olalindberg - January 4, 2008 - 10:32

I needed to have a drop down allowing my users to select a specific term from one vocabulary to search within and did the following (maybe useful to someone). It's pretty much the same as the comments above.

You will need to change these two variables to match your installation:

  • $contentType = "company"; (the name of the content type to limit search to)
  • $vocabularyId = 5; (The id for the vocabulary to search within)

In template.php

<?php
/**
* Return the custom search form
*/
function custom_search_form()

 
 
$vocabularyId = 5; //The id for the vocabulary to search within
 
  //Add one element to use as a search all option
 
$termsFromVocab = array(-1 => t("All")) + getTermsFromVocabulary($vocabularyId);
 
 
$form['customSearch_keywords'] = array(
   
'#type' => 'textfield',
   
'#title' => t("Enter your keywords")
  );
 
 
$form['customSearch_searchCategory'] = array(
   
'#type' => 'select',
   
'#title' => t("Category"),
   
'#options' => $termsFromVocab
 
);
 
 
$form['submit'] = array(
   
'#type' => 'submit',
   
'#value' => t("Search")
  );
 
  return
$form;
}

/**
* Return the URL to a custom search when submitting this form
*/
function custom_search_form_submit($form_id, $form_values)
{
 
$contentType = "company"; //Make empty to disable limiting by content type
 
$keywordString = "search/node/" . $form_values['customSearch_keywords'];
 
 
$termId = $form_values['customSearch_searchCategory'];
  if(
$termId >= 0)
  {
   
$categoryString = " category:" . $termId;
  }
 
 
$contentTypeString = "";
  if(
$contentType != "")
  {
   
$contentTypeString = " type:$contentType";
  }
  return
$keywordString . $categoryString . $contentTypeString;
}

/**
* Gets all term ids and names in the given vocabulary.
* $param $vocabularyId The id for the vocabulary to return all terms from.
* $return An array containing the termid as key and the termname as value for that key.
*/
function getTermsFromVocabulary($vocabularyId)
{
 
$termsList = array();
 
 
$terms = taxonomy_get_tree($vocabularyId);
    foreach (
$terms as $term)
  {
   
$termsList[$term->tid] = $term->name;
    }
 
  return
$termsList;
}
?>

And I call my search form from my new block customSearch

<?php
print drupal_get_form('custom_search_form');
?>

Using Views instead

olalindberg - January 14, 2008 - 09:31

I found out (thanks to TBarregren (http://drupal.org/user/16678)!) a better way to create a custom search using Views. I used the following two modules;

See the following Lullabot article for guidance on how to use them: http://www.lullabot.com/articles/custom_search_forms_views_and_fastsearch

Works like a charm!

subscribe

droople - January 16, 2008 - 16:31

link

subscribing

omnyx - February 29, 2008 - 18:46

subscribing

Does that work in drupal 6?

jonika - May 30, 2008 - 18:57

Does that work in drupal 6?

Don't Know

emackn - June 3, 2008 - 16:32

I doubt it works copy/paste. Give it a shot and let us know :)

Got a blank screen when I use this code

nexco - March 22, 2008 - 19:50

Thank you for the code, the form displays perfectly for me. However, I must be doing something wrong because when I submit the form I get a blank page.

I have printed the variables and do see that everything is being picked up for the return statement.

Any idea why I get a blank screen on submit?

check your server logs,

emackn - April 9, 2008 - 17:19

check your server logs, could be a php error in the validation or submit form hooks

subscribe

datawench - June 2, 2008 - 17:53

subscribe

Using the do_search

reed.richards - June 6, 2008 - 15:23

There's a chapter in Pro Drupal Development which describes a custom built search module. The chapter is badly written with little or no information about stuff you generally would like to know about i.e. the stuff above. However there's one line of code where they call a function that is called do_search(). Which basically does "a query on the full-text search index for a word or words". So my idea was to hook into that when building my customized search function. The function head looks like this

<?php
function do_search($keywords, $type, $join1 = '', $where1 = '1', $arguments1 = array(), $columns2 = 'i.relevance AS score', $join2 = '', $arguments2 = array(), $sort_parameters = 'ORDER BY score DESC') { ...
?>

So using the definitions for it(you'll have to read it yourself to understand) I patched together something using the example above(put this in your template.php)

<?php
function print_r_html($data,$return_data=false)
{
   
$data = print_r($data,true);
   
$data = str_replace( " ","&nbsp;", $data);
   
$data = str_replace( "\r\n","<br>\r\n", $data);
   
$data = str_replace( "\r","<br>\r", $data);
   
$data = str_replace( "\n","<br>\n", $data);

    if (!
$return_data)
        echo
$data;  
    else
        return
$data;
}



function
product_vendor_search_form() {
   
$form['#prefix'] = t('<h1>S&ouml;k Hund</h1>');
   
$form['pv_keywords'] = array(
       
'#type' => 'textfield'
   
);
   
$form['submit'] = array(
       
'#type' => 'submit',
       
'#value' => 'submit',
    );
    return
$form;
}

function
product_vendor_search_form_submit($form_id, $form_values) {
   
$hits = do_search($form_values['pv_keywords'],'node',"INNER JOIN {node} n ON n.nid = i.sid", "(n.type = 'product_vendor')");
   
print_r_html($hits);
    return
FALSE;
}
?>

Finally put this in a page with the php-filter on

<?php
print drupal_get_form('product_vendor_search_form');
?>

The do_search does the query on the full-text search index but removes the unwanted nodes by the INNER JOIN and WHERE statement arguments and returns a nice list of all the elements from the index. Then you just have to get the right nodes and display them. Voila!

I don't know if this is the right way to do it, it's kind of slow and I am guessing if you have searches for attributes and such it would be faster to write your own database search function. I will try to update on my progress on this if I have the time.

Subscribing

michellepurestock - November 6, 2008 - 23:39

Subscribing

 
 

Drupal is a registered trademark of Dries Buytaert.