1

I want to create a custom select field of select a course in registration form in which i have 5 options and when user click on create account its value should store in a course column in customer_entity table in magento 2 how to do this?

1

First of all create UpgradeSchema file to add column in table

<?php
namespace Companyname\Modulename\Setup;

use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
    class UpgradeSchema implements  UpgradeSchemaInterface
    {
        public function upgrade(SchemaSetupInterface $setup,
                                ModuleContextInterface $context){
            $setup->startSetup();
            
            if (version_compare($context->getVersion(), '1.0.2') < 0) {

                // Get module table
                $tableName = $setup->getTable('customer_entity');

                // Check if the table already exists
                if (version_compare($context->getVersion(), '1.0.1', '<')) {
            
                $setup->getConnection()->addColumn(
                $setup->getTable('customer_entity '),
                'course_name',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    'length' => 255,
                    'nullable' => false,
                    'comment' => 'Course Name'
                ]
            );
            }
            $setup->endSetup();
            }
        }
    }
?>

Then Run Commands:
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy -f
php bin/magento cache:flush

After that you have to get data in controller directory and save it to the custom column you created.

1
  • how to get data in controller directory – Aalap Aug 27 '20 at 7:42
0

Magento 2 uses Data scripts to add attributes. In folder Vendor/Module/Setup/Patch/Data add a .php file (eg: AddCustomerAttributes)

The following will add a customer attribute with options to the dropdown. After adding this bin/magento setup:upgrade command is required.

There will be an entry added to patch_list datatable, if the script file was executed correctly and also the attributes in the eav attribute table of course.

<?php
namespace Vendor\Module\Setup\Patch\Data;

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

class AddCustomerAttributes implements DataPatchInterface
{
    /**
     * @var ModuleDataSetupInterface
     */
    protected $moduleDataSetup;

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

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

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

    /**
     * {@inheritdoc}
     */
    public function apply()
    {
        $customerSetup = $this->customerSetupFactory->create(['setup' => $this->moduleDataSetup]);

        $customerEntity = $customerSetup->getEavConfig()->getEntityType(Customer::ENTITY);
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

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

        /** attribute_2 */
        $customerSetup->addAttribute(
            Customer::ENTITY,
            'attribute_2',
            [
                'type' => 'int',
                'label' => 'Attribute Two',
                'input' => 'select',
                'source' => 'Vendor\Module\Model\Config\Source\Options',
                'required' => false,
                'user_defined' => true,
                'sort_order' => 1000,
                'position' => 1000,
                'default' => 0,
                'system' => 0
            ]
        );

        $attribute = $customerSetup->getEavConfig()->getAttribute(
            Customer::ENTITY,
            'attribute_2'
        );

        $attribute->addData(
            [
                'attribute_set_id' => $attributeSetId,
                'attribute_group_id' => $attributeGroupId,
                'used_in_forms' => ['customer_account_create']
            ]
        );

        $attribute->save();
    }

    /**
     * {@inheritdoc}
     */
        public static function getDependencies()
    {
        return [];
    }

        /**
         * {@inheritdoc}
         */
        public function getAliases()
    {
        return [];
    }
}

If you want to add options to the dropdown you can use the follwing file Vendor/Module/Model/Config/Source/Options.php

<?php
namespace Vendor\Module\Model\Config\Source;

use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource;
use Magento\Eav\Model\Entity\Attribute\Source\SourceInterface;
use Magento\Framework\Data\OptionSourceInterface;

class Options extends AbstractSource implements SourceInterface, OptionSourceInterface
{
    /**
     * @return array
     */
    public static function getOptionArray()
    {
        return [
            '' => __(''),
            1 => __('Option 1'),
            2 => __('Option 2'),
            3 => __('Option 3')
        ];
    }

    /**
     * @return array
     */
    public function getAllOptions()
    {
        $result = [];

        foreach (self::getOptionArray() as $index => $value) {
            $result[] = ['value' => $index, 'label' => $value];
        }

        return $result;
    }
}

enter image description here

3
  • how to show this field in the registration form and how to store the value that i get from this select field into a column that i have created – Aalap Aug 27 '20 at 7:44
  • The field will be already shown in customer registration form as we have marked in the script. 'used_in_forms' => ['customer_account_create'] You will have to write some custom method to save this to a new custom column. – Paboda Aug 28 '20 at 1:55
  • where and what code i have to write to get it in the customer_entity table – Aalap Sep 7 '20 at 2:16

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.