In this blog, I created customer address attribute programmatic in magento 2. Code is supported to php8 and magento 2.4.6 😍
Let’s see how to create customer address attribute programmatically.
We are creating customer address attribute name unique_id.
First, Create data patch class like AddUniqueIdAddressAttribute.php
file at path app/code/Vendor/Module/Setup/Patch/Data/AddUniqueIdAddressAttribute.php
<?php
declare(strict_types=1);
namespace MageDad\Module\Setup\Patch\Data;
use Magento\Customer\Api\AddressMetadataInterface;
use Magento\Customer\Model\ResourceModel\Attribute as AttributeResource;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
class AddUniqueIdAddressAttribute implements DataPatchInterface
{
public function __construct(
private ModuleDataSetupInterface $moduleDataSetup,
private CustomerSetupFactory $customerSetupFactory,
private AttributeResource $attributeResource,
) { }
/**
* @inheritdoc
*/
public function apply()
{
$customerSetup = $this->customerSetupFactory->create(['setup' => $this->moduleDataSetup]);
$customerSetup->addAttribute(
AddressMetadataInterface::ENTITY_TYPE_ADDRESS,
'unique_id',
[
'input' => 'text',
'label' => 'Unique Id',
'position' => 205,
'required' => false,
'system' => false,
'type' => 'text',
'user_defined' => true,
'visible' => false,
],
);
$attribute = $customerSetup->getEavConfig()->getAttribute(AddressMetadataInterface::ENTITY_TYPE_ADDRESS, 'unique_id');
$customerSetup->addAttributeToSet(
AddressMetadataInterface::ENTITY_TYPE_ADDRESS,
AddressMetadataInterface::ATTRIBUTE_SET_ID_ADDRESS,
$customerSetup->getDefaultAttributeGroupId(AddressMetadataInterface::ENTITY_TYPE_ADDRESS),
'unique_id',
);
$attribute->setData('used_in_forms', [
'adminhtml_customer_address',
]);
$this->attributeResource->save($attribute);
return $this;
}
/**
* @inheritdoc
*/
public function getAliases(): array
{
return [];
}
/**
* @inheritdoc
*/
public static function getDependencies(): array
{
return [];
}
}
After create patch run magento setup upgrade command for execute code.php bin/magento setup:upgrade
We can see newly created customer address attribute in customer edit/add.
I hope this blog is useful for create customer address attribute programatically in magento2. In case, I missed anything or need to add some more information, Don’t heisted to leave a comment in this blog, I’ll get back with some positive approach.
Keep loving ❤️ Keep inspiring 🤩 Keep liking 👍 No sharing 😄
1 Comment
Thank you for your contribution.