{"id":2494,"date":"2024-08-20T20:22:33","date_gmt":"2024-08-20T20:22:33","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/how-to-dynamically-change-billing-address-in-magento-2\/"},"modified":"2025-07-16T16:44:52","modified_gmt":"2025-07-16T11:14:52","slug":"dynamically-change-billing-address-in-magento-2","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/dynamically-change-billing-address-in-magento-2\/","title":{"rendered":"How to Dynamically Change Billing Address in Magento 2"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">In this blog post, I have provided a complete solution to&nbsp;<em><strong>dynamically change billing address<\/strong><\/em>&nbsp;in Magento 2.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The billing address defines a physical location\/address where the invoices or bills of the online orders are sent to the customers. In special cases, you may require to dynamically change the billing address of specific customers after placing the orders on your\u00a0Magento 2\u00a0store.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Suppose you are running an online store on Magento 2 and have tied up with another company to deliver some essential products to their employees. In that case, you may require to dynamically change the shipping address of such orders to that of the company where you want to send the invoices. This process can be made easier if your e-commerce platform allows for the management of&nbsp;<a href=\"https:\/\/meetanshi.com\/blog\/configure-multiple-shipping-addresses-in-magento-2\/\">multiple shipping addresses<\/a>, as you can easily add and switch between different addresses for your orders<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To do that, you might need to define customers\u2019 attributes and change the billing addresses of customers having specific attributes. You can refer to the programmatic solution provided here for that.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">app\/code\/Vendor\/Module\/registration.php\n \n&lt;?php\n \nuse Magento\\Framework\\Component\\ComponentRegistrar;\n \nComponentRegistrar::register(\n    ComponentRegistrar::MODULE,\n    'Vendor_Module',\n    __DIR__\n);<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">After registering and creating the module, you need to create a custom event that can be dispatched when the customer places an order. Create an&nbsp;<em><strong>events.xml<\/strong><\/em>&nbsp;file at&nbsp;<strong>app\/code\/Vendor\/Extension\/etc\/<\/strong>&nbsp;with the following code:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">app\/code\/Vendor\/Module\/etc\/module.xml\n \n&lt;?xml version=\"1.0\"?>\n&lt;config xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:Module\/etc\/module.xsd\">\n    &lt;module name=\"Vendor_Module\" setup_version=\"1.0.0\">\n    &lt;\/module>\n&lt;\/config><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, you need to add an obersever that dynamically changes the customer\u2019s billing address once the order is placed. Create a&nbsp;<strong><em>AfterPlaceOrder.php<\/em>&nbsp;<\/strong>file at&nbsp;<strong>app\/code\/Vendor\/Extension\/Observer\/&nbsp;<\/strong>directory with the following code:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">app\/code\/Vendor\/Extension\/etc\/events.xml\n \n &lt;event name=\"checkout_onepage_controller_success_action\">\n        &lt;observer name=\"vendor_extension_order_place_after \"\n                  instance=\"Vendor\\Extension\\Observer\\AfterPlaceOrder\"\/>\n    &lt;\/event>\n \n4) app\/code\/Vendor\/Extension\/Observer\/AfterPlaceOrder.php\n \n&lt;?php\n \n \nnamespace Vendor\\Extension\\Observer;\n \nuse Exception;\nuse Magento\\Framework\\DataObject;\nuse Magento\\Framework\\Event\\Observer as EventObserver;\nuse Magento\\Framework\\Event\\ObserverInterface;\nuse Magento\\Framework\\Exception\\AlreadyExistsException;\nuse Magento\\Framework\\Message\\ManagerInterface;\nuse Magento\\Sales\\Model\\Order;\nuse Magento\\Sales\\Model\\OrderFactory;\nuse Magento\\Sales\\Model\\ResourceModel\\OrderFactory as OrderResourceModelFactory;\nuse Magento\\Directory\\Model\\ResourceModel\\Region\\CollectionFactory as RegionCollectionFactory;\n \n\/**\n * Class AfterPlaceOrder\n *\/\nclass AfterPlaceOrder implements ObserverInterface\n{\n    \/**\n     * @var RegionCollectionFactory\n     *\/\n    private $regionCollectionFactory;\n    \/**\n     * @var OrderResourceModelFactory\n     *\/\n    private $orderResourceModelFactory;\n \n    \/**\n     * @var OrderFactory\n     *\/\n    protected $orderModel;\n    \/**\n     * @var ManagerInterface\n     *\/\n    private $messageManager;\n \n    \/**\n     * PlaceOrder constructor.\n     * @param ManagerInterface $messageManager\n     * @param OrderResourceModelFactory $orderResourceModelFactory\n     * @param RegionCollectionFactory $regionCollectionFactory\n     * @param OrderFactory $orderModel\n     *\/\n    public function __construct(\n        ManagerInterface $messageManager,\n        OrderResourceModelFactory $orderResourceModelFactory,\n        RegionCollectionFactory $regionCollectionFactory,\n        OrderFactory $orderModel\n    ) {\n        $this->regionCollectionFactory = $regionCollectionFactory;\n        $this->orderResourceModelFactory = $orderResourceModelFactory;\n        $this->orderModel = $orderModel;\n        $this->messageManager = $messageManager;\n    }\n \n    \/**\n     * @param EventObserver $observer\n     * @throws Exception\n     *\/\n    public function execute(EventObserver $observer)\n    {\n        try {\n            \/**\n             * @var Order $order\n             *\/\n \n            $order = $observer->getEvent()->getOrder();\n            if ($order == null) {\n                $orders = $observer->getEvent()->getOrders();\n                foreach ($orders as $order) {\n                    $this->setBillingAddress($order);\n                }\n            } else {\n                $this->setBillingAddress($order);\n            }\n        } catch (Exception $e) {\n            $this->messageManager->addErrorMessage($e->getMessage());\n        }\n    }\n \n    \/**\n     * @param $order\n     * @throws AlreadyExistsException\n     *\/\n    public function setBillingAddress($order)\n    {\n        $regionInfo = $this->getRegionInfo('South Australia');\n        $order->getBillingAddress()->setStreet('street line');\n        $order->getBillingAddress()->setCity('melbourne');\n        $order->getBillingAddress()->setPostcode('3002');\n        $order->getBillingAddress()->setCountryId('AU');\n        $order->getBillingAddress()->setRegionId($regionInfo->getRegionId());\n        $order->getBillingAddress()->setRegionCode($regionInfo->getRegionCode());\n        $order->getBillingAddress()->setRegion('South Australia');\n        $order->getBillingAddress()->setTelephone('12456465');\n        $this->orderResourceModelFactory->create()->save($order);\n    }\n \n    \/**\n     * @param string $regionName\n     * @return DataObject\n     *\/\n    public function getRegionInfo(string $regionName)\n    {\n        return $this->regionCollectionFactory->create()\n            ->addRegionNameFilter($regionName)\n            ->getFirstItem();\n    }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can change the edit the observer file as per your requirements to dynamically change billing address in Magento 2.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Magento 2 store owners can use this programmatic solution to change the billing address of orders dynamically as per their requirements.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Also read:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/meetanshi.com\/blog\/add-or-remove-address-field-from-pdf-in-magento-2\/\" target=\"_blank\" rel=\"noreferrer noopener\">How to Add or Remove Address Field from PDF in Magento 2<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/meetanshi.com\/blog\/change-shipping-price-on-address-field-change-in-magento-2-custom-shipping-method\/\" target=\"_blank\" rel=\"noreferrer noopener\">How to Change Shipping Price on Address Field Change in Magento 2 Custom Shipping Method<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/meetanshi.com\/blog\/change-number-of-lines-in-street-address-in-magento-2\/\" target=\"_blank\" rel=\"noreferrer noopener\">How to Change Number of Lines in Street Address in Magento 2<\/a><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Also, do not forget to share this Magento 2 solution with your Magento friends via social media.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Thanks for reading.  <\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this blog post, I have provided a complete solution to&nbsp;dynamically change billing address&nbsp;in Magento 2. The billing address defines a physical location\/address where the&#8230;<\/p>\n","protected":false},"author":13,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[34],"tags":[],"class_list":["post-2494","post","type-post","status-publish","format-standard","hentry","category-magento"],"acf":[],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/2494","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/13"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=2494"}],"version-history":[{"count":4,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/2494\/revisions"}],"predecessor-version":[{"id":17987,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/2494\/revisions\/17987"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=2494"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=2494"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=2494"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}