0

I created a module in this way: I created a vendor folder "Test1" Then I created a module folder "AddCustomerAttr" then a folder inside the module "etc" and inside "etc" I put module.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Test1_AddCustomerAttr" setup_version="0.0.2">
</module>

Then I created registration.php:

 \Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE, 'Test1_AddCustomerAttr',
__DIR__
);

Then I created "Model" folder and "Attribute" folder inside it and then I created 3 folders inside "Attribute": "Backend" "Frontend" and "Source"

Inside of each folder, I created a file Attribute.php

/Backend/Attribute.php:

 namespace Test1\AddCustomerAttr\Model\Attribute\Backend;

 class Attribute extends \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend
 {
 /**
 * Validate
 * @param \Magento\Catalog\Model\Product $object
 * @throws \Magento\Framework\Exception\LocalizedException
 * @return bool
 */
public function validate($object)
{
    $value = $object->getData($this->getAttribute()->getAttributeCode());
    if ( ($object->getAttributeSetId() == 10) && ($value == 'wool')) {
        throw new \Magento\Framework\Exception\LocalizedException(
            __('Bottom can not be wool.')
        );
    }
    return true;
}
}

/Frontend/Attribute.php:

 namespace Test1\AddCustomerAttr\Model\Attribute\Frontend;
 class Attribute extends \Magento\Eav\Model\Entity\Attribute\Frontend\AbstractFrontend
 {
 public function getValue(\Magento\Framework\DataObject $object)
 {
    $value = $object->getData($this->getAttribute()->getAttributeCode());
    return "<b>$value</b>";
}
}

Then I created a Setup folder inside module folder and I put file InstallData.php inside it:

InstallData.php:

namespace Test1\AddCustomerData\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{
  private $eavSetupFactory;

  public function __construct(EavSetupFactory $eavSetupFactory)
  {
      $this->eavSetupFactory = $eavSetupFactory;
  }

  public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
  {
      $eavSetup = $this->eavSetupFactory->create();
      $eavSetup->addAttribute(
        \Magento\Customer\Model\Customer::ENTITY,
        'test_attribute',
        [
            'group' => 'General',
            'type' => 'varchar',
            'label' => 'Test Attribute',
            'input' => 'select',
            'source' => 'Test1\AddCustomerAttr\Model\Attribute\Source\Material',
            'frontend' => 'Test1\AddCustomerAttr\Model\Attribute\Frontend\Material',
            'backend' => 'Test1\AddCustomerAttr\Model\Attribute\Backend\Material',
            'required' => false,
            'sort_order' => 50,
            'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
            'is_used_in_grid' => false,
            'is_visible_in_grid' => false,
            'is_filterable_in_grid' => false,
            'visible' => true,
            'is_html_allowed_on_front' => true,
            'visible_on_front' => true
        ]
    );
  }

}

Then I run command

php bin/magento setup:upgrade

But no change occurred in customer page!

I did these modules on Product Model and It correctly worked!

I also tried these instructions: https://www.mageplaza.com/magento-2-module-development/magento-2-add-customer-attribute-programmatically.html But still I don't know what is the problem and it didn't work too.

1

To add customer attribute follow this step:

Namespace\Module\Setup\InstallData.php

    <?php
namespace Namespace\Module\Setup;

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

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

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

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

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


    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);

        $customerSetup->addAttribute(Customer::ENTITY, 'custom_attribute', [
            'type' => 'varchar',
            'label' => 'Custom Attribute',
            'input' => 'text',
            'required' => false,
            'visible' => true,
            'user_defined' => true,
            'position' =>999,
            'system' => 0,
        ]);

        $attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'custom_attribute')
        ->addData([
            'attribute_set_id' => $attributeSetId,
            'attribute_group_id' => $attributeGroupId,
            'used_in_forms' => ['adminhtml_customer'],//you can use other forms also ['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address']
        ]);

        $attribute->save();
    }
}

Check Backend: enter image description here

For Frontend Override vendor/magento/module-customer/view/frontend/templates/form/edit.phtml and add this

<div class="field custom_attribute">
    <label class="label" for="customer_attribute”><span><?php /* @escapeNotVerified */ echo __('Custom Attribute') ?></span></label>
    <div class="control">
        <input type="text" id="customer_attribute" name="customer_attribute" value="<?php echo $block->escapeHtml($block->getCustomer()->getCustomAttribute('customer_attribute')->getValue()) ?>" title="<?php /* @escapeNotVerified */ echo __('Custom Attribute') ?>" class="input-text" autocomplete="off" />
    </div>
</div>

Override vendor/magento/module-customer/view/frontend/templates/form/register.phtml

<div class="field custom_attribute”>
    <label class="label" for="customer_attribute"><span><?php /* @escapeNotVerified */ echo __('Custom Attribute') ?></span></label>
    <div class="control">
        <input type="text" id="customer_attribute" name="customer_attribute" value="<?php echo $block->escapeHtml($block->getFormData()->getCustomerAttribute()) ?>" title="<?php /* @escapeNotVerified */ echo __('Custom Attribute') ?>" class="input-text" autocomplete="off">
    </div>
</div>

source: https://webkul.com/blog/how-to-create-customer-custom-attribute-in-magento-2-0/

0

As Sameer Bhayani answered before, customer custom attribute should be assigned to an attribute set, also specifying 'used_in_forms' data you will add the attribute to those forms.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.