3

I want to add new customer attribute 'business_type' which would be a selectbox.

I want to do it in already created module, so I would need module update script.

Can anyone help me on this as I am new to Magento2.

2
  • Can anyone tell me how much time will it take to get a solution?
    – M Umair
    Jun 14, 2019 at 10:14
  • want this attribute on admin site ? Jun 14, 2019 at 10:28

2 Answers 2

3

1) Update module setup version in module.xml file. like setup_version="1.1.0" 2) Create file CustomerSetup.php into Setup/ directory.

    <?php

namespace Vendor\ModuleName\Setup;

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

/**
 * @codeCoverageIgnore
 */
class UpgradeData implements UpgradeDataInterface
{
    /**
     * EAV setup factory
     *
     * @var EavSetupFactory
     */
    private $eavSetupFactory;

    /**
     * Init
     *
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /** @var EavSetup $eavSetup */
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        if (version_compare($context->getVersion(), '1.1.0') < 0){

                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $customerSetup = $objectManager->create('Vendor\ModuleName\Setup\CustomerSetup');
                $customerSetup->installAttributes($customerSetup);



         }
    }
}

3) Create file UpgradeData.php into Setup/ folder.

<?php

namespace Vendor\ModuleName\Setup;

use Magento\Eav\Model\Config;
use Magento\Eav\Model\Entity\Setup\Context;
use Magento\Eav\Setup\EavSetup;
use Magento\Framework\App\CacheInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory;

class CustomerSetup extends EavSetup {

    protected $eavConfig;

    public function __construct(
        ModuleDataSetupInterface $setup,
        Context $context,
        CacheInterface $cache,
        CollectionFactory $attrGroupCollectionFactory,
        Config $eavConfig
        ) {
        $this -> eavConfig = $eavConfig;
        parent :: __construct($setup, $context, $cache, $attrGroupCollectionFactory);
    } 

    public function installAttributes($customerSetup) {
        $this -> installCustomerAttributes($customerSetup);
        $this -> installCustomerAddressAttributes($customerSetup);
    } 

    public function installCustomerAttributes($customerSetup) {


        $customerSetup -> addAttribute(\Magento\Customer\Model\Customer::ENTITY,
            'business_type',
            [
            'label' => 'Business Type',
            'system' => 0,
            'position' => 100,
            'sort_order' =>100,
            'visible' =>  true,
            'note' => '',


                        'type' => 'int',
                        'input' => 'select',
                        'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
                        'option' =>
                        array (
                            'values' =>
                                array (
                                    0 => 'Option1',
                                    1 => 'Option2',
                                    2 => 'Option3',
                                ),
                        ),

            ]
            );

        $customerSetup -> getEavConfig() -> getAttribute('customer', 'business_type')->setData('is_user_defined',1)->setData('is_required',0)->setData('default_value','')->setData('used_in_forms', ['adminhtml_customer', 'checkout_register', 'customer_account_create', 'customer_account_edit', 'adminhtml_checkout']) -> save();


    } 

    public function installCustomerAddressAttributes($customerSetup) {

    } 

    public function getEavConfig() {
        return $this -> eavConfig;
    } 
} 

After that Run Command . I hope it's working for you

3
<?php

namespace Test\Customer\Setup;

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

/**
 * Upgrade Data Class
 *
 * @package   Test\Customer
 */
class UpgradeData implements UpgradeDataInterface
{
    /**
     * Attribute Set Factory
     *
     * @var \Magento\Eav\Model\Entity\Attribute\SetFactory
     */
    private $attributeSetFactory;

    /**
     * Customer Setup Factory
     *
     * @var CustomerSetupFactory
     */
    protected $customerSetupFactory;


    /**
     * Upgrade Data Class Constructor.
     *
     * @param CustomerSetupFactory $customerSetupFactory Customer Setup Factory
     * @param AttributeSetFactory  $attributeSetFactory  Attribute Set Factory
     */
    public function __construct(
        CustomerSetupFactory $customerSetupFactory,
        AttributeSetFactory $attributeSetFactory
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
        $this->attributeSetFactory  = $attributeSetFactory;
    }//end __construct()


    /**
     * Upgrade Script to create custom customer attributes
     *
     * @param ModuleDataSetupInterface $setup   Module Data Setup Interface
     * @param ModuleContextInterface   $context Module Context Interface
     * @throws \Magento\Framework\Exception\AlreadyExistsException
     * @throws \Magento\Framework\Exception\FileSystemException
     */
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        if (version_compare($context->getVersion(), '2.0.0', '<')) {
            $this->createDropdownAttribute($setup);
        }
        $setup->endSetup();
    }//end upgrade()


    /**
     * create country_code customer attribute
     *
     * @param ModuleDataSetupInterface $setup Setup
     */
    private function createDropdownAttribute($setup) : void
    {
        $attributeCode  = 'dropdown_attribute';
        $attributeLabel = 'Dropdown Attribute';

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

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

        $attributeSet     = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

        $customerSetup->addAttribute(Customer::ENTITY, $attributeCode, [
            'label' => $attributeLabel,
            'type' => 'varchar',
            'input' => 'select',
            'source' => 'Test\Customer\Model\Source\DropdownValues',
            'required' => false,
            'visible' => true,
            'visible_on_front' => true,
            'user_defined' => false,
            'position' => 95,
            'system' => 0,
        ]);

        $attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, $attributeCode)
            ->addData([
                'attribute_set_id' => $attributeSetId,
                'attribute_group_id' => $attributeGroupId,
                'used_in_forms' => [
                    'customer_account_edit',
                    'adminhtml_customer',
                ],
                'is_used_for_customer_segment' => false,
                'is_system' => 0,
                'is_user_defined' => 1,
                'is_visible' => 1,
            ]);

        $attribute->save();
    }//end createDropdownAttribute()


}//end class
<?php

namespace Test\Customer\Model\Source;

use Magento\Eav\Model\Entity\Attribute\Source\Table as SourceTable;

/**
 * Class DropdownValues
 * @package Test\Customer\Model\Source
 */
class DropdownValues extends SourceTable
{


    /**
     * Retrieve Full Option values array
     * @return array
     */
    public function getAllOptions() : array
    {
        $this->_options = $this->getDropDownOptions();

        return $this->_options;
    }//end getAllOptions()


    /**
     * @return array
     */
    public function getDropDownOptions(): array
    {
        return [
            [
                'label' => 'First Value',
                'value' => 'First Value',
            ],
            [
                'label' => 'Second Value',
                'value' => 'Second Value',
            ],
            // You can add as much as you want.
        ];
    }//end getDropDownOptions()


}//end class

This might help you to create dropdown attribute.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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