Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save wkw/f0f257715375f89645ef to your computer and use it in GitHub Desktop.
Save wkw/f0f257715375f89645ef to your computer and use it in GitHub Desktop.
Magento backend admin: Edit form with a multiselect field with product categories
<?php
/* Set up: */
class Namespace_Module_Block_Adminhtml_News_Edit_Tab_Linking {
protected function _prepareForm(){
...
$fieldSet->addField('product_categories', 'multiselect',
array(
'name' => 'product_categories[]',
'label' => 'Product Categories',
'title' => 'Product Categories',
'required' => FALSE,
'values' => Mage::getModel('namespace_module/option_productcategories')->getOptionArray()
));
...
}
}
<?php
class Namespace_Module_Model_Option_Productcategories extends Varien_Object
{
const REPEATER = '_';
const PREFIX_END = '';
protected $_options = array();
/**
* @param int $parentId
* @param int $recursionLevel
*
* @return array
*/
public function getOptionArray($parentId = 1, $recursionLevel = 3)
{
$recursionLevel = (int)$recursionLevel;
$parentId = (int)$parentId;
$category = Mage::getModel('catalog/category');
/* @var $category Mage_Catalog_Model_Category */
$storeCategories = $category->getCategories($parentId, $recursionLevel, TRUE, FALSE, TRUE);
foreach ($storeCategories as $node) {
/* @var $node Varien_Data_Tree_Node */
$this->_options[] = array(
'label' => $node->getName(),
'value' => $node->getEntityId()
);
if ($node->hasChildren()) {
$this->_getChildOptions($node->getChildren());
}
}
return $this->_options;
}
/**
* @param Varien_Data_Tree_Node_Collection $nodeCollection
*/
protected function _getChildOptions(Varien_Data_Tree_Node_Collection $nodeCollection)
{
foreach ($nodeCollection as $node) {
/* @var $node Varien_Data_Tree_Node */
$prefix = str_repeat(self::REPEATER, $node->getLevel() * 1) . self::PREFIX_END;
$this->_options[] = array(
'label' => $prefix . $node->getName(),
'value' => $node->getEntityId()
);
if ($node->hasChildren()) {
$this->_getChildOptions($node->getChildren());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment