Question

I have created custom CRUD on new database table. I just wanted to save comma separated categories in a field.

I have this code for multiselect categories:

$fieldset->addField(
    'categories',
    'multiselect',
    [
        'label' => __('Categories'),
        'title' => __('Categories'),
        'name' => 'categories',
        'values' => \Vendor\Module\Block\Adminhtml\Products\Grid::getCategories(),
        'note' => __('Could be multiple'),
        'disabled' => $isElementDisabled
    ]
);

I have created getCategories function in Grid.php.

Can anyone suggested how to populate categories in tree form and return categories array

Was it helpful?

Solution

After so many tries, I have figured out the solution for my own question.

I used this code to make multiselect (as mentioned in my question):

$fieldset->addField(
    'categories',
    'multiselect',
    [
        'label' => __('Categories'),
        'title' => __('Categories'),
        'name' => 'categories',
        'values' => \Vendor\Module\Block\Adminhtml\Products\Grid::getCategories(),
        'note' => __('Could be multiple'),
        'disabled' => $isElementDisabled
    ]
);

In Grid.php file I have created two functions one is to create simple array for multi select values:

static public function getCategories()
{
    $data_array = array();
    foreach (\Vendor\Module\Block\Adminhtml\Productsgrid\Grid::getCategoryTree() as $k => $v) {
        $data_array[] = array('value' => $k, 'label' => $v);
    }
    return ($data_array);

}

And the 2nd one is a recursive function to generate category tree

static public function getCategoryTree($categories = "", $data_array = array())
{
    if(empty($categories)) {
        $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $categoryFactory = $_objectManager->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
        $categories = $categoryFactory->create()
            ->addAttributeToSelect('*')//or you can just add some attributes
            ->addAttributeToFilter('level', 2)//2 is actually the first level
            ->addAttributeToFilter('is_active', 1)//if you want only active categories
            ->addAttributeToSort('position', 'ASC');
    }

    foreach($categories as $k=>$category){
        $level = $category->getLevel();
        $data_array[$category->getId()] = str_repeat("*",$level)." ".$category->getName();
        $childCategories = $category->getChildrenCategories();
        if(count($childCategories) > 0){
            $data_array = \Vendor\Module\Block\Adminhtml\Productsgrid\Grid::getCategoryTree($childCategories, $data_array);
        }
    }
    if(count($data_array) == 0){
        return $data_array;
    }
    return ($data_array);
}

My final array $data_array contains the IDs in array key and Category title in values.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top