1

I want to set categories in dropdown field of form of subcategory module in magento2 . How can I get category collection on subcategory form page and set values in dropdown field.

I am trying to do this.
Code:

Model class:

namespace Sparx\Subcategory\Model;

use Magento\Framework\Exception\SubcategoryException;

/**
 * Subcategorytab subcategory model
 */
class Subcategory extends \Magento\Framework\Model\AbstractModel
{

    /**
     * @param \Magento\Framework\Model\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource
     * @param \Magento\Framework\Data\Collection\Db $resourceCollection
     * @param array $data
     */
    protected $categorymodelFactory;
    public function __construct(
        \Magento\Framework\Model\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
        \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
        \Sparx\Category\Model\ResourceModel\Category\CollectionFactory $categorymodelFactory,
        array $data = []
    ) {
        parent::__construct($context, $registry, $resource, $resourceCollection, $data);
        $this->categorymodelFactory = $categorymodelFactory;
    }

    /**
     * @return void
     */
    public function _construct()
    {
        $this->_init('Sparx\Subcategory\Model\ResourceModel\Subcategory');
    }   
}

Form class:

namespace Sparx\Subcategory\Block\Adminhtml\Subcategory\Edit\Tab;

class Basicinformation extends \Magento\Backend\Block\Widget\Form\Generic implements \Magento\Backend\Block\Widget\Tab\TabInterface {

    /**
     * @var \Magento\Store\Model\System\Store
     */
    protected $_systemStore;

    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param \Magento\Framework\Data\FormFactory $formFactory
     * @param \Magento\Store\Model\System\Store $systemStore
     * @param array $data
     */
    public function __construct(
    \Magento\Backend\Block\Template\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\Data\FormFactory $formFactory, \Magento\Store\Model\System\Store $systemStore, array $data = array()
    ) {
        $this->_systemStore = $systemStore;
        parent::__construct($context, $registry, $formFactory, $data);
    }

    /**
     * Prepare form
     *
     * @return $this
     */
    protected function _prepareForm() {
        /* @var $model \Magento\Cms\Model\Page */
        $model = $this->_coreRegistry->registry('subcategory_subcategory');
        $isElementDisabled = false;
        /** @var \Magento\Framework\Data\Form $form */
        $form = $this->_formFactory->create();

        $form->setHtmlIdPrefix('page_');

        $fieldset = $form->addFieldset('base_fieldset', array('legend' => __('Basic Information')));

        if ($model->getId()) {
            $fieldset->addField('id', 'hidden', array('name' => 'id'));
        }

        $coll=$this->_categoryFactory->create()->getCollection();
        echo '<pre>';        print_r($coll);

        $fieldset->addField(
                'category', 'select', array(
            'name' => 'category',
            'label' => __('Select Category'),
            'title' => __('Select Category'),
            //'values' => $this->_categoryFactory->create()->getCollection(),
            'required' => true,
                )
        );

        $fieldset->addField(
                'title', 'text', array(
            'name' => 'title',
            'label' => __('Subcategory Title'),
            'title' => __('Subcategory Title'),
            'required' => true,
                )
        );


        $fieldset->addField(
                'status', 'select', array(
            'name' => 'status',
            'label' => __('status'),
            'title' => __('status'),
            'values' => array(0 => array('label' => 'Enable', 'value' => '1'), 1 => array('label' => 'disable', 'value' => '2')),
            'required' => true,
                )
        );
        /* {{CedAddFormField}} */

        if (!$model->getId()) {
            $model->setData('status', $isElementDisabled ? '2' : '1');
        }

        $form->setValues($model->getData());
        $this->setForm($form);

        return parent::_prepareForm();
    }

    /**
     * Prepare label for tab
     *
     * @return string
     */
    public function getTabLabel() {
        return __('Basic Information');
    }

    /**
     * Prepare title for tab
     *
     * @return string
     */
    public function getTabTitle() {
        return __('Basic Information');
    }

    /**
     * {@inheritdoc}
     */
    public function canShowTab() {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function isHidden() {
        return false;
    }

    /**
     * Check permission for passed action
     *
     * @param string $resourceId
     * @return bool
     */
    protected function _isAllowedAction($resourceId) {
        return $this->_authorization->isAllowed($resourceId);
    }

}

It gives a blank page and I am not able to identify the exact problem.

  • Please add Form class to the question – KAndy Feb 4 '16 at 10:11
  • Form class is added now. – Arun Pal Feb 4 '16 at 10:26
  • i'm also stucked in the same issue, if you got the solution can you help me? by sandeep pandey – Amit Bera Jul 14 '16 at 7:32
1

Have you debugged what $this->_categoryFactory->create()->getCollection()->getData() gives you? Just outputting the collection data like that into a select box values field wont get you anywhere.

You need to do something like this i think:

$itemsArray = [];    
foreach($this->_categoryFactory->create()->getCollection()->getItems() as $item) {
    $itemsArray[] = $item->getName(); //or title or whatever it is
}

  $fieldset->addField(
            'category', 'select', array(
        'name' => 'category',
        'label' => __('Select Category'),
        'title' => __('Select Category'),
        'values' => $itemsArray,
        'required' => true,
            )
    );

This is a rough example. Some things might not be correct but should get you going.

  • Actually, the problem is in getting collection. I'm not able to get collection on form page. Setting the collection is not an issue. $coll=$this->_categoryFactory->create()->getCollection(); Even I tried to print_r($coll). I'm not getting the collection. – Arun Pal Feb 4 '16 at 10:15
1

To see problem uncomment #ini_set('display_errors', 1); line in app/bootstrap.php.

You class do not have dependency on categoryFactory. Add it to block constructor to use.

private $_categoryFactory;

public function __construct(
    \Magento\Backend\Block\Template\Context $context, 
    \Magento\Framework\Registry $registry, 
    \Magento\Framework\Data\FormFactory $formFactory,
    \Magento\Store\Model\System\Store $systemStore, 
    \Sparx\Category\Model\ResourceModel\Category\CollectionFactory $categorymodelFactory,
    array $data = array()
    ) {
        $this->_systemStore = $systemStore;
        $this->_categoryFactory = categorymodelFactory;
        parent::__construct($context, $registry, $formFactory, $data);
    }
  • I'm not able to maintain the dependency.Can you tell me all the files I need to make changes? – Arun Pal Feb 9 '16 at 5:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.