Magento – Magento 2 – Get attribute options and sort order

attributeseavmagento2

I need to get the label and sort order (as defined in backend) of all the options of a custom attribute, programmatically.

I'm using this interface: Magento\Eav\Api\AttributeRepositoryInterface

This is what I tried already:

// Access to the attribute interface
$attribute = $this->_attributeRepository->get(\Magento\Catalog\Model\Product::ENTITY, 'attribute_code');

// Get an array of options
$options = $attribute->getOptions();

// Get the label and sort order of each option
foreach ($options as $option) {
    var_dump($option->getLabel()); // Works OK
    var_dump($option->getSortOrder()); // Always returns NULL
}

I have double checked and there exists a sort order, both in database and in admin area, but the getSortOrder method always returns NULL.

Any ideas?

Best Answer

//Use the following code.

function getExistingOptions( $object_Manager ) {

$eavConfig = $object_Manager->get('\Magento\Eav\Model\Config');
$attribute = $eavConfig->getAttribute('catalog_product', 'color');
$options = $attribute->getSource()->getAllOptions();

$optionsExists = array();

foreach($options as $option) {
    $optionsValues[] = $option['value'];
    $optionsExists[] = $option['label'];
}

return $optionsExists;

}

Click here for detailed explanation. http://www.pearlbells.co.uk/code-snippets/get-magento-attribute-options-programmatically/