cancel
Showing results for 
Search instead for 
Did you mean: 

Adding an address to an account in PHP.

SOLVED

Adding an address to an account in PHP.

I am working on a module that adds an account in the checkout in Magento 2.3

I am able to create an account now but i'm struggling with adding an address to that account. I already tried multiple different ways by using the customer address factory.

 

/Model/Checkout/ShippingInformationManagementPlugin.php

 

<?php
namespace BB\Checkout\Model\Checkout;

class ShippingInformationManagementPlugin
{
    protected $quoteRepository;

    /**
     * @var \Magento\Newsletter\Model\SubscriberFactory
     */
    protected $subscriberFactory;

    /**
     * @var \Magento\Customer\Api\AccountManagementInterface
     */
    protected $accountManagement;

    /**
     * @var \Magento\Customer\Helper\Address
     */
    protected $addressHelper;

    /**
     * @var \Magento\Customer\Model\Metadata\FormFactory
     */
    protected $formFactory;

    /**
     * @var \Magento\Customer\Api\Data\RegionInterfaceFactory
     */
    protected $regionDataFactory;

    /**
     * @var \Magento\Customer\Api\Data\AddressInterfaceFactory
     */
    protected $addressDataFactory;

    /**
     * @var \Magento\Customer\Model\Registration
     */
    protected $registration;

    /**
     * @var \Magento\Customer\Api\Data\CustomerInterfaceFactory
     */
    protected $customerDataFactory;

    /**
     * @var \Magento\Customer\Model\Url
     */
    protected $customerUrl;

    /**
     * @var \Magento\Framework\Escaper
     */
    protected $escaper;

    /**
     * @var \Magento\Customer\Model\CustomerExtractor
     */
    protected $customerExtractor;

    /**
     * @var \Magento\Framework\UrlInterface
     */
    protected $urlModel;

    /**
     * @var \Magento\Framework\Api\DataObjectHelper
     */
    protected $dataObjectHelper;

    /**
     * @var Session
     */
    protected $session;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @var \Magento\Customer\Model\CustomerFactory
     */
    protected $customerFactory;

    /**
     * @var \Magento\Customer\Model\AddressFactory
     */
    protected $addressFactory;

    public function __construct(
        \Magento\Quote\Model\QuoteRepository $quoteRepository,
        \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
        \Magento\Framework\Api\ExtensionAttributesFactory $extensionAttributesFactory,
        \Magento\Framework\Event\Observer $observer,
        \Magento\Customer\Model\Session $customerSession,

        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory,

        \Magento\Customer\Model\AddressFactory $addressFactory
    )
    {
        $this->quoteRepository = $quoteRepository;
        $this->subscriberFactory = $subscriberFactory;
        $this->extensionAttributesFactory = $extensionAttributesFactory;
        $this->observer = $observer;

        $this->storeManager = $storeManager;
        $this->customerFactory = $customerFactory;
        $this->addressFactory = $addressFactory;
    }

    /**
     * @param \Magento\Checkout\Model\ShippingInformationManagement $subject
     * @param $cartId
     * @param \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
     */
    public function beforeSaveAddressInformation(
        \Magento\Checkout\Model\ShippingInformationManagement $subject,
        $cartId,
        \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
    )
    {
        $extAttributes = $addressInformation->getExtensionAttributes();
        $email = $extAttributes->getEmail();

        // Create account for user
         if ($extAttributes->getPassword() !== '') {

            // Get Website ID
            $websiteId = $this->storeManager->getWebsite()->getWebsiteId();

            // Instantiate object (this is the most important part)
            $customer = $this->customerFactory->create();
            $customer->setWebsiteId($websiteId);
            $address = $addressInformation->getShippingAddress();

            // Preparing data for new customer
            $customer->setEmail($extAttributes->getEmail());
            $customer->setPassword($extAttributes->getPassword());
            $customer->setFirstname($address->getFirstname());
            $customer->setLastname($address->getLastname());

//            //Address data (not working)
//            $customer->setStreet($address->getStreet());
//            $customer->setPostcode($address->getPostcode());
//            $customer->setCity($address->getCity());
//            $customer->setCountry($address->getCountry());
//            $customer->setTelephone($address->getTelephone());

            // Save data
            try {
                $customer->save();

                echo 'Create customer successfully, customer ID: ' . $customer->getId();
                $addAddress = $this->addressFactory->create();

                $addAddress->setCustomerId($customer->getId());
                $addAddress->setCountryId('NL');
                $addAddress->setPostcode('6942AE');
                $addAddress->setCity('Arnhem');
                $addAddress->setTelephone('0123456789');
                $addAddress->setStreet('Street 1');
                $addAddress->setIsDefaultBilling('1');
                $addAddress->setIsDefaultShipping('1');
                $addAddress->setSaveInAddressBook('1');

                $addAddress->save();

            } catch (\Exception $e) {
                // E-mail address is already added, this will occur if the customer goes back and forward in steps, the account is already created by then.
            }
        }
    }
}

Any idea? It saves the account but doesn't add the address.

3 REPLIES

Re: Adding an address to an account in PHP.

Might be you missing the firstname and lastname of customer address,

 

$address->setCustomerId($customerId)
                    ->setFirstname($firstname)
                    ->setLastname($lastname)

Add above field and check.

If Issue Solved, Click Kudos/Accept As solutions.

Re: Adding an address to an account in PHP.

That sadly doesn't fix it.

Re: Adding an address to an account in PHP.

I'm not exactly sure what I was missing but I changed around some variable names and somehow it works now.

 

ShippingInformationManagementPlugin.php

<?php

namespace BB\Checkout\Model\Checkout;

class ShippingInformationManagementPlugin
{
    protected $quoteRepository;

    /**
     * @var \Magento\Newsletter\Model\SubscriberFactory
     */
    protected $subscriberFactory;

    /**
     * @var \Magento\Customer\Api\AccountManagementInterface
     */
    protected $accountManagement;

    /**
     * @var \Magento\Customer\Helper\Address
     */
    protected $addressHelper;

    /**
     * @var \Magento\Customer\Model\Metadata\FormFactory
     */
    protected $formFactory;

    /**
     * @var \Magento\Customer\Api\Data\RegionInterfaceFactory
     */
    protected $regionDataFactory;

    /**
     * @var \Magento\Customer\Api\Data\AddressInterfaceFactory
     */
    protected $addressDataFactory;

    /**
     * @var \Magento\Customer\Model\Registration
     */
    protected $registration;

    /**
     * @var \Magento\Customer\Api\Data\CustomerInterfaceFactory
     */
    protected $customerDataFactory;

    /**
     * @var \Magento\Customer\Model\Url
     */
    protected $customerUrl;

    /**
     * @var \Magento\Framework\Escaper
     */
    protected $escaper;

    /**
     * @var \Magento\Customer\Model\CustomerExtractor
     */
    protected $customerExtractor;

    /**
     * @var \Magento\Framework\UrlInterface
     */
    protected $urlModel;

    /**
     * @var \Magento\Framework\Api\DataObjectHelper
     */
    protected $dataObjectHelper;

    /**
     * @var Session
     */
    protected $session;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @var \Magento\Customer\Model\CustomerFactory
     */
    protected $customerFactory;

    /**
     * @var \Magento\Customer\Model\AddressFactory
     */
    protected $addressFactory;

    public function __construct(
        \Magento\Quote\Model\QuoteRepository $quoteRepository,
        \Magento\Newsletter\Model\SubscriberFactory $subscriberFactory,
        \Magento\Framework\Api\ExtensionAttributesFactory $extensionAttributesFactory,
        \Magento\Framework\Event\Observer $observer,
        \Magento\Customer\Model\Session $customerSession,

        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory,

        \Magento\Customer\Model\AddressFactory $addressFactory
    )
    {
        $this->quoteRepository = $quoteRepository;
        $this->subscriberFactory = $subscriberFactory;
        $this->extensionAttributesFactory = $extensionAttributesFactory;
        $this->observer = $observer;

        $this->storeManager = $storeManager;
        $this->customerFactory = $customerFactory;
        $this->addressFactory = $addressFactory;
    }

    /**
     * @param \Magento\Checkout\Model\ShippingInformationManagement $subject
     * @param $cartId
     * @param \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
     */
    public function beforeSaveAddressInformation(
        \Magento\Checkout\Model\ShippingInformationManagement $subject,
        $cartId,
        \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
    )
    {
        $extAttributes = $addressInformation->getExtensionAttributes();
        $email = $extAttributes->getEmail();
        $subscribe = $extAttributes->getSubscribe();

        // Subscribe user to newsletter
        if ($subscribe === true) {
            $subscriber = $this->subscriberFactory->create()->loadByEmail($email);
            if ($subscriber->getId() && $subscriber->getSubscriberStatus() == \Magento\Newsletter\Model\Subscriber::STATUS_SUBSCRIBED) {
            } else {
                $status = $this->subscriberFactory->create()->subscribe($email);
            }
        }

        // Create account for user
         if ($extAttributes->getPassword() !== '') {

            // Create account
            $websiteId = $this->storeManager->getWebsite()->getWebsiteId();
            $customer = $this->customerFactory->create();
            $customer->setWebsiteId($websiteId);
            $address = $addressInformation->getShippingAddress();

            // Preparing data for new customer
            $customer->setEmail($extAttributes->getEmail());
            $customer->setPassword($extAttributes->getPassword());
            $customer->setFirstname($address->getFirstname());
            $customer->setLastname($address->getLastname());

            try {
                $customer->save();

                // Create address
                $customerAddress = $this->addressFactory->create();

                $customerAddress->setCustomerId($customer->getId());
                $customerAddress->setFirstname($address->getFirstname());
                $customerAddress->setLastname($address->getFirstname());
                $customerAddress->setCountryId($address->getCountryId());
                $customerAddress->setPostcode($address->getPostcode());
                $customerAddress->setCity($address->getCity());
                $customerAddress->setTelephone($address->getTelephone());
                $customerAddress->setStreet($address->getStreet());
                $customerAddress->setCompany($address->getCompany());
                $customerAddress->setVatId($address->getVatId());
                $customerAddress->setIsDefaultBilling('1');
                $customerAddress->setIsDefaultShipping('1');
                $customerAddress->setSaveInAddressBook('1');

                $customerAddress->save();
            } catch (\Exception $e) {
                // E-mail address is already added, this will occur if the customer goes back and forward in steps, the account is already created by then.
            }
        }
    }
}