Magento 2 Extensions – How to Create Options Array for Use in Backend Grid

collection;extensionsgridmagento2

all. Fairly new in Magento development. I am trying to get a dropdown select element in UI grid with values read from database working.

Currently I have it working in a non-preferred manner with the use of ObjectManager, but I gather it's not the 'proper' way.

What I currently use is:

<?php
namespace WDT\Faq\Model\Category\Source;

class Status implements \Magento\Framework\Data\OptionSourceInterface
{
    //*
    // @var \WDT\Faq\Model\Category
    //
    protected $_category;

    //*
    // Constructor
    //
    // @param \WDT\Faq\Model\Category $category
    //
    public function __construct(
        \WDT\Faq\Model\Category $category
    )
    {
        $this->_category = $category;
    }

    /**
    * Get options
    *
    * @return array
    */
    public function toOptionArray()
    {
        $options[] = ['label' => '', 'value' => ''];
        //
        //  Q-n-D solution
        //
        $objectManager =   \Magento\Framework\App\ObjectManager::getInstance();
        $connection = $objectManager->get('Magento\Framework\App\ResourceConnection')->getConnection('\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION');
        $result1 = $connection->fetchAll("SELECT * FROM wdt_faq_category");

        foreach ($result1 as $n => $row) {
            $options[] = [
                'label' => $row['name'] . ' ' . __('Category'),
                'value' => $row['category_id'],
            ];
        }
        return $options;
    }
}

So after many tries with extending ResourceModel and/or Block instances I'am stumped. What is the right way to implement this, and get the intended result?

Best Answer

Here's an example of the bare minimum requirements using dependency injection. Utilizing the ObjectManager directly should be avoided at all costs.

Source Model:

<?php
namespace WDT\Faq\Model\Category\Source;

class Status implements \Magento\Framework\Data\OptionSourceInterface {
    /**
     * @var \WDT\Faq\Model\ResourceModel\Category\CollectionFactory
     */
    protected $_collectionFactory;

    /**
     * @var array|null
     */
    protected $_options;

    /**
     * @param \WDT\Faq\Model\ResourceModel\Category\CollectionFactory $collectionFactory
     */
    public function __construct(
        \WDT\Faq\Model\ResourceModel\Category\CollectionFactory $collectionFactory
    ) {
        $this->_collectionFactory = $collectionFactory;
    }

    /**
     * @return array
     */
    public function toOptionArray() {
        if ($this->_options === null) {
            $collection = $this->_collectionFactory->create();

            $this->_options = [['label' => '', 'value' => '']];

            foreach ($collection as $category) {
                $this->_options[] = [
                    'label' => __('%1 Category', $category->getName()),
                    'value' => $category->getId()
                ];
            }
        }

        return $this->_options;
    }
}

Category Collection:

<?php
namespace WDT\Faq\Model\ResourceModel\Category;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection {
    protected function _construct() {
        $this->_init('WDT\Faq\Model\Category', 'WDT\Faq\Model\ResourceModel\Category');
    }
}

Category Resource:

<?php
namespace WDT\Faq\Model\ResourceModel;

class Category extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb {
    protected function _construct() {
        $this->_init('wdt_faq_category', 'category_id');
    }
}

Category Model:

<?php
namespace WDT\Faq\Model;

class Category extends \Magento\Framework\Model\AbstractModel {
    protected function _construct() {
        $this->_init('WDT\Faq\Model\ResourceModel\Category');
    }
}