Select Box in Magento
Hello All,
I am listing here a useful topic related to Magento.
Below is the description to generate a select box using inbuilt functions of Magento.
Lets take an example of displaying a select box containing all the catalog products.
I am using the existing core files for better understanding, you are recommended make new module or override existing files
Lets use helper file of Catalog, app/code/core/Mage/Catalog/Helper/Data.php
Paste these two functions at the bottom of the file, before ending of class.
//get all products
public function getProductOptions()
{
$products_collection = Mage::getModel('catalog/product')->getCollection()->addStoreFilter()->addAttributeToSelect('*') ; //for fetching all the products
$cnt = $products_collection->count();
$options = array();
$options[] = array(
'label' => 'Please Select Product',
'value' => ''
);
if($cnt>0)
{
foreach ($products_collection as $_product)
{
$options[] = array(
'label' => $_product->getName(),
'value' => $_product->getId()
);
}
}
return $options;
}
//below function for getting products
public function getProductsHtmlSelect($pid)
{
$tmp = Mage::app()->getLayout()->createBlock('core/html_select')
->setName('product_id')
->setId('product_id')
->setClass('validate-select')
->setExtraParams('onchange="getOptions()"');
if(!empty($pid))
{
$tmp = $tmp->setValue($pid);
}
$select = $tmp->setOptions($this->getProductOptions());
return $select->getHtml();
}
Below code to be written in any view file, where a select box need to be displayed. Lets say header.phtml
echo Mage::helper('catalog')->getProductsHtmlSelect(1); //note 1 is the id of product which needs to kept default selected, you can pass any id of product
This will display all the products as options in a select box, where product with id 1 will be kept selected by default.
Hope this is helpful.
One thought on “Select Box in Magento”
Comments are closed.

Very nice, I like that and never even knew you could do it so easily.