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
2 Answers
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
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.
last added attribute option id in magento 2?
orattribute option to save it to your custom db table