Magento 2以编程方式创建客户

在Magento 2中创建新客户,您可以在Magento 2商店后端的注册表单中填写完整的信息。但是,如果要创建来自多个地址(城市,州/省,国家/地区)的大量新客户并同时将它们发送到不同的客户组,这将非常耗时。因此,教程主题Magento 2编程方式创建客户的方式提供给了开发人员。他们将直接使用代码。

以编程方式创建客户的概述

运行代码片段

您只需要做以下代码段,当您要以编程方式创建客户时,请将其插入控制台。

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customerSetupFactory = $objectManager->create('Magento\Customer\Setup\CustomerSetupFactory');

        $setupInterface = $objectManager->create('Magento\Framework\Setup\ModuleDataSetupInterface');

        $customerSetup = $customerSetupFactory->create(['setup' => $setupInterface]);

        $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

        $attributeSetFactory = $objectManager->create('Magento\Eav\Model\Entity\Attribute\SetFactory');

        /** @var $attributeSet AttributeSet */
        $attributeSet = $attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

        $customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'attribute_code', [
            'type' => 'varchar',
            'label' => 'Attribute Title',
            'input' => 'text',
            'required' => false,
            'visible' => true,
            'user_defined' => true,
            'sort_order' => 1000,
            'position' => 1000,
            'system' => 0,
        ]);
        //add attribute to attribute set
        $attribute = $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'attribute_code')
        ->addData([
            'attribute_set_id' => $attributeSetId,
            'attribute_group_id' => $attributeGroupId,
            'used_in_forms' => ['adminhtml_customer'],
        ]);

        $attribute->save();

摘要

有了代码的给定说明,我相信您将以编程的方式创建新客户会感到更加舒适和省时。特别是,如果要添加许多客户,则可以循环应用部分代码,并快速完成所有工作

相关文章

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