Magento: Display multi-select field in form and grid

The multi-select field is very useful in many features like assigning an item to multiple categories. I am writing code here to implement multi-select in form page and then display multi-selected values in grid page.

To display multi-select in form:

Go to Adminhtml/Example/Edit/Tab/Form.php

// Get category collection          
$categoryCollection = Mage::getModel('example/category')->getCollection()
->addFieldToFilter('status' , '1');
;

foreach($categoryCollection as $category){
	$optioncat[$category->getId()] = array('label'=>$category->getTitle(),'value'=>$category->getId());
}

$fieldset->addField('category', 'multiselect', array(
	'label'     => Mage::helper('core')->__('Select Category'),
	'class'     => 'required-entry',
	'required'  => true,
	'name'     => 'category[]',
	'onclick' => "return false;",
	'onchange' => "return false;",
	'value'  => '4',
	'values' => $optioncat,
	'disabled' => false,
	'readonly' => false,          
	'tabindex' => 1
));

To display multi-select value and filter in grid:

Go to Block/Adminhtml/Example/Grid.php

protected function _prepareColumns()
{
	$this->addColumn('category', array(
	    'header'    => Mage::helper('catalog')->__('Category'),
	    'width'     => '180px',
	    'index'     => 'category',
	    'type'  => 'options',
	    'options' => $categoryOption,
	    'filter_condition_callback' => array($this, '_filterCategoriesCondition'),
	    'renderer'=> new Example_Example_Block_Adminhtml_Renderer_Category(),
	));
}


protected function _filterCategoriesCondition($collection, $column)
{
    if (!$value = $column->getFilter()->getValue()) {
        return;
    }
 
    $this->getCollection()->addFieldToFilter('category', array('finset' => $value));
}

Block/Adminhtml/Renderer/Category.php

class Example_Example_Block_Adminhtml_Renderer_Category extends  Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{

	public function render(Varien_Object $row)
	{
		$categoryIds =  $row->getCategory();
		$categoryIdsArray = explode(',', $categoryIds);
		$str = '<ul>';
		foreach ($categoryIdsArray as $value) {
			$categoryData = Mage::getModel('example/category')->load($value);
			$str.='<li>'.$categoryData->getTitle().'</li>';

		}
		$str.= '</ul>';

		return $str;
	}

}

Enjoy!!!