Magento 2 – How to Make Billing Address Same as Shipping Address

magento2

In the guest customer checkout process if customer select paypal as a payment method it only store shipping address. So billing address are showing blank.

I have found an alternative way for that.

I am trying to save billing address same as shipping address after successfully place order. I have used observer for that.

Below is my code.

events.xml

<?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="checkout_onepage_controller_success_action">
        <observer name="bls_redirection_controller_success_action" instance="Bls\Redirection\Observer\MyObserver"  />
    </event>
</config>

MyObserver.php

<?php
namespace Bls\Redirection\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
class MyObserver implements ObserverInterface
{ 

    protected $orderRepository;
    protected $_customerFactory;
    protected $_addressFactory;

    public function __construct(  
    OrderRepositoryInterface $OrderRepositoryInterface,
    \Magento\Customer\Model\CustomerFactory $customerFactory,
    \Magento\Customer\Model\AddressFactory $addressFactory

    ) {
        $this->orderRepository = $OrderRepositoryInterface;
        $this->_customerFactory = $customerFactory;
        $this->_addressFactory = $addressFactory;

    }

    public function execute(\Magento\Framework\Event\Observer $observer) 
    {


          echo $order_ids = $observer->getEvent()->getOrderIds()[0];
            $order = $this->orderRepository->get($order_ids);           
           $order_id = $order->getIncrementId();   
           echo $customer_email = $order->getCustomerEmail();           
           $shippingaddress = $order->getShippingAddress()->getData();

            $addresss = $this->_addressFactory->create();
                    $address->setCustomerEmail("xyz@gmail.com")
                    ->setFirstname('test') //set firstname from shipping
                    ->setLastname('test') //set lastname from shipping
                    ->setCountryId('US') // from shipping
                    ->setRegionId('Texas') // from shipping
                    ->setPostcode('75244') // from shipping
                    ->setCity('Dallas') // from shipping
                    ->setTelephone('123456789') // from shipping
                    ->setFax('123456789') // from shipping
                    ->setCompany('test') // from shipping
                    ->setStreet('4099 McEwen Road Suite 516') // from shipping
                    ->setIsDefaultBilling('1');
                    try{
                            $address->save();
                    }
                    catch (Exception $e) {
                            Zend_Debug::dump($e->getMessage());
                    }



exit;

            //Get Payment Method
            $payment = $order->getPayment();
            $method = $payment->getMethodInstance();
            $methodTitle = $method->getTitle();
            $paymentmethod = $payment->getMethod();


    }
}

In my code I got all shipping address in $shippingadderss variable now I want to save this in billing address too.

Could anyone tell me how can I save shipping address in billing address.

I am getting below error

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`a76e6b4a_demo`.`customer_address_entity`, CONSTRAINT `CUSTOMER_ADDRESS_ENTITY_PARENT_ID_CUSTOMER_ENTITY_ENTITY_ID` FOREIGN KEY (`parent_id`) REFERENCES `customer_entity` (`entity_id`) ON DELE), query was: INSERT INTO `customer_address_entity` (`parent_id`, `created_at`, `updated_at`, `city`, `company`, `country_id`, `fax`, `firstname`, `lastname`, `postcode`, `region_id`, `street`, `telephone`) VALUES (?, '2019-01-30 13:56:26', '2019-01-30 13:56:26', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

Best Answer

Hi @Jaimin Can you please try this.

....
protected $orderRepository; 
   protected $_addressRepo; 

   public function __construct( 
      OrderRepositoryInterface $OrderRepositoryInterface,   
      \Magento\Sales\Model\Order\AddressRepository $addressRepo

      ) { 
      $this->orderRepository = $OrderRepositoryInterface;
      $this->_addressRepo = $addressRepo;

   } 

   public function execute(\Magento\Framework\Event\Observer $observer) 
   { 
//get Order Id
      $order_ids = $observer->getEvent()->getOrderIds()[0]; 
//Load Order Details from Id
      $order = $this->orderRepository->get($order_ids);
//get Shipping data
      $addressdata = $order->getShippingAddress()->getData();
      $regionid = $order->getShippingAddress()->getRegionId();
      $region = $order->getShippingAddress()->getRegion();
      $postcode = $order->getShippingAddress()->getPostcode();
      $lastname = $order->getShippingAddress()->getLastname();
      $street = $order->getShippingAddress()->getStreet();
      $city = $order->getShippingAddress()->getCity();
      $email = $order->getShippingAddress()->getEmail();
      $telephone = $order->getShippingAddress()->getTelephone();
      $countryid = $order->getShippingAddress()->getCountryId();
      $firstname = $order->getShippingAddress()->getFirstname();
      $company = $order->getShippingAddress()->getCompany();
//Get Billing Address Id
      $billingaddressId = $order->getBillingAddress()->getEntityId(); 
//Load Billing Address data from Id
      $billAddress = $this->_addressRepo->get($billingaddressId);
//Set Or Update Billing Address data.
      if($billAddress->getId())
      {
         $billAddress->setRegionId($regionid);
         $billAddress->setRegion($region);
         $billAddress->setPostcode($postcode);
         $billAddress->setLastname($lastname);
         $billAddress->setStreet($street);
         $billAddress->setCity($city);
         $billAddress->setEmail($email);
         $billAddress->setTelephone($telephone);
         $billAddress->setCountryId($countryid);
         $billAddress->setFirstname($firstname);
         $billAddress->setCompany($company);
//Save Billing Address Data.
         $this->_addressRepo->save($billAddress);
      }
   }
....
Related Topic