Home    Articles

 

How to search by category in top search of magento, form.mini.phtml

 

I assume that you want to use an HTML select TAG to make the simple search from the header of magento a little more advanced.

In order to do that you have to get all categories and to create the select tag with them.

The search form is using the GET method so this is easy to be done.

1) How to get all categories

function get_categories()
{
	$category = Mage::getModel('catalog/category'); 
	$treeModel = $category->getTreeModel(); 
	$treeModel->load();
	
	$ids = $treeModel->getCollection()->getAllIds(); 
	
	$data = array();
	
	if (!empty($ids))
	{ 
		foreach ($ids as $id)
		{ 
			$cat = Mage::getModel('catalog/category'); 
			$cat->load($id); 
			$categoryData = array('id'=>$cat->getId(),
							  'url'=>$cat->getUrl(),
							  'name'=>$cat->getName(),
							  'image'=>$cat->getImageUrl(),
							  'isActive'=>$cat->getIsActive()
			                 );
			if($id>2)
			{
				array_push($data, $categoryData);
			} 
		} 
    }
	
	return $data;
}

This function will return all categories, you can ajust it if you need.

2) How to create the select tag

Add the code bellow in the app/design/frontend/default//template/catalogsearch/form.mini.phtml

Inside the <form id="search_mini_form"...

 <select id="category" class="search_select" name="cat">
        	<option value="">category</option>
        	<?php 
        	$categories = get_categories();
			#echo '<pre/>';print_r($categories);exit;
        	foreach($categories as $k=>$v) 
        	{
        	?>
        	<option value="<?php echo $v['id']; ?>" <?php echo  (isset($_GET['cat']) && isset($_GET['q']) && $_GET['cat'] == $v['id'] )? 'selected':''; ?>><?php echo $v['name']; ?></option>
        	<?php 
			} 
			?>
        </select>

The select tag need to have the name = "cat" .

This should do the job.

Enjoy.

by