23

How can I get the attribute options values of eav entity?
I found solution only for magento 1.x but M2 I don't know.
M1:

$attr = Mage::getResourceModel('eav/entity_attribute_collection')->setCodeFilter('specialty')->getData()[0];
$attributeModel = Mage::getModel('eav/entity_attribute')->load($attr['attribute_id']);
$src =  $attributeModel->getSource()->getAllOptions();

Anyone know, show me step by step, pls!Thanks!

Marius
  • 197,939
  • 53
  • 422
  • 830
MrTo-Kane
  • 3,656
  • 10
  • 44
  • 74
  • -- Divya I didn't succeed with your code. Here is a working example for finding product data <?php use Magento\Framework\App\Bootstrap; require realpath(DIR) . '/../app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER); $obj = $bootstrap->getObjectManager(); $state = $obj->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); $sku ='YL-YM-101'; // my product sku $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $productObject = $objectManager->get('Magento\Catalog\Model\Product'); $product = $productObject->loadByAttribute('sku', $sku); echo $p – Павел Лукьянчук Mar 30 '21 at 14:04
  • I didn't get it Can you give an example of a working code where you get magento attribute parameters programmatically Like here https://pearlbells.co.uk/code-snippets/get-magento-attribute-options-programmatically/ it didn't work for me. – Павел Лукьянчук Mar 22 '21 at 07:44

6 Answers6

75

you can add to the constructor of your class an instance of \Magento\Eav\Model\Config like this:

protected $eavConfig;
public function __construct(
    ...
    \Magento\Eav\Model\Config $eavConfig,
    ...
){
    ...
    $this->eavConfig = $eavConfig;
    ...
}

then you can use that in your class

$attribute = $this->eavConfig->getAttribute('catalog_product', 'attribute_code_here');
$options = $attribute->getSource()->getAllOptions();
Marius
  • 197,939
  • 53
  • 422
  • 830
  • How to get "value" and "label"? – MrTo-Kane Mar 08 '16 at 08:19
  • 1
    see how the result looks like. Var dump it or something. – Marius Mar 08 '16 at 08:26
  • array(2) { [0]=> array(2) { ["value"]=> int(1) ["label"]=> object(Magento\Framework\Phrase)#1504 (2) { ["text":"Magento\Framework\Phrase":private]=> string(7) "Enabled" ["arguments":"Magento\Framework\Phrase":private]=> array(0) { } } } [1]=> array(2) { ["value"]=> int(2) ["label"]=> object(Magento\Framework\Phrase)#1494 (2) { ["text":"Magento\Framework\Phrase":private]=> string(8) "Disabled" ["arguments":"Magento\Framework\Phrase":private]=> array(0) { } } } } – MrTo-Kane Mar 08 '16 at 08:29
  • Okey! I resolved => $attributesArrays = array();
     foreach($options as $cal=>$val){
      $attributesArrays[$val['value']] = $val['label']->getText();
     }
    
    – MrTo-Kane Mar 08 '16 at 08:47
  • 12
    Small but important remark: If available, better to use Module Service Layer. For eav attributes it's \Magento\Eav\Api\Attribute RepositoryInterface. Anything not marked as @api treated as private and can be removed in minor releases. – KAndy Mar 08 '16 at 11:54
  • 5
    @KAndy Good remark. You can write that as an answer. I think it's far better than mine. – Marius Mar 08 '16 at 12:16
  • @MagentoOdoo.com get value and label like below
                                <option value="<?php echo $option['value'] ?>"<?php if ($option['value'] == $fieldValue) echo ' selected="selected"' ?>><?php echo $option['label']->getText();?></option>
                            <?php endforeach;?>
    
    – Pandurang Babar Oct 20 '16 at 11:28
  • Could you post this as a step-step answer?? I don't know how to create a module like that in magento2, so I don;t know how to use that code. – zekia Aug 29 '18 at 10:39
  • @zekia maybe this helps: https://inchoo.net/magento-2/how-to-create-a-basic-module-in-magento-2/ – Marius Aug 29 '18 at 11:20
  • @Marius I've read this article but there's a big step between a basic module and a module with controllers and blocks. I can't fill the blanks there. That's why I asked for a more detailed step-step answer. – zekia Aug 31 '18 at 06:12
10

Use the following code to get all attribute options.

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) {
    $optionsExists[] = $option['label'];
}

return $optionsExists;

 }

Please Can you click here for more detailed explanation. http://www.pearlbells.co.uk/code-snippets/get-magento-attribute-options-programmatically/

Magento_Bhurio
  • 940
  • 5
  • 14
Liz Eipe C
  • 1,286
  • 12
  • 17
6

I use the Api Service Layer Magento\Eav\Api\AttributeRepositoryInterface suggested by @kandy in comments on @marius answer.

Inject the service data member in your constructor as follow.

protected $eavAttributeRepository;
public function __construct(
    ...
    \Magento\Eav\Api\AttributeRepositoryInterface $eavAttributeRepositoryInterface,
    ...
){
    ...
    $this->eavAttributeRepository = $eavAttributeRepositoryInterface;
    ...
}

And the you can get the attribute using this.

$attribute = $this->eavAttributeRepository->get(
    \Magento\Catalog\Model\Product::ENTITY,
    'attribute_code_here'
);
// var_dump($attribute->getData()); 

In order to get attribute option values array, use this.

$options = $attribute->getSource()->getAllOptions();
Roman Snitko
  • 786
  • 5
  • 15
Muhammad Saeed Khan
  • 1,343
  • 2
  • 16
  • 29
5

You can do it simply call below code inside your Block file.

<?php
namespace Vendor\Package\Block;

class Blockname extends \Magento\Framework\View\Element\Template
{
    protected $_productAttributeRepository;

    public function __construct(        
        \Magento\Framework\View\Element\Template\Context $context,   
        \Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository,
        array $data = [] 
    ){        
        parent::__construct($context,$data);
        $this->_productAttributeRepository = $productAttributeRepository;
    } 

    public function getAllBrand(){
        $manufacturerOptions = $this->_productAttributeRepository->get('manufacturer')->getOptions();       
        $values = array();
        foreach ($manufacturerOptions as $manufacturerOption) { 
           //$manufacturerOption->getValue();  // Value
            $values[] = $manufacturerOption->getLabel();  // Label
        }
        return $values;
    }  
}

Call inside your phtml file,

<div class="manufacturer-name">
      <?php $getOptionValue = $this->getAllBrand();?>
      <?php foreach($getOptionValue as $value){ ?>
           <span><?php echo $value;?></span>
      <?php } ?>
</div>

Thanks.

Rakesh Jesadiya
  • 42,221
  • 18
  • 132
  • 183
  • This doesn't return the options for attributes configured to use swatch inputs, like color. The getOptions() method is hard coded to certain input types, like "dropdowns", so it skips the swatch input options. Just a heads up if anyone else runs in to that. – thaddeusmt Aug 15 '17 at 16:44
  • Hi @Rakesh, How I achieve this same but for Admin. I need these option value for Grid column filter. Can you please tell me. – Ravi Soni Sep 20 '17 at 10:20
  • How to get item attribute values based on store-level on order summary section at checkout Magento 2 – Roshan Rakesh Yadav Mar 31 '20 at 10:36
  • @Rakesh, does it work in magento 2.4 – Pankaj Pant Apr 08 '21 at 07:23
4

Inject an instance of \Magento\Catalog\Model\Product\Attribute\Repository in your constructor (in a block, helper class or wherever):

/**
 * @var \Magento\Catalog\Model\Product\Attribute\Repository $_productAttributeRepository
 */
protected $_productAttributeRepository;

/**
 * ...
 * @param \Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository
 * ...
 */
public function __construct(
    ...
    \Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository,
    ...
) {
    ...
    $this->_productAttributeRepository = $productAttributeRepository;
    ...
}

Then create a method in your class to get the attribute by code:

/**
 * Get single product attribute data 
 *
 * @return Magento\Catalog\Api\Data\ProductAttributeInterface
 */
public function getProductAttributeByCode($code)
{
    $attribute = $this->_productAttributeRepository->get($code);
    return $attribute;
}

You can then call this method like so, e.g. inside a .phtml file

$attrTest = $block->getProductAttributeByCode('test');

Then you can make calls on the attribute object, e.g.

  1. Get options: $attribute->getOptions()
  2. Get frontend label for each store: $attrTest->getFrontendLabels()
  3. Debug the data array: echo '> ' . print_r($attrTest->debug(), true);

debug: Array ( [attribute_id] => 274 [entity_type_id] => 4 [attribute_code] => product_manual_download_label [backend_type] => varchar [frontend_input] => text [frontend_label] => Product Manual Download Label [is_required] => 0 [is_user_defined] => 1 [default_value] => Product Manual Download [is_unique] => 0 [is_global] => 0 [is_visible] => 1 [is_searchable] => 0 [is_filterable] => 0 [is_comparable] => 0 [is_visible_on_front] => 0 [is_html_allowed_on_front] => 1 [is_used_for_price_rules] => 0 [is_filterable_in_search] => 0 [used_in_product_listing] => 0 [used_for_sort_by] => 0 [is_visible_in_advanced_search] => 0 [position] => 0 [is_wysiwyg_enabled] => 0 [is_used_for_promo_rules] => 0 [is_required_in_admin_store] => 0 [is_used_in_grid] => 1 [is_visible_in_grid] => 1 [is_filterable_in_grid] => 1 [search_weight] => 1 )

ajmedway
  • 187
  • 8
0
   <?php
      /* to load the Product */
  $_product = $block->getProduct();
  $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  $attributeSet = $objectManager- 
   >create('Magento\Eav\Api\AttributeSetRepositoryInterface');
  $attributeSetRepository = $attributeSet->get($_product->getAttributeSetId());
  $_attributeValue  = $attributeSetRepository->getAttributeSetName();  
Divya
  • 402
  • 3
  • 11