$setup->getConnection()->addColumn( $setup->getTable('customer_entity'), 'field1', [ 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT, 'nullable' => false, 'unsigned' => true, 'default' => 0, 'comment' => 'new field comment' ] );
public function __construct(Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory) { $this->customerSetupFactory = $customerSetupFactory; } public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { $setup->startSetup(); $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]); $attributesInfo = [ 'field1' => [ 'type' => 'static', 'label' => 'Label1', 'input' => 'select', // 如要實現動態option就要重寫source 'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Table', 'sort_order' => 10, 'position' => 10, 'is_used_in_grid' => true, 'is_visible_in_grid' => false, 'is_filterable_in_grid' => false, 'is_searchable_in_grid' => false ], ]; foreach ($attributesInfo as $attributeCode => $attributeParams) { $customerSetup->addAttribute('customer', $attributeCode, $attributeParams); } $attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'field1'); $attribute->setData( 'used_in_forms', ['adminhtml_customer', 'customer_account_create'] ); $attribute->save(); $setup->endSetup(); }
其它屬性類型可參考代碼:vendor/magento/module-customer/Setup/CustomerSetup.php
使用了is_used_in_grid參數後,filter新增屬性時會出現customer_grid_flat沒有此字段的提示。flat表用於存儲index數據,每次reindex會對flat表刪除再重建,因此flat表添加字段沒有用,必須經過index機制讓系統認出這個字段php
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Indexer/etc/indexer.xsd"> <indexer id="customer_grid" view_id="customer_dummy" class="Magento\Framework\Indexer\Action\Entity" primary="customer"> <fieldset name="customer" source="Magento\Customer\Model\ResourceModel\Customer\Collection" provider="Magento\Customer\Model\Indexer\AttributeProvider"> <field name="field1" xsi:type="filterable" dataType="int"/> </fieldset> </indexer> </config>
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $city = $objectManager->create( 'Magento\Catalog\Model\ResourceModel\Eav\Attribute' ) ->loadByCode( 'customer_address', 'city'); $output->writeln(print_r($city->getData(), true)); $city->setData('is_required', true); $city->save();
注:email,first name, last name與多數的地址信息字段與內核多處有關聯,因此不是EAV設定了非必填就能全面實現html