I'm new to Magento 2 and trying to add a customer attribute using a Data Patch.
I created the following patch class:
What I Tried:
Using addData(['used_in_forms' => ['adminhtml_customer']]).
Clearing cache and generated code.
Ensuring the attribute is not already in the database.
Converting the attribute to a Customer\Model\Attribute object.
<?php
namespace Vendor\Module\Setup\Patch\Data;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class CreateQuickbooksInvoiceAttribute implements DataPatchInterface
{
/**
* @var ModuleDataSetupInterface
*/
private $moduleDataSetup;
/**
* @var CustomerSetupFactory
*/
private $customerSetupFactory;
/**
* @var AttributeSetFactory
*/
private $attributeSetFactory;
/**
* Constructor
*/
public function __construct(
ModuleDataSetupInterface $moduleDataSetup,
CustomerSetupFactory $customerSetupFactory,
AttributeSetFactory $attributeSetFactory
) {
$this->moduleDataSetup = $moduleDataSetup;
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
}
/**
* Apply patch
*/
public function apply()
{
/** @var \Magento\Customer\Setup\CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $this->moduleDataSetup]);
$customerEntity = $customerSetup->getEavConfig()->getEntityType(Customer::ENTITY);
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
if (!$customerSetup->getAttributeId(Customer::ENTITY, 'quickbooks_invoice')) {
// Add attribute
$customerSetup->addAttribute(Customer::ENTITY, 'quickbooks_invoice', [
'type' => 'int',
'label' => 'QuickBooks Invoice',
'input' => 'select',
'source' => \Magento\Eav\Model\Entity\Attribute\Source\Boolean::class,
'required' => false,
'visible' => true,
'user_defined' => true,
'system' => 0,
'position' => 100,
'sort_order' => 100,
'default' => 0,
]);
}
// Load as customer attribute to safely assign used_in_forms
/** @var \Magento\Customer\Model\Attribute $attribute */
$attribute = \Magento\Framework\App\ObjectManager::getInstance()
->create(\Magento\Customer\Model\Attribute::class)
->loadByCode(Customer::ENTITY, 'quickbooks_invoice');
$attribute->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer'],
]);
$attribute->save();
}
public static function getDependencies()
{
return [];
}
public function getAliases()
{
return [];
}
}