2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.