1

I am getting error during to save order data to xml format using observer..

Recoverable Error: Object of class Magento\Sales\Model\Order\Item\Interceptor could not be converted to string in

 namespace XYZ\Checkout\Observer;

 use Magento\Framework\Event\Observer as EventObserver;
 use Magento\Framework\Event\ObserverInterface;
 use Magento\Framework\Simplexml\Element as SimpleXMLElement;


  class Afterplaceorder implements ObserverInterface
   {     
     protected $_request;
     protected $_layout;
     protected $_objectManager;
     protected $_resource;
     protected $dir;
     protected $jsonHelper;
     protected $timezone;
     protected $_customerRepositoryInterface;
     protected $_io;
     protected $_cartExtension;


/**
* @param \Magento\Framework\ObjectManagerInterface $objectManager
*/
public function __construct(
    \Magento\Framework\View\Element\Context $context,
    \Magento\Framework\App\ResourceConnection $resource,
    \Magento\Framework\ObjectManagerInterface $objectmanager,
    \Magento\Framework\Filesystem\DirectoryList $dir,
    \Magento\Framework\Json\Helper\Data $jsonHelper,
    \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone,
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
    \Magento\Framework\Filesystem\Io\File $io,
    \Magento\Quote\Api\Data\CartExtension $cartExtension
){
    $this->_layout = $context->getLayout();
    $this->_request = $context->getRequest();
    $this->_objectManager = $objectmanager;
    $this->_resource = $resource;
    $this->_dir = $dir;
    $this->jsonHelper = $jsonHelper;
    $this->timezone = $timezone;
    $this->_customerRepositoryInterface = $customerRepositoryInterface;
    $this->_io = $io;
    $this->_cartExtension = $cartExtension;
}


/**
* @param \Magento\Framework\Event\Observer $observer
* @return void
*/
public function execute(EventObserver $observer)
{   
    $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/orderdata.log');
    $logger = new \Zend\Log\Logger();
    $logger->addWriter($writer);

    $order   = $observer->getData('order');
    $orderId = $order->getId();
    $QuoteId = $order->getQuoteId();
    $CustomerId = $order->getCustomerId();

    $logger->info(print_r($order->getIncrementId(),true));

    $quote = $observer->getQuote();

    try{        

        $LocalInstitute     = $quote->getLocalInstitute();
        $SocietyInstitute   = $quote->getLocalSociety();
        $AuthStatus         = $quote->getAuthStatus();
        $SentApi            = 1;
        $response           = 0;
        $NavOrderId         = " ";

        if($LocalInstitute):    
            $order->setLocalInstitute($LocalInstitute)->setLocalSociety($SocietyInstitute)->setAuthStatus($AuthStatus)->setApiSentFromMagento($SentApi)->setApiResponseFromNav($response)->setApiResponseNavOrderId($NavOrderId);
            $order->save();
        endif;  

        $customerDetails = array();             
        $orderItemsxml   = array();

        foreach($order->getItemsCollection() as $orderItem) 
            {
              $orderItemsxml[] = $orderItem;                
            }

            $orderDeatails['orderItems']      = $orderItemsxml;     
            $orderDeatails['billingAddress']  =     $order->getBillingAddress()->getData();
            $orderDeatails['shippingAddress'] = $order->getShippingAddress()->getData();

                // function defination to convert array to xml
                function array_to_xml( $data, &$xml_data ) {
                    foreach( $data as $key => $value ) {
                        if( is_numeric($key) ){
                            $key = 'item'.$key; //dealing with <0/>..<n/> issues
                        }
                        if( is_array($value) ) {
                            $subnode = $xml_data->addChild($key);
                            array_to_xml($value, $subnode);
                        } else {
                            $xml_data->addChild("$key",htmlspecialchars("$value"));
                        }
                     }
                }


                $data = array('total_stud' => 500);
                // creating object of SimpleXMLElement
                $xml_data = new SimpleXMLElement('<?xml version="1.0"?><order></order>');

                //$OrderCollection = array_merge($orderDeatails,$customerDetails);
                // function call to convert array to xml
                array_to_xml($orderDeatails,$xml_data);
                //saving generated xml file;
                if ( ! file_exists($this->_dir->getPath('var').'/api/order')) {
                    $this->_io->mkdir($this->_dir->getPath('var').'/api/order', 0775); 
                }
                $result = $xml_data->asXML($this->_dir->getRoot().'/var/api/order/order_'.$order->getIncrementId().'.xml');

        }catch(\Exception $e){
            $logger->info(print_r('error-> '.$e->getMessage(),true));
        }

        return; 
   }
 }

I didn't find what is wrong with my code.

Please anyone can resolve this..

2

I fond a solution for it

You can use jsonEncode and Decode to resolve the issue.

$this->jsonHelper->jsonDecode($this->jsonHelper->jsonEncode($order->getItemsCollection()));

Here is the full code

class Afterplaceorder implements ObserverInterface
{    
   protected $_Logs;

   public function __construct(
    \Magento\Framework\Json\Helper\Data $jsonHelper,
){
    $this->jsonHelper = $jsonHelper;
}

public function execute(EventObserver $observer)
{   
    $order   = $observer->getData('order');

    try{                    
            $orderDeatails['orderItems']      = $this->jsonHelper->jsonDecode($this->jsonHelper->jsonEncode($order->getItemsCollection()));

        }catch(\Exception $e){
            $logger->info(print_r('error-> '.$e->getMessage(),true));
        }

        return;

}

}

Its working well for me.

hope it will help others to resolve these kind of issues.

Thanks! Happy Coding!!

0

I suspect that one of the elements of sub elements of orderDeatails is the actual order object and when generating the xml you handle the cases where the element is numerical or array. Otherwise you treat it as a sting. And for the order object your script tries to convert it to string.
it could be the $orderItem elements. I think they contain a reference to the order object.

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.