Magento 2: How add dropdown in admin form?
Change Category class by following code:
namespace Book\Flip\Model\Source; class Category implements \Magento\Framework\Option\ArrayInterface { /** * Retrieve options array. * * @return array */ public function toOptionArray() { $result = []; foreach (self::getOptionArray() as $index => $value) { $result[] = ['value' => $index, 'label' => $value]; } return $result; } /** * Retrieve option array * * @return string[] */ public static function getOptionArray() { return [1 => __('science')]; } /** * Retrieve option array with empty value * * @return string[] */ public function getAllOptions() { $result = []; foreach (self::getOptionArray() as $index => $value) { $result[] = ['value' => $index, 'label' => $value]; } return $result; } /** * Retrieve option text by option value * * @param string $optionId * @return string */ public function getOptionText($optionId) { $options = self::getOptionArray(); return isset($options[$optionId]) ? $options[$optionId] : null; } }
I assume you found this out by now, but the xml in the form ui
<item name="options" xsi:type="string">Book\Flip\Model\Category\Attribute\Source\Category</item>
belongs under data as a sibling of config not a child, and its xsi:type should be "object"
Like this
<argument name="data" xsi:type="array">
<item name="options" xsi:type="object">Book\Flip\Model\Category\Attribute\Source\Category</item>
<item name="config" xsi:type="array">
<item name="dataType" xsi:type="string">text</item>
<item name="label" translate="true" xsi:type="string">category</item>
...
I also was stuck on this issue for awhile until I figured out that bit.
class category implements \Magento\Framework\Option\ArrayInterface
{
//Below function is supposed to return options.
public function toOptionArray()
{
return [
['value' => 1, 'label' => 'label1'],
['value' => 2, 'label' => 'label2']
];
}
}