Add custom attribute in magento 2

做~自己de王妃 提交于 2019-12-11 15:54:45

问题


How to add a custom field to the frontend registration form. I already added required feilds in database by following

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
    $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
    $eavSetup->addAttribute(
        \Magento\Customer\Model\Customer::ENTITY,
        'sample_attribute',
        [
            'type'         => 'varchar',
            'label'        => 'Sample Attribute',
            'input'        => 'text',
            'required'     => false,
            'visible'      => true,
            'user_defined' => true,
            'position'     => 999,
            'system'       => 0,
        ]
    );
    $sampleAttribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'sample_attribute');

    // more used_in_forms ['adminhtml_checkout','adminhtml_customer','adminhtml_customer_address','customer_account_edit','customer_address_edit','customer_register_address']
    $sampleAttribute->setData(
        'used_in_forms',
        ['adminhtml_customer']

    );
    $sampleAttribute->save();
}

my feild listed in magento admin. I'm unable to display it in frontend


回答1:


The path of customer_account_create.xml should be Vendor_Module\view\frontend\layout\.

For those who are new to Magento and do not know about all the filename and filepath conventions to be precise is very important to avoid spending time searching for errors.




回答2:


first thing that comes to my eyes is that attributes are created just for the backend, if you set

'used_in_forms' => ['adminhtml_customer'] 

only, it will display only in backend. You at least have to add

'used_in_forms' => ['adminhtml_customer', 
'customer_account_edit','customer_address_edit','customer_register_address']

but you should post also the code of your register form in frontend




回答3:


To add additional field in a customer account

Vendor_Module\layout\customer_account_create.xml

<?xml version="1.0"?><page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="form.additional.info">
            <block class="Magento\Framework\View\Element\Template" name="my_form_additional_info_customer" template="Vendor_Module::additionalinfocustomer.phtml"/>
        </referenceContainer>
    </body>
</page>

Vendor_Module\view\frontend\templates\additionalinfocustomer.phtml

<fieldset class="fieldset create account" data-hasrequired="<?php /* @escapeNotVerified */echo __('* Required Fields') ?>">
    <legend class="legend"><span><?php /* @escapeNotVerified */ echo __('Additional Information') ?></span></legend>
    <p>
    <div class="field regulation required">
        <label for="Mobile" class="label">
            <span><?php /* @escapeNotVerified */ echo __('Mobile Number') ?></span>
        </label>
        <div class="control">
            <input type="text" name="mobile_number" id="mobile_number" title="<?php /* @escapeNotVerified */ echo __('Mobile Number') ?>" class="input-text" data-validate="{required:true}">
        </div>
    </div>
</p>
</fieldset>

Vendor_Module\Setup\InstallData.php

<?php
/**
 * Copyright © 2018 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Vendor\Module\Setup;

use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
 * Install data
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface {

    /**
     * CustomerSetupFactory
     * @var CustomerSetupFactory
     */
    protected $customerSetupFactory;

    /**
     * $attributeSetFactory
     * @var AttributeSetFactory
     */
    private $attributeSetFactory;

    /**
     * initiate object
     * @param CustomerSetupFactory $customerSetupFactory
     * @param AttributeSetFactory $attributeSetFactory
     */
    public function __construct(
    CustomerSetupFactory $customerSetupFactory, AttributeSetFactory $attributeSetFactory
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
        $this->attributeSetFactory = $attributeSetFactory;
    }

    /**
     * install data method
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {

        /** @var CustomerSetup $customerSetup */
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

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

        /** @var $attributeSet AttributeSet */
        $attributeSet = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
        /**
         * customer registration form default field mobile number
         */
        $customerSetup->addAttribute(Customer::ENTITY, 'mobile_number', [
            'type' => 'varchar',
            'label' => 'Mobile Number',
            'input' => 'text',
            'required' => true,
            'visible' => true,
            'user_defined' => true,
            'sort_order' => 1000,
            'position' => 1000,
            'system' => 0,
        ]);
        //add attribute to attribute set
        $attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'mobile_number')
                ->addData([
            'attribute_set_id' => $attributeSetId,
            'attribute_group_id' => $attributeGroupId,
            'used_in_forms' => ['adminhtml_customer', 'customer_account_create', 'customer_address_edit', 'customer_register_address', 'checkout_register', 'adminhtml_checkout'],
        ]);
        $attribute->save();
    }

}

After that run Below Commands:

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


来源:https://stackoverflow.com/questions/49049011/add-custom-attribute-in-magento-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!