0

I want to create a custom customer address attribute called customer_custom_id in the below address.( check the below image.). how can I do that?

enter image description here

1 Answer 1

1

You can achieve this by create a data patch using a custom module.

<?php
namespace Ayakil\CustomAttributes\Setup\Patch\Data;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Customer\Model\ResourceModel\Attribute;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class CreatedCustomAdressAttribute implements DataPatchInterface
{


private $moduleDataSetup;
private $attributeSetFactory;
private $customerSetupFactory;
private $attribute;


public function __construct(
    ModuleDataSetupInterface $moduleDataSetup,
    AttributeSetFactory $attributeSetFactory,
    CustomerSetupFactory $customerSetupFactory,
    Attribute $attribute
) {
    $this->moduleDataSetup = $moduleDataSetup;
    $this->attributeSetFactory = $attributeSetFactory;
    $this->customerSetupFactory = $customerSetupFactory;
    $this->attribute = $attribute;
}

public function apply()
{
    $customerSetup = $this->customerSetupFactory->create(['setup' => $this->moduleDataSetup]);
    $customerAddressEntity = $customerSetup->getEavConfig()->getEntityType('customer_address');
    $attributeSetId = $customerAddressEntity->getDefaultAttributeSetId();

    $attributeSet = $this->attributeSetFactory->create();
    $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

    $customerSetup->addAttribute('customer_address', 'customer_custom_id', [
        'type'          => 'varchar',
        'label'         => 'Customer Custom Field',
        'input'         => 'text',
        'required'      =>  false,
        'visible'       =>  true,
        'user_defined'  =>  true,
        'sort_order'    =>  13,
        'position'      =>  13,
        'system'        =>  0,
    ]);


    $attribute = $customerSetup->getEavConfig()->getAttribute('customer_address', 'customer_custom_id');

    $attribute->setData('used_in_forms', [
        'adminhtml_customer',
        'adminhtml_checkout',
        'adminhtml_customer_address',
        'customer_account_edit',
        'customer_address_edit',
    ]);
    
    $this->attribute->save($attribute);


    return $this;
}

public static function getDependencies()
{
    return [];
}

public function getAliases()
{
    return [];
}
}

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.