Magento2 – Get List of Attribute Set Names and IDs

attribute-setmagento2

How would I get a list of Attribute Set names and IDs in Magento 2?

Edit: Adding code.

Edit 2: Added code that worked for me

<?php

namespace Company\CustomAttributes\Model\Config\Source;

use Magento\Eav\Model\ResourceModel\Entity\Attribute\OptionFactory;
use Magento\Framework\DB\Ddl\Table;


class Options extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
    /**
     * @var OptionFactory
     */
    protected $optionFactory;

    /**
     * @param OptionFactory $optionFactory
     */
    public function __construct(OptionFactory $optionFactory)
    {
        $this->optionFactory = $optionFactory;
        //you can use this if you want to prepare options dynamically
        //$coll = $objectManager->create(\Magento\Catalog\Model\Product\AttributeSet\Options::class);
    }

    /**
     * Get all options
     *
     * @return array
     */
    public function getAllOptions()
    {
        /* your Attribute options list*/

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

        $coll = $objectManager->create(\Magento\Catalog\Model\Product\AttributeSet\Options::class);

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

        foreach($coll->toOptionArray() as $d){
            if($d['label'] !== 'Default') {
                $this->_options[] = ['label' => $d['label'], 'value' => $d['value']];
            }
        }
        return $this->_options;
    }

    /**
     * Get a text for option value
     *
     * @param string|integer $value
     * @return string|bool
     */
    public function getOptionText($value)
    {
        foreach ($this->getAllOptions() as $option) {
            if ($option['value'] == $value) {
                return $option['label'];
            }
        }
        return false;
    }

    /**
     * Retrieve flat column definition
     *
     * @return array
     */
    public function getFlatColumns()
    {
        $attributeCode = $this->getAttribute()->getAttributeCode();
        return [
            $attributeCode => [
                'unsigned' => false,
                'default' => null,
                'extra' => null,
                'type' => Table::TYPE_INTEGER,
                'nullable' => true,
                'comment' => 'Custom Attribute Options  ' . $attributeCode . ' column',
            ],
        ];
    }
}

Best Answer

The best way to get it is to use the following source model : \Magento\Catalog\Model\Product\AttributeSet\Options

You can inject it in your constructor then call the toOptionArray() method to retrieve all attribute sets name and ids.

Related Topic