Can't retrieve custom option from order items












1















I am writing an extension where I need to place an order with the items already in the user's cart (added programmatically). I have been successful with this, however my orders lose custom options added via $_product->addCustomOption().



$addOptns['my_custom_option'] = 3;
foreach ($addOptns as $key => $value) {
$_product->addCustomOption( $key, $value);
}
$params = array(
'product' => 123, //product Id
'qty' => 100 //quantity of product
);
$this->_cart->addProduct(
$_product,
$params
);
$this->_cart->save();
$quote = $this->_cart->getQuote();

...[shipping and payment config]...

$order_id = $this->cartManagementInterface->placeOrder($quote->getId());


When I try to receive my_custom_option from the order that is placed, I get null.



var_dump($item->getCustomOptions()); // NULL


Any guess what is wrong with my approach?



Note: This is not a 'custom option' like those created in the admin UI nor do I expect it to be, I use these custom options for other customized processes and they are not directly user selectable.










share|improve this question





























    1















    I am writing an extension where I need to place an order with the items already in the user's cart (added programmatically). I have been successful with this, however my orders lose custom options added via $_product->addCustomOption().



    $addOptns['my_custom_option'] = 3;
    foreach ($addOptns as $key => $value) {
    $_product->addCustomOption( $key, $value);
    }
    $params = array(
    'product' => 123, //product Id
    'qty' => 100 //quantity of product
    );
    $this->_cart->addProduct(
    $_product,
    $params
    );
    $this->_cart->save();
    $quote = $this->_cart->getQuote();

    ...[shipping and payment config]...

    $order_id = $this->cartManagementInterface->placeOrder($quote->getId());


    When I try to receive my_custom_option from the order that is placed, I get null.



    var_dump($item->getCustomOptions()); // NULL


    Any guess what is wrong with my approach?



    Note: This is not a 'custom option' like those created in the admin UI nor do I expect it to be, I use these custom options for other customized processes and they are not directly user selectable.










    share|improve this question



























      1












      1








      1


      2






      I am writing an extension where I need to place an order with the items already in the user's cart (added programmatically). I have been successful with this, however my orders lose custom options added via $_product->addCustomOption().



      $addOptns['my_custom_option'] = 3;
      foreach ($addOptns as $key => $value) {
      $_product->addCustomOption( $key, $value);
      }
      $params = array(
      'product' => 123, //product Id
      'qty' => 100 //quantity of product
      );
      $this->_cart->addProduct(
      $_product,
      $params
      );
      $this->_cart->save();
      $quote = $this->_cart->getQuote();

      ...[shipping and payment config]...

      $order_id = $this->cartManagementInterface->placeOrder($quote->getId());


      When I try to receive my_custom_option from the order that is placed, I get null.



      var_dump($item->getCustomOptions()); // NULL


      Any guess what is wrong with my approach?



      Note: This is not a 'custom option' like those created in the admin UI nor do I expect it to be, I use these custom options for other customized processes and they are not directly user selectable.










      share|improve this question
















      I am writing an extension where I need to place an order with the items already in the user's cart (added programmatically). I have been successful with this, however my orders lose custom options added via $_product->addCustomOption().



      $addOptns['my_custom_option'] = 3;
      foreach ($addOptns as $key => $value) {
      $_product->addCustomOption( $key, $value);
      }
      $params = array(
      'product' => 123, //product Id
      'qty' => 100 //quantity of product
      );
      $this->_cart->addProduct(
      $_product,
      $params
      );
      $this->_cart->save();
      $quote = $this->_cart->getQuote();

      ...[shipping and payment config]...

      $order_id = $this->cartManagementInterface->placeOrder($quote->getId());


      When I try to receive my_custom_option from the order that is placed, I get null.



      var_dump($item->getCustomOptions()); // NULL


      Any guess what is wrong with my approach?



      Note: This is not a 'custom option' like those created in the admin UI nor do I expect it to be, I use these custom options for other customized processes and they are not directly user selectable.







      magento2 product cart






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 19 '18 at 17:44







      jamil

















      asked Jan 19 '18 at 17:02









      jamiljamil

      564425




      564425






















          3 Answers
          3






          active

          oldest

          votes


















          2





          +50









          Order object does not take custom options from quote but you can force it with event



          sales_model_service_quote_submit_before


          check this tutorial: https://www.cloudways.com/blog/add-additional-options-in-magento-2/. it covers your case completely






          share|improve this answer
























          • Thanks for this, it took some significant changes to work for my specific case but seems to work. I'm still surprised there isn't something more direct.

            – jamil
            Feb 2 '18 at 23:48











          • Yes the sales_model_service_quote_submit_before is not working, is there have any other event for accomplish the task

            – senthil
            May 11 '18 at 10:00





















          3














          You can achieve by a plugin in Magento 2.2.*



          First of all, we need to create an observer file and one Magento event file to implement this functionality.



          <?xml version="1.0"?>
          <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
          <event name="catalog_product_load_after">
          <observer name="set_additional_options" instance="CompanyNameModuleNameModelSetAdditionalOptions" />
          </event>
          </config>


          Once you have created this file, now you need to Create another file and named as: CompanyNameModuleName/Model/SetAdditionalOptions.php



          <?php
          namespace CompanyNameModuleNameModel;

          use MagentoFrameworkEventObserverInterface;
          use MagentoFrameworkAppRequestInterface;
          use MagentoFrameworkAppObjectManager;
          use MagentoFrameworkSerializeSerializerJson;

          class SetAdditionalOptions implements ObserverInterface
          {
          protected $_request;
          public function __construct(RequestInterface $request, Json $serializer = null)
          {
          $this->_request = $request;
          $this->serializer = $serializer ?: MagentoFrameworkAppObjectManager::getInstance()
          ->get(MagentoFrameworkSerializeSerializerJson::class);
          }

          /**
          * @param MagentoFrameworkEventObserver $observer
          */
          public function execute(MagentoFrameworkEventObserver $observer)
          {
          // Check and set information according to your need
          $product = $observer->getProduct();
          if ($this->_request->getFullActionName() == 'checkout_cart_add') { //checking when product is adding to cart
          $product = $observer->getProduct();
          $additionalOptions = ;
          $additionalOptions = array(
          'label' => "Release Date", //Custom option label
          'value' => $product->getReleaseDate(), //Custom option value
          );
          $product->addCustomOption('additional_options', $this->serializer->serialize($additionalOptions));
          }
          }

          }




          Now, We need to create a plugin for the retrieve custom option from cart to order.



          First We need to create di.xml.



          <?xml version="1.0"?>
          <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
          <type name="MagentoQuoteModelQuoteItemToOrderItem">
          <plugin name="unique_name" type="CompanyNameModuleNameModelPluginQuoteToOrderItem" sortOrder="1" />
          </type>
          </config>


          Once you have created this file, now you need to Create another file and named as: CompanyNameModuleNameModelPluginQuoteToOrderItem.php



          <?php
          namespace ZCompanyNameModuleNameModelPluginQuote;

          use MagentoQuoteModelQuoteItemToOrderItem as QuoteToOrderItem;
          use MagentoFrameworkSerializeSerializerJson;
          class ToOrderItem
          {
          public function __construct(Json $serializer = null)
          {
          $this->serializer = $serializer ?: MagentoFrameworkAppObjectManager::getInstance()
          ->get(MagentoFrameworkSerializeSerializerJson::class);
          }

          public function aroundConvert(QuoteToOrderItem $subject,
          Closure $proceed,
          $item,
          $data =
          ) {
          // Get Order Item
          $orderItem = $proceed($item, $data);

          $additionalOptions = $item->getOptionByCode('additional_options');
          // Check if there is any additional options in Quote Item
          if (count($additionalOptions) > 0) {
          // Get Order Item's other options
          $options = $orderItem->getProductOptions();
          // Set additional options to Order Item
          $options['additional_options'] = $this->serializer->unserialize($additionalOptions->getValue());
          $orderItem->setProductOptions($options);
          }

          return $orderItem;
          }
          }







          share|improve this answer
























          • Hi @dhairya Its working for me above version 2.2.*, you save my day bro!

            – Rajan Soni
            May 3 '18 at 5:56



















          0














          Retrieve custom options of products present any order



          $orderObject = $objectManager->get('MagentoSalesModelOrder'); 

          // load by order id
          $orderId = 1; // YOUR ORDER ID
          $order = $orderObject->load($orderId);

          // load by order increment id
          // $incrementId = '000000001'; // YOUR ORDER INCREMENT ID
          // $order = $orderObject->loadByIncrementId($incrementId);

          $items = $order->getAllVisibleItems(); // get all items aren't marked as deleted and that do not have parent item; for e.g. here associated simple products of a configurable products are not fetched

          // Order items can also be fetched with the following functions
          // $items = $order->getAllItems(); // get all items that are not marked as deleted
          // $items = $order->getItems(); // get all items

          foreach ($items as $item) {
          $options = $item->getProductOptions();
          if (isset($options['options']) && !empty($options['options'])) {
          foreach ($options['options'] as $option) {
          echo 'Title: ' . $option['label'] . '<br />';
          echo 'ID: ' . $option['option_id'] . '<br />';
          echo 'Type: ' . $option['option_type'] . '<br />';
          echo 'Value: ' . $option['option_value'] . '<br />' . '<br />';
          }
          }
          }


          However, using ObjectManager directly for that is not a great solution. You can still use the code with dependency injection as the below:




          • Open the block class Yourcompany_HelloWorld, then inject the object of MagentoSalesModelOrder in the constructor of my module’s block class.



          app/code/Yourcompany/HelloWorld/Block/HelloWorld.php




          <?php
          namespace YourcompanyHelloWorldBlock;
          class HelloWorld extends MagentoFrameworkViewElementTemplate
          {
          protected $_orderModel;

          public function __construct(
          MagentoBackendBlockTemplateContext $context,
          MagentoSalesModelOrder $orderModel,
          array $data =
          )
          {
          $this->_orderModel = $orderModel;
          parent::__construct($context, $data);
          }

          public function getOrderItems($orderId)
          {
          $order = $this->_orderModel->load($orderId);
          return $order->getAllVisibleItems();
          }
          }
          ?>



          Like that, you can use the function in the .phtml file.




          $orderId = 1; // YOUR ORDER ID
          $items = $block->getOrderItems($orderId);

          foreach ($items as $item) {
          $options = $item->getProductOptions();
          if (isset($options['options']) && !empty($options['options'])) {
          foreach ($options['options'] as $option) {
          echo 'Title: ' . $option['label'] . '<br />';
          echo 'ID: ' . $option['option_id'] . '<br />';
          echo 'Type: ' . $option['option_type'] . '<br />';
          echo 'Value: ' . $option['option_value'] . '<br />' . '<br />';
          }
          }
          }


          That is all things you will use to retrieve value product custom option cart order in Magento 2.






          share|improve this answer























            Your Answer








            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "479"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f210213%2fcant-retrieve-custom-option-from-order-items%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2





            +50









            Order object does not take custom options from quote but you can force it with event



            sales_model_service_quote_submit_before


            check this tutorial: https://www.cloudways.com/blog/add-additional-options-in-magento-2/. it covers your case completely






            share|improve this answer
























            • Thanks for this, it took some significant changes to work for my specific case but seems to work. I'm still surprised there isn't something more direct.

              – jamil
              Feb 2 '18 at 23:48











            • Yes the sales_model_service_quote_submit_before is not working, is there have any other event for accomplish the task

              – senthil
              May 11 '18 at 10:00


















            2





            +50









            Order object does not take custom options from quote but you can force it with event



            sales_model_service_quote_submit_before


            check this tutorial: https://www.cloudways.com/blog/add-additional-options-in-magento-2/. it covers your case completely






            share|improve this answer
























            • Thanks for this, it took some significant changes to work for my specific case but seems to work. I'm still surprised there isn't something more direct.

              – jamil
              Feb 2 '18 at 23:48











            • Yes the sales_model_service_quote_submit_before is not working, is there have any other event for accomplish the task

              – senthil
              May 11 '18 at 10:00
















            2





            +50







            2





            +50



            2




            +50





            Order object does not take custom options from quote but you can force it with event



            sales_model_service_quote_submit_before


            check this tutorial: https://www.cloudways.com/blog/add-additional-options-in-magento-2/. it covers your case completely






            share|improve this answer













            Order object does not take custom options from quote but you can force it with event



            sales_model_service_quote_submit_before


            check this tutorial: https://www.cloudways.com/blog/add-additional-options-in-magento-2/. it covers your case completely







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Feb 2 '18 at 11:31









            Vladimir SamsonovVladimir Samsonov

            42428




            42428













            • Thanks for this, it took some significant changes to work for my specific case but seems to work. I'm still surprised there isn't something more direct.

              – jamil
              Feb 2 '18 at 23:48











            • Yes the sales_model_service_quote_submit_before is not working, is there have any other event for accomplish the task

              – senthil
              May 11 '18 at 10:00





















            • Thanks for this, it took some significant changes to work for my specific case but seems to work. I'm still surprised there isn't something more direct.

              – jamil
              Feb 2 '18 at 23:48











            • Yes the sales_model_service_quote_submit_before is not working, is there have any other event for accomplish the task

              – senthil
              May 11 '18 at 10:00



















            Thanks for this, it took some significant changes to work for my specific case but seems to work. I'm still surprised there isn't something more direct.

            – jamil
            Feb 2 '18 at 23:48





            Thanks for this, it took some significant changes to work for my specific case but seems to work. I'm still surprised there isn't something more direct.

            – jamil
            Feb 2 '18 at 23:48













            Yes the sales_model_service_quote_submit_before is not working, is there have any other event for accomplish the task

            – senthil
            May 11 '18 at 10:00







            Yes the sales_model_service_quote_submit_before is not working, is there have any other event for accomplish the task

            – senthil
            May 11 '18 at 10:00















            3














            You can achieve by a plugin in Magento 2.2.*



            First of all, we need to create an observer file and one Magento event file to implement this functionality.



            <?xml version="1.0"?>
            <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
            <event name="catalog_product_load_after">
            <observer name="set_additional_options" instance="CompanyNameModuleNameModelSetAdditionalOptions" />
            </event>
            </config>


            Once you have created this file, now you need to Create another file and named as: CompanyNameModuleName/Model/SetAdditionalOptions.php



            <?php
            namespace CompanyNameModuleNameModel;

            use MagentoFrameworkEventObserverInterface;
            use MagentoFrameworkAppRequestInterface;
            use MagentoFrameworkAppObjectManager;
            use MagentoFrameworkSerializeSerializerJson;

            class SetAdditionalOptions implements ObserverInterface
            {
            protected $_request;
            public function __construct(RequestInterface $request, Json $serializer = null)
            {
            $this->_request = $request;
            $this->serializer = $serializer ?: MagentoFrameworkAppObjectManager::getInstance()
            ->get(MagentoFrameworkSerializeSerializerJson::class);
            }

            /**
            * @param MagentoFrameworkEventObserver $observer
            */
            public function execute(MagentoFrameworkEventObserver $observer)
            {
            // Check and set information according to your need
            $product = $observer->getProduct();
            if ($this->_request->getFullActionName() == 'checkout_cart_add') { //checking when product is adding to cart
            $product = $observer->getProduct();
            $additionalOptions = ;
            $additionalOptions = array(
            'label' => "Release Date", //Custom option label
            'value' => $product->getReleaseDate(), //Custom option value
            );
            $product->addCustomOption('additional_options', $this->serializer->serialize($additionalOptions));
            }
            }

            }




            Now, We need to create a plugin for the retrieve custom option from cart to order.



            First We need to create di.xml.



            <?xml version="1.0"?>
            <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
            <type name="MagentoQuoteModelQuoteItemToOrderItem">
            <plugin name="unique_name" type="CompanyNameModuleNameModelPluginQuoteToOrderItem" sortOrder="1" />
            </type>
            </config>


            Once you have created this file, now you need to Create another file and named as: CompanyNameModuleNameModelPluginQuoteToOrderItem.php



            <?php
            namespace ZCompanyNameModuleNameModelPluginQuote;

            use MagentoQuoteModelQuoteItemToOrderItem as QuoteToOrderItem;
            use MagentoFrameworkSerializeSerializerJson;
            class ToOrderItem
            {
            public function __construct(Json $serializer = null)
            {
            $this->serializer = $serializer ?: MagentoFrameworkAppObjectManager::getInstance()
            ->get(MagentoFrameworkSerializeSerializerJson::class);
            }

            public function aroundConvert(QuoteToOrderItem $subject,
            Closure $proceed,
            $item,
            $data =
            ) {
            // Get Order Item
            $orderItem = $proceed($item, $data);

            $additionalOptions = $item->getOptionByCode('additional_options');
            // Check if there is any additional options in Quote Item
            if (count($additionalOptions) > 0) {
            // Get Order Item's other options
            $options = $orderItem->getProductOptions();
            // Set additional options to Order Item
            $options['additional_options'] = $this->serializer->unserialize($additionalOptions->getValue());
            $orderItem->setProductOptions($options);
            }

            return $orderItem;
            }
            }







            share|improve this answer
























            • Hi @dhairya Its working for me above version 2.2.*, you save my day bro!

              – Rajan Soni
              May 3 '18 at 5:56
















            3














            You can achieve by a plugin in Magento 2.2.*



            First of all, we need to create an observer file and one Magento event file to implement this functionality.



            <?xml version="1.0"?>
            <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
            <event name="catalog_product_load_after">
            <observer name="set_additional_options" instance="CompanyNameModuleNameModelSetAdditionalOptions" />
            </event>
            </config>


            Once you have created this file, now you need to Create another file and named as: CompanyNameModuleName/Model/SetAdditionalOptions.php



            <?php
            namespace CompanyNameModuleNameModel;

            use MagentoFrameworkEventObserverInterface;
            use MagentoFrameworkAppRequestInterface;
            use MagentoFrameworkAppObjectManager;
            use MagentoFrameworkSerializeSerializerJson;

            class SetAdditionalOptions implements ObserverInterface
            {
            protected $_request;
            public function __construct(RequestInterface $request, Json $serializer = null)
            {
            $this->_request = $request;
            $this->serializer = $serializer ?: MagentoFrameworkAppObjectManager::getInstance()
            ->get(MagentoFrameworkSerializeSerializerJson::class);
            }

            /**
            * @param MagentoFrameworkEventObserver $observer
            */
            public function execute(MagentoFrameworkEventObserver $observer)
            {
            // Check and set information according to your need
            $product = $observer->getProduct();
            if ($this->_request->getFullActionName() == 'checkout_cart_add') { //checking when product is adding to cart
            $product = $observer->getProduct();
            $additionalOptions = ;
            $additionalOptions = array(
            'label' => "Release Date", //Custom option label
            'value' => $product->getReleaseDate(), //Custom option value
            );
            $product->addCustomOption('additional_options', $this->serializer->serialize($additionalOptions));
            }
            }

            }




            Now, We need to create a plugin for the retrieve custom option from cart to order.



            First We need to create di.xml.



            <?xml version="1.0"?>
            <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
            <type name="MagentoQuoteModelQuoteItemToOrderItem">
            <plugin name="unique_name" type="CompanyNameModuleNameModelPluginQuoteToOrderItem" sortOrder="1" />
            </type>
            </config>


            Once you have created this file, now you need to Create another file and named as: CompanyNameModuleNameModelPluginQuoteToOrderItem.php



            <?php
            namespace ZCompanyNameModuleNameModelPluginQuote;

            use MagentoQuoteModelQuoteItemToOrderItem as QuoteToOrderItem;
            use MagentoFrameworkSerializeSerializerJson;
            class ToOrderItem
            {
            public function __construct(Json $serializer = null)
            {
            $this->serializer = $serializer ?: MagentoFrameworkAppObjectManager::getInstance()
            ->get(MagentoFrameworkSerializeSerializerJson::class);
            }

            public function aroundConvert(QuoteToOrderItem $subject,
            Closure $proceed,
            $item,
            $data =
            ) {
            // Get Order Item
            $orderItem = $proceed($item, $data);

            $additionalOptions = $item->getOptionByCode('additional_options');
            // Check if there is any additional options in Quote Item
            if (count($additionalOptions) > 0) {
            // Get Order Item's other options
            $options = $orderItem->getProductOptions();
            // Set additional options to Order Item
            $options['additional_options'] = $this->serializer->unserialize($additionalOptions->getValue());
            $orderItem->setProductOptions($options);
            }

            return $orderItem;
            }
            }







            share|improve this answer
























            • Hi @dhairya Its working for me above version 2.2.*, you save my day bro!

              – Rajan Soni
              May 3 '18 at 5:56














            3












            3








            3







            You can achieve by a plugin in Magento 2.2.*



            First of all, we need to create an observer file and one Magento event file to implement this functionality.



            <?xml version="1.0"?>
            <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
            <event name="catalog_product_load_after">
            <observer name="set_additional_options" instance="CompanyNameModuleNameModelSetAdditionalOptions" />
            </event>
            </config>


            Once you have created this file, now you need to Create another file and named as: CompanyNameModuleName/Model/SetAdditionalOptions.php



            <?php
            namespace CompanyNameModuleNameModel;

            use MagentoFrameworkEventObserverInterface;
            use MagentoFrameworkAppRequestInterface;
            use MagentoFrameworkAppObjectManager;
            use MagentoFrameworkSerializeSerializerJson;

            class SetAdditionalOptions implements ObserverInterface
            {
            protected $_request;
            public function __construct(RequestInterface $request, Json $serializer = null)
            {
            $this->_request = $request;
            $this->serializer = $serializer ?: MagentoFrameworkAppObjectManager::getInstance()
            ->get(MagentoFrameworkSerializeSerializerJson::class);
            }

            /**
            * @param MagentoFrameworkEventObserver $observer
            */
            public function execute(MagentoFrameworkEventObserver $observer)
            {
            // Check and set information according to your need
            $product = $observer->getProduct();
            if ($this->_request->getFullActionName() == 'checkout_cart_add') { //checking when product is adding to cart
            $product = $observer->getProduct();
            $additionalOptions = ;
            $additionalOptions = array(
            'label' => "Release Date", //Custom option label
            'value' => $product->getReleaseDate(), //Custom option value
            );
            $product->addCustomOption('additional_options', $this->serializer->serialize($additionalOptions));
            }
            }

            }




            Now, We need to create a plugin for the retrieve custom option from cart to order.



            First We need to create di.xml.



            <?xml version="1.0"?>
            <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
            <type name="MagentoQuoteModelQuoteItemToOrderItem">
            <plugin name="unique_name" type="CompanyNameModuleNameModelPluginQuoteToOrderItem" sortOrder="1" />
            </type>
            </config>


            Once you have created this file, now you need to Create another file and named as: CompanyNameModuleNameModelPluginQuoteToOrderItem.php



            <?php
            namespace ZCompanyNameModuleNameModelPluginQuote;

            use MagentoQuoteModelQuoteItemToOrderItem as QuoteToOrderItem;
            use MagentoFrameworkSerializeSerializerJson;
            class ToOrderItem
            {
            public function __construct(Json $serializer = null)
            {
            $this->serializer = $serializer ?: MagentoFrameworkAppObjectManager::getInstance()
            ->get(MagentoFrameworkSerializeSerializerJson::class);
            }

            public function aroundConvert(QuoteToOrderItem $subject,
            Closure $proceed,
            $item,
            $data =
            ) {
            // Get Order Item
            $orderItem = $proceed($item, $data);

            $additionalOptions = $item->getOptionByCode('additional_options');
            // Check if there is any additional options in Quote Item
            if (count($additionalOptions) > 0) {
            // Get Order Item's other options
            $options = $orderItem->getProductOptions();
            // Set additional options to Order Item
            $options['additional_options'] = $this->serializer->unserialize($additionalOptions->getValue());
            $orderItem->setProductOptions($options);
            }

            return $orderItem;
            }
            }







            share|improve this answer













            You can achieve by a plugin in Magento 2.2.*



            First of all, we need to create an observer file and one Magento event file to implement this functionality.



            <?xml version="1.0"?>
            <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
            <event name="catalog_product_load_after">
            <observer name="set_additional_options" instance="CompanyNameModuleNameModelSetAdditionalOptions" />
            </event>
            </config>


            Once you have created this file, now you need to Create another file and named as: CompanyNameModuleName/Model/SetAdditionalOptions.php



            <?php
            namespace CompanyNameModuleNameModel;

            use MagentoFrameworkEventObserverInterface;
            use MagentoFrameworkAppRequestInterface;
            use MagentoFrameworkAppObjectManager;
            use MagentoFrameworkSerializeSerializerJson;

            class SetAdditionalOptions implements ObserverInterface
            {
            protected $_request;
            public function __construct(RequestInterface $request, Json $serializer = null)
            {
            $this->_request = $request;
            $this->serializer = $serializer ?: MagentoFrameworkAppObjectManager::getInstance()
            ->get(MagentoFrameworkSerializeSerializerJson::class);
            }

            /**
            * @param MagentoFrameworkEventObserver $observer
            */
            public function execute(MagentoFrameworkEventObserver $observer)
            {
            // Check and set information according to your need
            $product = $observer->getProduct();
            if ($this->_request->getFullActionName() == 'checkout_cart_add') { //checking when product is adding to cart
            $product = $observer->getProduct();
            $additionalOptions = ;
            $additionalOptions = array(
            'label' => "Release Date", //Custom option label
            'value' => $product->getReleaseDate(), //Custom option value
            );
            $product->addCustomOption('additional_options', $this->serializer->serialize($additionalOptions));
            }
            }

            }




            Now, We need to create a plugin for the retrieve custom option from cart to order.



            First We need to create di.xml.



            <?xml version="1.0"?>
            <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
            <type name="MagentoQuoteModelQuoteItemToOrderItem">
            <plugin name="unique_name" type="CompanyNameModuleNameModelPluginQuoteToOrderItem" sortOrder="1" />
            </type>
            </config>


            Once you have created this file, now you need to Create another file and named as: CompanyNameModuleNameModelPluginQuoteToOrderItem.php



            <?php
            namespace ZCompanyNameModuleNameModelPluginQuote;

            use MagentoQuoteModelQuoteItemToOrderItem as QuoteToOrderItem;
            use MagentoFrameworkSerializeSerializerJson;
            class ToOrderItem
            {
            public function __construct(Json $serializer = null)
            {
            $this->serializer = $serializer ?: MagentoFrameworkAppObjectManager::getInstance()
            ->get(MagentoFrameworkSerializeSerializerJson::class);
            }

            public function aroundConvert(QuoteToOrderItem $subject,
            Closure $proceed,
            $item,
            $data =
            ) {
            // Get Order Item
            $orderItem = $proceed($item, $data);

            $additionalOptions = $item->getOptionByCode('additional_options');
            // Check if there is any additional options in Quote Item
            if (count($additionalOptions) > 0) {
            // Get Order Item's other options
            $options = $orderItem->getProductOptions();
            // Set additional options to Order Item
            $options['additional_options'] = $this->serializer->unserialize($additionalOptions->getValue());
            $orderItem->setProductOptions($options);
            }

            return $orderItem;
            }
            }








            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered May 3 '18 at 5:53









            shah dhairyashah dhairya

            913




            913













            • Hi @dhairya Its working for me above version 2.2.*, you save my day bro!

              – Rajan Soni
              May 3 '18 at 5:56



















            • Hi @dhairya Its working for me above version 2.2.*, you save my day bro!

              – Rajan Soni
              May 3 '18 at 5:56

















            Hi @dhairya Its working for me above version 2.2.*, you save my day bro!

            – Rajan Soni
            May 3 '18 at 5:56





            Hi @dhairya Its working for me above version 2.2.*, you save my day bro!

            – Rajan Soni
            May 3 '18 at 5:56











            0














            Retrieve custom options of products present any order



            $orderObject = $objectManager->get('MagentoSalesModelOrder'); 

            // load by order id
            $orderId = 1; // YOUR ORDER ID
            $order = $orderObject->load($orderId);

            // load by order increment id
            // $incrementId = '000000001'; // YOUR ORDER INCREMENT ID
            // $order = $orderObject->loadByIncrementId($incrementId);

            $items = $order->getAllVisibleItems(); // get all items aren't marked as deleted and that do not have parent item; for e.g. here associated simple products of a configurable products are not fetched

            // Order items can also be fetched with the following functions
            // $items = $order->getAllItems(); // get all items that are not marked as deleted
            // $items = $order->getItems(); // get all items

            foreach ($items as $item) {
            $options = $item->getProductOptions();
            if (isset($options['options']) && !empty($options['options'])) {
            foreach ($options['options'] as $option) {
            echo 'Title: ' . $option['label'] . '<br />';
            echo 'ID: ' . $option['option_id'] . '<br />';
            echo 'Type: ' . $option['option_type'] . '<br />';
            echo 'Value: ' . $option['option_value'] . '<br />' . '<br />';
            }
            }
            }


            However, using ObjectManager directly for that is not a great solution. You can still use the code with dependency injection as the below:




            • Open the block class Yourcompany_HelloWorld, then inject the object of MagentoSalesModelOrder in the constructor of my module’s block class.



            app/code/Yourcompany/HelloWorld/Block/HelloWorld.php




            <?php
            namespace YourcompanyHelloWorldBlock;
            class HelloWorld extends MagentoFrameworkViewElementTemplate
            {
            protected $_orderModel;

            public function __construct(
            MagentoBackendBlockTemplateContext $context,
            MagentoSalesModelOrder $orderModel,
            array $data =
            )
            {
            $this->_orderModel = $orderModel;
            parent::__construct($context, $data);
            }

            public function getOrderItems($orderId)
            {
            $order = $this->_orderModel->load($orderId);
            return $order->getAllVisibleItems();
            }
            }
            ?>



            Like that, you can use the function in the .phtml file.




            $orderId = 1; // YOUR ORDER ID
            $items = $block->getOrderItems($orderId);

            foreach ($items as $item) {
            $options = $item->getProductOptions();
            if (isset($options['options']) && !empty($options['options'])) {
            foreach ($options['options'] as $option) {
            echo 'Title: ' . $option['label'] . '<br />';
            echo 'ID: ' . $option['option_id'] . '<br />';
            echo 'Type: ' . $option['option_type'] . '<br />';
            echo 'Value: ' . $option['option_value'] . '<br />' . '<br />';
            }
            }
            }


            That is all things you will use to retrieve value product custom option cart order in Magento 2.






            share|improve this answer




























              0














              Retrieve custom options of products present any order



              $orderObject = $objectManager->get('MagentoSalesModelOrder'); 

              // load by order id
              $orderId = 1; // YOUR ORDER ID
              $order = $orderObject->load($orderId);

              // load by order increment id
              // $incrementId = '000000001'; // YOUR ORDER INCREMENT ID
              // $order = $orderObject->loadByIncrementId($incrementId);

              $items = $order->getAllVisibleItems(); // get all items aren't marked as deleted and that do not have parent item; for e.g. here associated simple products of a configurable products are not fetched

              // Order items can also be fetched with the following functions
              // $items = $order->getAllItems(); // get all items that are not marked as deleted
              // $items = $order->getItems(); // get all items

              foreach ($items as $item) {
              $options = $item->getProductOptions();
              if (isset($options['options']) && !empty($options['options'])) {
              foreach ($options['options'] as $option) {
              echo 'Title: ' . $option['label'] . '<br />';
              echo 'ID: ' . $option['option_id'] . '<br />';
              echo 'Type: ' . $option['option_type'] . '<br />';
              echo 'Value: ' . $option['option_value'] . '<br />' . '<br />';
              }
              }
              }


              However, using ObjectManager directly for that is not a great solution. You can still use the code with dependency injection as the below:




              • Open the block class Yourcompany_HelloWorld, then inject the object of MagentoSalesModelOrder in the constructor of my module’s block class.



              app/code/Yourcompany/HelloWorld/Block/HelloWorld.php




              <?php
              namespace YourcompanyHelloWorldBlock;
              class HelloWorld extends MagentoFrameworkViewElementTemplate
              {
              protected $_orderModel;

              public function __construct(
              MagentoBackendBlockTemplateContext $context,
              MagentoSalesModelOrder $orderModel,
              array $data =
              )
              {
              $this->_orderModel = $orderModel;
              parent::__construct($context, $data);
              }

              public function getOrderItems($orderId)
              {
              $order = $this->_orderModel->load($orderId);
              return $order->getAllVisibleItems();
              }
              }
              ?>



              Like that, you can use the function in the .phtml file.




              $orderId = 1; // YOUR ORDER ID
              $items = $block->getOrderItems($orderId);

              foreach ($items as $item) {
              $options = $item->getProductOptions();
              if (isset($options['options']) && !empty($options['options'])) {
              foreach ($options['options'] as $option) {
              echo 'Title: ' . $option['label'] . '<br />';
              echo 'ID: ' . $option['option_id'] . '<br />';
              echo 'Type: ' . $option['option_type'] . '<br />';
              echo 'Value: ' . $option['option_value'] . '<br />' . '<br />';
              }
              }
              }


              That is all things you will use to retrieve value product custom option cart order in Magento 2.






              share|improve this answer


























                0












                0








                0







                Retrieve custom options of products present any order



                $orderObject = $objectManager->get('MagentoSalesModelOrder'); 

                // load by order id
                $orderId = 1; // YOUR ORDER ID
                $order = $orderObject->load($orderId);

                // load by order increment id
                // $incrementId = '000000001'; // YOUR ORDER INCREMENT ID
                // $order = $orderObject->loadByIncrementId($incrementId);

                $items = $order->getAllVisibleItems(); // get all items aren't marked as deleted and that do not have parent item; for e.g. here associated simple products of a configurable products are not fetched

                // Order items can also be fetched with the following functions
                // $items = $order->getAllItems(); // get all items that are not marked as deleted
                // $items = $order->getItems(); // get all items

                foreach ($items as $item) {
                $options = $item->getProductOptions();
                if (isset($options['options']) && !empty($options['options'])) {
                foreach ($options['options'] as $option) {
                echo 'Title: ' . $option['label'] . '<br />';
                echo 'ID: ' . $option['option_id'] . '<br />';
                echo 'Type: ' . $option['option_type'] . '<br />';
                echo 'Value: ' . $option['option_value'] . '<br />' . '<br />';
                }
                }
                }


                However, using ObjectManager directly for that is not a great solution. You can still use the code with dependency injection as the below:




                • Open the block class Yourcompany_HelloWorld, then inject the object of MagentoSalesModelOrder in the constructor of my module’s block class.



                app/code/Yourcompany/HelloWorld/Block/HelloWorld.php




                <?php
                namespace YourcompanyHelloWorldBlock;
                class HelloWorld extends MagentoFrameworkViewElementTemplate
                {
                protected $_orderModel;

                public function __construct(
                MagentoBackendBlockTemplateContext $context,
                MagentoSalesModelOrder $orderModel,
                array $data =
                )
                {
                $this->_orderModel = $orderModel;
                parent::__construct($context, $data);
                }

                public function getOrderItems($orderId)
                {
                $order = $this->_orderModel->load($orderId);
                return $order->getAllVisibleItems();
                }
                }
                ?>



                Like that, you can use the function in the .phtml file.




                $orderId = 1; // YOUR ORDER ID
                $items = $block->getOrderItems($orderId);

                foreach ($items as $item) {
                $options = $item->getProductOptions();
                if (isset($options['options']) && !empty($options['options'])) {
                foreach ($options['options'] as $option) {
                echo 'Title: ' . $option['label'] . '<br />';
                echo 'ID: ' . $option['option_id'] . '<br />';
                echo 'Type: ' . $option['option_type'] . '<br />';
                echo 'Value: ' . $option['option_value'] . '<br />' . '<br />';
                }
                }
                }


                That is all things you will use to retrieve value product custom option cart order in Magento 2.






                share|improve this answer













                Retrieve custom options of products present any order



                $orderObject = $objectManager->get('MagentoSalesModelOrder'); 

                // load by order id
                $orderId = 1; // YOUR ORDER ID
                $order = $orderObject->load($orderId);

                // load by order increment id
                // $incrementId = '000000001'; // YOUR ORDER INCREMENT ID
                // $order = $orderObject->loadByIncrementId($incrementId);

                $items = $order->getAllVisibleItems(); // get all items aren't marked as deleted and that do not have parent item; for e.g. here associated simple products of a configurable products are not fetched

                // Order items can also be fetched with the following functions
                // $items = $order->getAllItems(); // get all items that are not marked as deleted
                // $items = $order->getItems(); // get all items

                foreach ($items as $item) {
                $options = $item->getProductOptions();
                if (isset($options['options']) && !empty($options['options'])) {
                foreach ($options['options'] as $option) {
                echo 'Title: ' . $option['label'] . '<br />';
                echo 'ID: ' . $option['option_id'] . '<br />';
                echo 'Type: ' . $option['option_type'] . '<br />';
                echo 'Value: ' . $option['option_value'] . '<br />' . '<br />';
                }
                }
                }


                However, using ObjectManager directly for that is not a great solution. You can still use the code with dependency injection as the below:




                • Open the block class Yourcompany_HelloWorld, then inject the object of MagentoSalesModelOrder in the constructor of my module’s block class.



                app/code/Yourcompany/HelloWorld/Block/HelloWorld.php




                <?php
                namespace YourcompanyHelloWorldBlock;
                class HelloWorld extends MagentoFrameworkViewElementTemplate
                {
                protected $_orderModel;

                public function __construct(
                MagentoBackendBlockTemplateContext $context,
                MagentoSalesModelOrder $orderModel,
                array $data =
                )
                {
                $this->_orderModel = $orderModel;
                parent::__construct($context, $data);
                }

                public function getOrderItems($orderId)
                {
                $order = $this->_orderModel->load($orderId);
                return $order->getAllVisibleItems();
                }
                }
                ?>



                Like that, you can use the function in the .phtml file.




                $orderId = 1; // YOUR ORDER ID
                $items = $block->getOrderItems($orderId);

                foreach ($items as $item) {
                $options = $item->getProductOptions();
                if (isset($options['options']) && !empty($options['options'])) {
                foreach ($options['options'] as $option) {
                echo 'Title: ' . $option['label'] . '<br />';
                echo 'ID: ' . $option['option_id'] . '<br />';
                echo 'Type: ' . $option['option_type'] . '<br />';
                echo 'Value: ' . $option['option_value'] . '<br />' . '<br />';
                }
                }
                }


                That is all things you will use to retrieve value product custom option cart order in Magento 2.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 18 mins ago









                DhruminDhrumin

                491418




                491418






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Magento Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f210213%2fcant-retrieve-custom-option-from-order-items%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    What other Star Trek series did the main TNG cast show up in?

                    Berlina muro

                    Berlina aerponto