Magento how to programmatically create customer address


Step 1: Define Function


Magento 1


<?php class MageCheck_Tutorial_IndexController extends Mage_Core_Controller_Front_Action { public function indexAction() { $this-> createCustomerAddress(); } public function createCustomerAddress() { // ... } }

Magento 2


/** * @var \Magento\Customer\Model\Address $address */ protected $_address; /** * @var \Magento\Customer\Model\Customer $customer */ protected $_customer; public function __construct( { \Magento\Customer\Model\Address $address, \Magento\Customer\Model\Customer $customer ){ $this->_address = $address; $this->_customer = $customer; } public function execute() { $this->creatingCustomerAddress(); } public function creatingCustomerAddress() { // ... }

Step 2: Create Function


Magento 1


public function createCustomerAddress() { $websiteId = Mage::app()->getWebsite()->getId(); $store = Mage::app()->getStore(); $customer = Mage::getModel('customer/customer'); $customer->setWebsiteId($websiteId) ->setStore($store) ->setFirstname('Mage') ->setLastname('Check') ->setEmail('example@magecheck.com') ->setPassword('password1234567890'); $customer->save(); $address = Mage::getModel('customer/address'); $address->setCustomerId($customer->getId()) ->setFirstname($customer->getFirstname()) ->setMiddleName($customer->getMiddlename()) ->setLastname($customer->getLastname()) ->setPostcode('12345AA') ->setCity('New York') ->setTelephone('01234567890') ->setFax('01234567890') ->setCompany('Test') ->setStreet('streetname') ->setIsDefaultBilling('1') ->setIsDefaultShipping('1') ->setSaveInAddressBook('1'); $address->save(); }

Magento 2


public function creatingCustomerAddress() { $customer = $this->_customer; $address = $this->_address; $address->setCustomerId($customer->getId()) ->setFirstname('Mage') ->setLastname('Check') ->setCountryId('US') ->setPostcode('10000') ->setCity('New York') ->setTelephone('12634567890') ->setFax('1236456789') ->setCompany('MageCheck') ->setStreet('1st Street') ->setIsDefaultBilling('1') ->setIsDefaultShipping('1') ->setSaveInAddressBook('1'); $address->save(); }