Magento 2:以编程方式创建客户属性[也更新和删除客户属性]

本文介绍了如何在Magento 2中以编程方式添加或创建新的客户属性。它还显示了如何在Magento 2中以编程方式更新和删除/删除客户属性。

我还将展示如何从安装脚本和升级脚本中添加产品属性:

–从安装脚本(InstallData.php)
添加客户属性–从升级脚本(UpgradeData.php)添加客户属性

本文的模块名称是:Chapagain_CustomerAttribute

使用安装脚本添加/创建客户属性

在这里,我们创建了两个客户属性:

-我的客户类型(属性代码:my_customer_type
-我的客户档案/图片(属性代码:my_customer_image

文件:app / code / Chapagain / CustomerAttribute / Setup / InstallData.php

<?php
 
namespace Chapagain\CustomerAttribute\Setup;
 
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
 
class InstallData implements InstallDataInterface
{
    /**
     * EAV setup factory
     *
     * @var \Magento\Eav\Setup\EavSetupFactory
     */
    private $eavSetupFactory;
 
    /**
     * Customer setup factory
     *
     * @var CustomerSetupFactory
     */
    private $customerSetupFactory;
 
    /**
     * Constructor
     *
     * @param EavSetupFactory $eavSetupFactory
     * @param CustomerSetupFactory $customerSetupFactory
     */
    public function __construct(
        EavSetupFactory $eavSetupFactory,
        CustomerSetupFactory $customerSetupFactory
    ) 
    {
        $this->eavSetupFactory = $eavSetupFactory;
        $this->customerSetupFactory = $customerSetupFactory;
    }
 
    /**
     * {@inheritdoc}
     */
    public function install(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $setup->startSetup();
 
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
 
        /**
         * Create a select box attribute
         */
        $attributeCode = 'my_customer_type';
 
        $customerSetup->addAttribute(
            \Magento\Customer\Model\Customer::ENTITY, 
            $attributeCode, 
            [
                'type' => 'int',
                'label' => 'My Customer Type',
                'input' => 'select',
                'source' => 'Chapagain\CustomerAttribute\Model\Config\Source\MyCustomerType',
                'required' => false,
                'visible' => true,
                'position' => 300,
                'system' => false,
                'backend' => ''
            ]
        );
        
        // show the attribute in the following forms
        $attribute = $customerSetup
                        ->getEavConfig()
                        ->getAttribute(
                            \Magento\Customer\Model\Customer::ENTITY,
                            $attributeCode
                        )
                        ->addData(
                            ['used_in_forms' => [
                                'adminhtml_customer',
                                'adminhtml_checkout',
                                'customer_account_create',
                                'customer_account_edit'
                            ]
                        ]);
 
        $attribute->save();
 
        /**
         * Create a file type attribute
         * For File or Image Upload
         */
        $attributeCode = 'my_customer_image';
 
        $customerSetup->addAttribute(
            \Magento\Customer\Model\Customer::ENTITY, 
            $attributeCode, 
            [
                'type' => 'text',
                'label' => 'My Customer File/Image',
                'input' => 'file',
                'source' => '',
                'required' => false,
                'visible' => true,
                'position' => 200,
                'system' => false,
                'backend' => ''
            ]
        );
        
        // show the attribute in the following forms
        $attribute = $customerSetup
                        ->getEavConfig()
                        ->getAttribute(
                            \Magento\Customer\Model\Customer::ENTITY, 
                            $attributeCode
                        )
                        ->addData(
                            ['used_in_forms' => [
                                'adminhtml_customer',
                                'adminhtml_checkout',
                                'customer_account_create',
                                'customer_account_edit'
                            ]
                        ]);
 
        $attribute->save();
 
        $setup->endSetup();
    }
}

在这里,我们创建了两个客户属性:

–我的客户类型(my_customer_type)
–我的客户文件/图像(my_customer_image)

我的客户类型是一个选择框属性。因此,为此,我们定义了一个自定义源文件:Chapagain \ CustomerAttribute \ Model \ Config \ Source \ MyCustomerType

因此,我们还需要创建源文件。

文件:app / code / Chapagain / CustomerAttribute / Model / Config / Source / MyCustomerType.php

<?php
 
namespace Chapagain\CustomerAttribute\Model\Config\Source;
 
class MyCustomerType extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
    /**
     * Get all options
     *
     * @return array
     */
    public function getAllOptions()
    {
        if ($this->_options === null) {
            $this->_options = [
                ['value' => '', 'label' => __('Please Select')],
                ['value' => '1', 'label' => __('My Option 1')],
                ['value' => '2', 'label' => __('My Option 2')],
                ['value' => '3', 'label' => __('My Option 3')],
                ['value' => '4', 'label' => __('My Option 4')]
            ];
        }
        return $this->_options;
    }
 
    /**
     * Get text of the option value
     * 
     * @param string|integer $value
     * @return string|bool
     */
    public function getOptionValue($value) 
    { 
        foreach ($this->getAllOptions() as $option) {
            if ($option['value'] == $value) {
                return $option['label'];
            }
        }
        return false;
    }
}

使用升级脚本添加/创建/更新/删除客户属性

这里:

–首先,我们创建一个名为:的新属性My Customer Date,其属性代码为:my_customer_date
–然后,将属性设置为不同的形式
–然后,有代码来更新frontend_model属性的
–我们还更新frontend_label了属性
–最后,我们查看通过其属性代码删除任何属性的代码
version_compare()函数用于在每次版本升级时运行该代码

文件:app / code / Chapagain / ProductAttribute / Setup / UpgradeData.php

<?php
 
namespace Chapagain\CustomerAttribute\Setup;
 
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
 
/**
 * @codeCoverageIgnore
 */
class UpgradeData implements UpgradeDataInterface
{
    /**
     * Customer setup factory
     *
     * @var CustomerSetupFactory
     */
    private $customerSetupFactory;
 
    /**
     * EAV setup factory
     *
     * @var \Magento\Eav\Setup\EavSetupFactory
     */
    private $eavSetupFactory;
 
    /**
     * Constructor
     *
     * @param EavSetupFactory $eavSetupFactory
     * @param CustomerSetupFactory $customerSetupFactory
     */
    public function __construct(
        EavSetupFactory $eavSetupFactory,
        CustomerSetupFactory $customerSetupFactory
    ) {
        $this->eavSetupFactory = $eavSetupFactory;
        $this->customerSetupFactory = $customerSetupFactory;
    }
 
    /**
     * {@inheritdoc}
     */
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
 
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
        
        /**
         * run this code if the module version stored in database is less than 1.0.1
         * i.e. the code is run while upgrading the module from version 1.0.0 to 1.0.1
         * 
         * you can write the version_compare function in the following way as well:
         * if(version_compare($context->getVersion(), '1.0.1', '<')) { 
         * 
         * the syntax is only different
         * output is the same
         */ 
        if (version_compare($context->getVersion(), '1.0.1') < 0) { 
 
            $attributeCode = 'my_customer_date';
 
            $customerSetup->addAttribute(
                \Magento\Customer\Model\Customer::ENTITY, 
                $attributeCode, 
                [
                    'type' => 'static', // backend type
                    'label' => 'My Customer Date',
                    'input' => 'date', // frontend input
                    'source' => '', // source model
                    'backend' => \Magento\Eav\Model\Entity\Attribute\Backend\Datetime::class,
                    'required' => false,
                    'visible' => true,
                    'sort_order' => 200,
                    'position' => 300,
                    'system' => false
                ]
            );
 
            // show the attribute in the following forms
            $attribute = $customerSetup
                            ->getEavConfig()
                            ->getAttribute(
                                \Magento\Customer\Model\Customer::ENTITY, 
                                $attributeCode
                            )
                            ->addData(
                                ['used_in_forms' => [
                                    'adminhtml_customer',
                                    'adminhtml_checkout',
                                    'customer_account_create',
                                    'customer_account_edit'
                                ]
                            ]);
 
            $attribute->save();
        }
 
        if(version_compare($context->getVersion(), '1.0.2', '<')) { 
            
            $attributeCode = 'my_customer_date';
            
            // add/update frontend_model to the attribute
            $customerSetup->updateAttribute(
                \Magento\Customer\Model\Customer::ENTITY, // customer entity code
                $attributeCode,
                'frontend_model',
                \Magento\Eav\Model\Entity\Attribute\Frontend\Datetime::class
            );
 
            // update the label of the attribute
            $customerSetup->updateAttribute(
                \Magento\Customer\Model\Customer::ENTITY, // customer entity code
                $attributeCode,
                'frontend_label',
                'My Custom Date Modified'
            );
        }
 
        if(version_compare($context->getVersion(), '1.0.3', '<')) { 
 
            $attributeCode = 'your_customer_attribute_code';
 
            // remove customer attribute
            $customerSetup->removeAttribute(
                \Magento\Customer\Model\Customer::ENTITY,
                $attributeCode // attribute code to remove
            );
        }
 
        $setup->endSetup();
    }
}

更新升级设置代码后,还需要确保已升级模块etc/module.xml文件中的模块版本号。

之后,您需要:

–打开终端
–转到Magento的根目录
–并运行以下命令:

php bin/magento setup:upgrade

希望这可以帮助。谢谢。

赞(0)
微信
支付宝
微信二维码图片

微信扫描二维码打赏

支付宝二维码图片

支付宝扫描二维码打赏

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论