Saving Customer Default Addresses Programmatically in Magento 2
When working with customer addresses in Magento 2, you may need to save new default addresses or update existing ones programmatically within your custom module. This can be achieved by extending the edit action of the Magento\Customer\Controller\Address\IndexController. Here’s a step-by-step guide on how to do this correctly:
Extending the Address Edit Controller
First, you need to create an override for the address edit controller in your custom module. Create a new file named EditPost.php inside the app/code/Vendor/Module/etc/adminhtml/di.xml folder.
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Customer\Controller\Address\Index">
<arguments>
<argument name="customerSession" xsi:type="object">Vendor\Module\Model\Session\Customer</argument>
</arguments>
</type>
</config>
Next, create the app/code/Vendor/Module/Model/Session/Customer.php file:
namespace Vendor\Module\Model\Session;
class Customer extends \Magento\Customer\Model\Session
{
public function editPostAction()
{
// Your custom logic here
return $this->resultPageFactory->create('customer_address_index');
}
}
Saving the New or Updated Default Address
In your EditPost method, you need to process the form data and save the address. Here’s how to do it:
- Get the customer ID from the session.
- Retrieve the current default billing and shipping addresses for this customer.
- If a new address is being added, create a new instance of
\Magento\Customer\Model\Address. - Set the required fields (e.g.,
firstname,lastname,street,city, etc.). - Save the address with
save()or update it if it already exists.
Here’s some sample code to illustrate this:
namespace Vendor\Module\Controller\Customer;
class Address extends \Magento\Customer\Controller\Address\Index
{
public function editPostAction()
{
$customerId = $this->getCustomerSession()->getCustomerId();
if (!$customerId) {
return $this->_redirect('*/*/index');
}
/** @var \Magento\Framework\Controller\ResultInterface $resultPage */
$resultRedirect = $this->resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT);
try {
$post = $this->getRequest()->getPostValue();
if (isset($post['default_billing']) && isset($post['billing_address_id'])) {
$addressId = $post['billing_address_id'];
$customerAddress = $this->_addressFactory->create();
$address = $customerAddress->load($addressId);
$address->addData($post);
$address->save();
}
if (isset($post['default_shipping']) && isset($post['shipping_address_id'])) {
// Similar logic for shipping address
}
// Save the default addresses for this customer
// You can use the Magento API to update customer addresses here
} catch (\Exception $e) {
$resultRedirect->setPath('*/*/index', ['_current' => true]);
$this->messageManager->addError($e->getMessage());
}
return $resultRedirect;
}
}
Conclusion
Saving default addresses programmatically in Magento 2 requires a combination of extending the editPost action and processing form data correctly. It’s essential to ensure that you’re following best practices for code organization and maintainability.
Remember, when working with customer data, always consider the security implications and make sure you are using the appropriate Magento APIs and models.
For more advanced customizations in Magento 2, I recommend checking out the official Magento documentation (https://laravelcompany.com/magento-2-development/), which provides detailed guides on module development and extension creation.