6

I want to programmatically fetch quote item options which are currently selected.

I've added product with options like following;

Color : Red

Size : 6

enter image description here

Now I want to fetch that selected options programmatically in another Controller.

How can I do that.

2
  • Check in Magento\Checkout\Model\Session u will get it magento\vendor\magento\module-checkout\view\frontend\templates\cart\form.phtml
    – Jackson
    Mar 22, 2017 at 1:26
  • @AnkitShah How can I fetch selected options in another controller programetically? I want that code. Mar 22, 2017 at 3:18

4 Answers 4

12

You can usually call $item->getProductOptions() to get all options and then sort through to get selected options as mentioned by @Rakesh Jesadiya.

But, Sometimes $item->getProductOptions() returns NULL, then you can call

$item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());

instead and it will return options in the same format.

0
6

If you want to know how to do something, it's always best to look at how Magento does it. So if you take a look at the cart templates, you'll notice that the template responsible for rendering a default product (module-checkout/view/frontend/templates/cart/item/default.phtml) uses a method getOptionList() to get the options:

<?php if ($_options = $block->getOptionList()):?>
    ... etc.

Now take a look at this method (Magento\Checkout\Block\Cart\Item\Renderer::getOptionList()):

public function getOptionList()
{
    return $this->getProductOptions();
}

And Magento\Checkout\Block\Cart\Item\Renderer::getProductOptions() will do the following:

public function getProductOptions()
{
    /* @var $helper \Magento\Catalog\Helper\Product\Configuration */
    $helper = $this->_productConfig;
    return $helper->getCustomOptions($this->getItem());
}

Now this is interesting, because here we see the use of a helper that does exactly what your question is: get the custom options of a quote item. And it's a helper, so you can use dependency injection to use it in your own code.

A simple example:

class Example
{
    /**
     * @var \Magento\Catalog\Helper\Product\Configuration
     */
    protected $configurationHelper;

    /**
     * Example constructor.
     * @param \Magento\Catalog\Helper\Product\Configuration $configurationHelper
     */
    public function __construct(
        \Magento\Catalog\Helper\Product\Configuration $configurationHelper
    )
    {
        $this->configurationHelper = $configurationHelper;
    }

    /**
     * @param \Magento\Catalog\Model\Product\Configuration\Item\ItemInterface $item
     * @return array
     */
    public function getSelectedOptionsOfQuoteItem(\Magento\Catalog\Model\Product\Configuration\Item\ItemInterface $item)
    {
        return $this->configurationHelper->getCustomOptions($item);
    }
}

This should solve your problem.

Using Magento 2.1.6

2

You need to load quote item and call below functions,

public function getSelectedOptions($item){
     $result = [];
        $options = $item->getProductOptions();
        if ($options) {
            if (isset($options['options'])) {
                $result = array_merge($result, $options['options']);
            }
            if (isset($options['additional_options'])) {
                $result = array_merge($result, $options['additional_options']);
            }
            if (isset($options['attributes_info'])) {
                $result = array_merge($result, $options['attributes_info']);
            }
        }
        return $result;
    }

You can get selected option by below blog in magento 2, Get Selected options Using Magento 2

Using above Blog you can get Selected options value either by Quote or Order Object. Above link is used for Configurable and Bundle product selected options.

2
  • Thnanks for the answer. I already find this solutions. Sep 10, 2018 at 3:35
  • 2
    $options = $item->getProductOptions(); In my case $options is blank. Can you please guide? Thank you. Mar 30, 2019 at 7:38
0

I find that doing an optimised query using the Magento\Framework\DB\Adapter\AdapterInterface on information readily accessible getOptions method on an $item was the best performer for me:

    /**
     * @param Item $item
     * @return string
     */
    public function newActionVarientFromCartItem(CartItemInterface $item): string
    {
        $variants = [];
        $delimiter = $this->configValue(static::CONFIG_PATH_GAEE_CATEGORY_SEPARATOR_DELIMITER);
        $options = $item->getOptions();
        if (count($options)) {
            foreach ($options as $option) {
                if ($option->getCode() === 'attributes') {
                    $values = $this->serialiser->unserialize($option->getValue());
                    foreach ($values as $attrId => $attrOptId) {
                        $connection = $this->newResourceConnection();
                        $t1 = $connection->getTableName('eav_attribute_option');
                        $t2 = $connection->getTableName('eav_attribute_option_value');
                        $w1 = $connection->prepareSqlCondition('eao.attribute_id', ['eq' => $attrId]);
                        $w2 = $connection->prepareSqlCondition('eaov.option_id', ['eq' => $attrOptId]);
                        $w3 = $connection->prepareSqlCondition('eaov.store_id', ['in' => [0, $item->getStoreId()]]);
                        $select = $connection
                            ->select()
                            ->from(['eao' => $t1], 'eaov.value')
                            ->joinInner(['eaov' => $t2], "eao.option_id=eaov.option_id")
                            ->where(implode(' AND ', [$w1, $w2, $w3]))
                            ->order(new Zend_Db_Expr('eaov.store_id' . ' ' . SortOrder::SORT_DESC));

                        // var_dump($select->__toString());
                        $variants[] = (string) $connection->fetchOne($select);
                    }
                }
            }
        }

        return implode($delimiter, $variants);
    }

    /**
     * Create a new connection to the database
     * @var \Magento\Framework\App\ResourceConnectionFactory $this->_resourceConnectionFactory
     * @return AdapterInterface
     */
    public function newResourceConnection(): AdapterInterface
    {
        return $this->_resourceConnectionFactory
            ->create()
            ->getConnection();
    }

Personally this command:

$item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());

Was not very performant for me.

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.