0

I'm looking for creating a custom attribute for products, already have a CRUD module, with name and descriptions fields, so the names from my DB should be options of that attribute. How do I need to correct this code, so it will get values from my DB? Thanks everyone!

class Material extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
    /**
     * Get all options
     * @return array
     */
    public function getAllOptions()
    {
        if (!$this->_options) {
            $this->_options = [
                ['label' => __('Cotton'), 'value' => 'cotton'],
                ['label' => __('Leather'), 'value' => 'leather'],
                ['label' => __('Silk'), 'value' => 'silk'],
                ['label' => __('Denim'), 'value' => 'denim'],
                ['label' => __('Fur'), 'value' => 'fur'],
                ['label' => __('Wool'), 'value' => 'wool'],
            ];
        }
        return $this->_options;
    }
}
2

So I figured out, how to get options for my custom attribute, from DB table, here is how my class in Source/Vendors.php looks now:

class Vendors extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource { protected $collectionFactory;

public function __construct(CollectionFactory $collectionFactory)
{
    $this->collectionFactory = $collectionFactory;
}

/**
 * Get all options
 * @return array
 */
public function getAllOptions()
{
    if (!$this->_options) {
        /** @var Collection $collection */
        $collection = $this->collectionFactory->create();

        $vendors = $collection->getItems();

        if (!$vendors) {
            return [];
        }

        $options = [];

        foreach ($vendors as $vendor) {
            $options[] = [
                'label' => $vendor->getData('name'),
                'value' => $vendor->getData('name')
            ];
        }

        $this->_options = $options;
    }

    return $this->_options;
}

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.