3

I want to save custom customer address attribute in Customer Edit Form under My Account section. I have created an attribute using Setup script and save that attribute using extension attributes.

Vendor/Module/etc/extension_attributes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
 <extension_attributes for="Magento\Customer\Api\Data\AddressInterface">
 <attribute code="city_id" type="string"/>
 </extension_attributes>
</config>

Here I couldn't extend Magento\Customer\Api\Data\AddressInterface, that's why I'm using extension_attributes. Then I created a plugin to get and set that attribute value as follows:

Vendor/Module/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
 <type name="Magento\Customer\Api\AddressRepositoryInterface">
 <plugin name="customer_city_id" type="Vendor\Module\Plugin\CustomerCity"/>
 </type>
</config>

Vendor/Module/Plugin/CustomerCity.php

<?php
namespace Vendor\Module\Plugin;
use Magento\Customer\Api\Data\AddressInterface;
class CustomerCity {
 public function afterGetById(
 \Magento\Customer\Api\AddressRepositoryInterface $subject,
 $address,
 $addressId
 ) {
 try {
 if ($address->getExtensionAttributes() === null) {
 $address->setExtensionAttributes($this->extensionAttributeFactory->create(AddressInterface::class));
 }
 $extensionAttribute = $address->getExtensionAttributes();
 $extensionAttribute->setCityId(
 ($address->getCustomAttribute('city_id')) ?
 $address->getCustomAttribute('city_id')->getValue() : ""
 );
 $address->setExtensionAttributes($extensionAttribute);
 }
 catch (\Exception $e) {
 // Don't handle exceptions
 }
 return $address;
 }
}

Unfortunately, I'm getting an error We can't save the address. As I printed an exception message, I'm getting this message: Class string does not exist.

Please anyone let me know what I'm doing wrong. Thanks in anticipation.

asked Apr 11, 2019 at 10:22
2

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.