Address Book
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
The Address Book concept is a very convenient solution for the customers of your shop, that come back. Once they provide an address it is saved in the system and can be reused the next time.
Sylius handles the address book in a not complex way:
On the Customer entity we are holding a collection of addresses:
class Customer {
/**
* @var Collection|AddressInterface[]
*/
protected $addresses;
}
We can operate on it as usual - by adding and removing objects.
Besides the Customer entity has a default address field that is the default address used both for shipping and billing, the one that will be filling the form fields by default.
If you would like to add an address to the collection of Addresses of a chosen customer thatโs all that you should do:
Create a new address:
/** @var AddressInterface $address */
$address = $this->container->get('sylius.factory.address')->createNew();
$address->setFirstName('Ronald');
$address->setLastName('Weasley');
$address->setCompany('Ministry of Magic');
$address->setCountryCode('UK');
$address->setProvinceCode('UKJ');
$address->setCity('Otter St Catchpole');
$address->setStreet('The Burrow');
$address->setPostcode('000001');
Then find a customer to which you would like to assign it, and add the address.
$customer = $this->container->get('sylius.repository.customer')->findOneBy(['email' => '[email protected]']);
$customer->addAddress($address);
Remember to flush the customerโs manager to save this change.
$this->container->get('sylius.manager.customer')->flush();