How to add dropdown attribute to custom module in magento 2.0
-
05-10-2020 - |
题
I wanted to add dropdown attribute called 'customer type' with drop down options 'buyer' and 'seller' to my custom module. How can I make it to my upgrade schema?
解决方案
Add bellow installation script in your module at path app/code/{Namespace} /{Module-Name}/Setup/InstallData.php
<?php
/**
* @author AR
* @category AR
* @package AR_CustomerAttribute
*/
namespace {Namespace}\{Module-name}\Setup;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{
/**
* @var CustomerSetupFactory
*/
protected $customerSetupFactory;
/**
* @var AttributeSetFactory
*/
private $attributeSetFactory;
/**
* @param CustomerSetupFactory $customerSetupFactory
* @param AttributeSetFactory $attributeSetFactory
*/
public function __construct(
CustomerSetupFactory $customerSetupFactory,
AttributeSetFactory $attributeSetFactory
) {
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
}
/**
* {@inheritdoc}
*/
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
/** @var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
/** @var $attributeSet AttributeSet */
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
$customerSetup->addAttribute(Customer::ENTITY, 'customer_type', [
'type' => 'static',
'label' => 'Customer Type',
'input' => 'select',
'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Table',
'required' => false,
'sort_order' => 210,
'visible' => false,
'system' => false,
'validate_rules'=> 'a:0:{}',
'position' => 210,
'admin_checkout' => 1,
'option' => ['values' => ['Buyer', 'Seller']],
]);
$attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'customer_type')
->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer'],
]);
$attribute->save();
}
}
其他提示
For creating custom attribute through schema, please follow this link. At place of source, you can give options in array OR you can define your own source in custom module.