0

I am adding options to attribute programmatically as explained here http://webkul.com/blog/programmatically-add-options-attribute-magento2/.
What i want is to get the id of that attribute option to save it to my custom db table. How to achieve this?
thanks

Seefan
  • 540
  • 1
  • 5
  • 21

2 Answers2

1

At magento2, If you want a options then follow Marius answer https://magento.stackexchange.com/a/105171/4564

$options = $attribute->getSource()->getAllOptions();

give list of options with value and label

$OptionInarray=array();
foreach ($options as $option) {
    $options->getValue();  // Value
    $option->getLabel();  // Label
   $OptionInarray[$options->getValue()] = $option->getLabel();
}

here, $options->getValue(); is give u list option id of this attribute

Then using krsort() you can get last order id fro $OptionInarray

krsort($OptionInarray);..Then array_values(krsort($OptionInarray))[0]; , we can get last id

Amit Bera
  • 77,456
  • 20
  • 123
  • 237
0

Here is how I am getting last added attribute option id. I am getting the id by passing last added option label.

$attributeInfo=$this->_attributeFactory->getCollection()
               ->addFieldToFilter('attribute_code',['eq'=>"attribute_id"])
               ->getFirstItem(); 
$option_id = $attributeInfo->getSource()->getOptionId($attributeValue);//$attributeValue is the label of last added attribute option;

Please comment if there is any better way.

Piyush
  • 5,893
  • 9
  • 34
  • 64
Seefan
  • 540
  • 1
  • 5
  • 21