Magento 2 – Fix Item Options Not Available Issue

addtocartmagento2

We have installed Magento ver. 2.1.6. using composer with sample data.

We have call event checkout_cart_product_add_after for adding addition information with item. The event observer code is given below.

$item = $observer->getQuoteItem();

    $additionalOptions = array();

    if ($additionalOption = $item->getOptionByCode('additional_options')){
        $additionalOptions = (array) unserialize($additionalOption->getValue());
    }

    $post = $this->_request->getParam('info');

    if(is_array($post)){
        foreach($post as $key => $value){
            if($key == '' || $value == ''){
                continue;
            }

            $additionalOptions[] = [
                'label' => $key,
                'value' => $value
            ];
        }
    }

    if(count($additionalOptions) > 0){
        $item->addOption(array(
            'code' => 'additional_options',
            'value' => serialize($additionalOptions)
        ));
    }

When we add the configurable product with addition information in the cart then in shopping cart page display additional information with error Some item options or their combination are not currently available

Best Answer

Cart Quote Item Option data stored in the quote_item_option table. This table contains option_id, item_id, product_id, code and value fields.

I have to pass product_id, code and value data to the addOption function but missing to pass product_id. Refer the following code

$item = $observer->getQuoteItem();

    $additionalOptions = array();

    if ($additionalOption = $item->getOptionByCode('additional_options')){
        $additionalOptions = (array) unserialize($additionalOption->getValue());
    }

    $post = $this->_request->getParam('info');

    if(is_array($post)){
        foreach($post as $key => $value){
            if($key == '' || $value == ''){
                continue;
            }

            $additionalOptions[] = [
                'label' => $key,
                'value' => $value
            ];
        }
    }

    if(count($additionalOptions) > 0){
        $item->addOption(array(
            'product_id' => $item->getProductId(),//Missing data
            'code' => 'additional_options',
            'value' => serialize($additionalOptions)
        ));
    }