0

In a magento2 plugin I would like to get the product custom options title from the option ID, but I do not know what injection to make in the constructor and what functions to use to achieve that...

$option_id=13;
$option_Title=$this->..->getTitle($option_id);

1 Answer 1

0

You can do this with collection, my solution:

protected $_storeManager;
protected $_options;

public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Bundle\Model\ResourceModel\Option\CollectionFactory $options,
        \Magento\Store\Model\StoreManagerInterface $_storeManager
    ){
    $this->_storeManager = $_storeManager;
    $this->_options = $options;
    parent::__construct($context);
}

public function getOption($optionId){
    return $this->appendSelections(
        $this->_options->create()
        ->addFieldToFilter('option_id', $optionId)
        ->addFieldToFilter('parent_id', $this->getProduct()->getEntityId())
        ->joinValues($this->_storeManager->getStore()->getId()) // this will append title
        ->getFirstItem(),
        $this->getProduct()
    );
}
protected function appendSelections(\Magento\Bundle\Model\Option $option, $product){
    if($option->getOptionId()){
        $typeInstance = $product->getTypeInstance();
        $selections = $typeInstance->getSelectionsCollection([$option->getOptionId()], $product);
        $option->setData('selections', $selections);
    }
    return $option;
}

With "Repository":

$this->_objectManager->get('Magento\Bundle\Model\OptionRepository')->get(
    $productSku,
    $optionId
);

This solution for bundle options but in custom options will be similar...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.