2

setup/InstallSchema.php

$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'
    ]
);

setup/InstallData.php

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

etc/indexer.xml

使用了is_used_in_grid参数后,filter新增属性时会出现customer_grid_flat没有此字段的提示。flat表用于存储index数据,每次reindex会对flat表删除再重建,所以flat表添加字段没有用,必须通过index机制让系统认出这个字段

<?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>

修改attribute为非必填

$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设定了非必填就能全面实现


猫之良品
2.5k 声望139 粉丝

资深Drupal, magento与Joomla


引用和评论

0 条评论