0

i am trying to add product to cart with addition option but i ended up with message: "Unable to unserialize value." this error on console resoponse on section refresh.

Console

I am using checkout_cart_product_add_after event and observer code like below.

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

    $additionalOptions[] = [
        'label' => 'Additional Options Label',
        'value' => 'Additional Options Value',
    ];

    if (count($additionalOptions) > 0) {
        $item->addOption(array(
            'product_id' => $item->getProductId(),
            'code' => 'additional_options',
            'value' => serialize($additionalOptions),
        ));
    }
  • What is inside $additionalOption->getValue()? – Siarhey Uchukhlebau May 15 at 13:38
  • to make sure if anything exist in additional option then it won't overwrite – MageLerner May 16 at 5:51
1

Use json_encode instead serialize

public function execute(EventObserver $observer) {

    $additionalOptions = array();
    if ($additionalOption = $item->getOptionByCode('additional_options')) {
        $additionalOptions = (array) unserialize($additionalOption->getValue());
    }
    $additionalOptions[] = [
        'label' => 'helllo',
        'value' => 'vaddfsd',
    ];

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

}
0

A lot of previously serlialised stuff in m2 is now json encoded. Try json decode instead?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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