Product Select Box in Magento

Lets use helper file of Catalog, app/code/core/Mage/Catalog/Helper/Data.php

//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

Comments