Magento utility function: How to easily create a select box for drop-down attributes?

From now onward I will be sharing custom utility functions on a regular basis which will make your programming life easier to some extent at least in case of Magento 🙂

Here I am going to share a utility function which will help you to create a select box for drop-down attributes(manufacturer, color, size, etc.) of a product.

Utility Function:

function getSelectBox($attributeCode, $label = '', $defaultSelect = null, $extraParams = null){
	$options			= array();
	$product			= Mage::getModel('catalog/product');
	$attribute			= $product->getResource()->getAttribute($attributeCode);
	if($attribute->usesSource()){
		$options = $attribute->getSource()->getAllOptions(false);
		array_unshift($options, array('label' => $label, 'value' => ''));
	}

	$select = Mage::app()->getLayout()->createBlock('core/html_select')
			->setName($attributeCode)
			->setId($attributeCode)
			->setTitle($label)
			->setValue($defaultSelect)
			->setExtraParams($extraParams)
			->setOptions($options);
	return $select->getHtml();
}

Now you can easily draw a select box for any drop-down attribute (for example manufacturer) by simply calling the above function as:

<?php echo getSelectBox('manufacturer', 'Select Manufacturer'); ?>

Output:

Select Box - Manufacturer
Select Box – Manufacturer

Note: You can also pass a default value to be selected, extra parameter like CSS class, javascript event handlers, etc via function arguments. Or you can customize the function easily as per your requirements.

You can define the above function in your Helper class and can call from anywhere within your application in order to create a select box for any drop-down attributes of the product.

Happy Coding!!