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:
Category Collection:
Category Resource:
Category Model: