Как добавить второе поле в регистрационную форму в Magento 2?


Я добавил один атрибут, используя этот код, но когда я пытаюсь добавить другой атрибут, он не работает

Почему?

<?php
namespace Icore\Module\Setup;

use Magento\Customer\Model\Customer;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements \Magento\Framework\Setup\InstallDataInterface
{
    private $eavSetupFactory;

    private $eavConfig;

    private $attributeResource;

    public function __construct(
        \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory,
        \Magento\Eav\Model\Config $eavConfig,
        \Magento\Customer\Model\ResourceModel\Attribute $attributeResource
    ) {
        $this->eavSetupFactory = $eavSetupFactory;
        $this->eavConfig = $eavConfig;
        $this->attributeResource = $attributeResource;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        $eavSetup->removeAttribute(Customer::ENTITY, "skype");

        $attributeSetId = $eavSetup->getDefaultAttributeSetId(Customer::ENTITY);
        $attributeGroupId = $eavSetup->getDefaultAttributeGroupId(Customer::ENTITY);

        $eavSetup->addAttribute(Customer::ENTITY, 'skype', [
            // Attribute parameters
            'type' => 'varchar',
            'label' => 'Skype Account',
            'input' => 'text',
            'required' => false,
            'visible' => true,
            'user_defined' => true,
            'sort_order' => 990,
            'position' => 990,
            'system' => 0,
        ]);

        $attribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'skype');

        $attribute->setData('attribute_set_id', $attributeSetId);
        $attribute->setData('attribute_group_id', $attributeGroupId);


        $eavSetup->removeAttribute(Customer::ENTITY, "bussiness");
        $attributeSetId = $eavSetup->getDefaultAttributeSetId(Customer::ENTITY);
        $attributeGroupId = $eavSetup->getDefaultAttributeGroupId(Customer::ENTITY);

        $eavSetup->addAttribute(Customer::ENTITY, 'bussiness', [
            // Attribute parameters
            'type' => 'varchar',
            'label' => 'Check',
            'input' => 'text',
            'required' => false,
            'visible' => true,
            'user_defined' => true,
            'sort_order' => 1000,
            'position' => 1000,
            'system' => 0,
        ]);

        $attribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'bussiness');
        $attribute->setData('attribute_set_id', $attributeSetId);
        $attribute->setData('attribute_group_id', $attributeGroupId);












        /*
        //You can use this attribute in the following forms
        adminhtml_checkout
        adminhtml_customer
        adminhtml_customer_address
        customer_account_create
        customer_account_edit
        customer_address_edit
        customer_register_address
        */

        $attribute->setData('used_in_forms', [
            'adminhtml_customer',
            'customer_account_create',
            'customer_account_edit'
        ]);

        $this->attributeResource->save($attribute);
    }
}
?>

Также добавлен дополнительный.phtml но не отображается в регистрационной форме Magento 2 (отображается только "учетная запись skype")

<div class="field skype required">
    <label class="label" for="skype">
        <span><?= $block->escapeHtml(__('Skype Account')) ?></span>
    </label>
    <div class="control">
        <input type="text" name="skype" id="skype" value="" title="<?= $block->escapeHtmlAttr(__('Skype Account')) ?>" class="input-text" data-validate="{required:false}">
    </div>
</div>




<div class="field skype required">
    <label class="label" for="skype2">
        <span><?= $block->escapeHtml(__('Check')) ?></span>
    </label>
    <div class="control">
        <input type="text" name="skype2" id="skype2" value="" title="<?= $block->escapeHtmlAttr(__('Check')) ?>" class="input-text" data-validate="{required:false}">
    </div>
</div>

<div class="field tcagreecreateaccount required">
    <div class="control">
        <input type="checkbox" id="tcagreecreateaccount" name="tcagreecreateaccount" data-validate="{required:true}" class="input-checkbox checkbox required" value="1">
        <label for="tcagreecreateaccount" class="label">
            <?= __('Custom T&C') ?>
        </label>
    </div>
</div>

Есть идеи? Пожалуйста, помогите!

Author: fmsthird, 2019-03-16

1 answers

В вашем случае второй атрибут не установлен в таблице magento, так как InstallData.php и InstallSchema.php сработает, когда модуль будет установлен. Итак, во второй раз после того, как вы изменили свой InstallData.php для второго атрибута файл там не сработает.

Magento 2 имеет функцию UpgradeData.php и там мы должны определить нашу версию модуля для обновления данных, и версия модуля должна быть объявлена в module.xml в вашем модуле.

Для получения дополнительной информации висти здесь

Функция обновленных данных, которую вы можете использовать, когда ваш модуль будет запущен в производство, и в следующий раз, когда вы захотите установить новый атрибут в том смысле, что вы можете использовать эту функцию, и на данный момент я надеюсь, что ваше расширение еще не запущено в производство, поэтому вы можете выполнить следующие действия, чтобы установить свой второй атрибут.

Шаги по удалению модуля из базы данных:

Выполните приведенный ниже запрос в вас база данных,

 DELETE from setup_module where module = 'Icore_Module';

Затем измените свой InstallData.php в соответствии с вашими требованиями затем выполните следующие команды для установки модуля

 php bin/magento setup:upgrade
 php bin/magento cache:flush

Надеюсь, это поможет:)

 2
Author: Prathap Gunasekaran, 2019-03-16 11:29:28