Magento 2 Get Category list in admin tab/main.php

1.7k Views Asked by At

I have created a custom module.Now I want to get categories in drop down in admin.enter image description here

The file is on the following path, app/code/vendor/theme/block/adminhtml/catbanner/edit/tab/Main.php

The html is for dropdown is,

 $fieldset->addField(
        'banner_category',
        'select',
        [
            'label' => __('Select Category'),
            'title' => __('Select Category'),
            'name' => 'banner_category',
            'required' => true,
            'options' => \vendor\module\Block\Adminhtml\Catbanner\Grid::getOptionArray1(),
            'disabled' => $isElementDisabled
        ]
    );

I want the options to be populated by the categories.Kindly help how can i do that?

1

There are 1 best solutions below

0
Virang Jethva On

Use below code for fieldset

$fieldset->addField(
'category',
'select',
[
    'name' => 'category',
    'label' => __('Category'),
    'id' => 'category',
    'title' => __('Category'),
    'values' => \vendor\module\Block\Adminhtml\Catbanner\Grid::getOptionArray1(),
    'class' => 'category',
    'required' => true,
]);

In your grid block use below code:

public function getOptionArray1()
{
    $categoryCollection = $this->_categoryCollectionFactory->create()
        ->addAttributeToSelect(array('id','name'))
        ->addAttributeToFilter('is_active','1');
    $options = array();
    foreach($categoryCollection as $category){
            $options[] = array(
               'label' => $category->getName(),
               'value' => $category->getId()
            );
    }
    return $options;
}

Hope this will work for you...