0

I want to create a custom customer account which should be displayed as dropdown in frontend (customer registration) and backend (edit customer).

I only was able to create a "normal" custom attribute.

Anyone knows how I can do that?

Thanks!

2 Answers 2

4

please try using this code,

public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
    if (version_compare($context->getVersion(), 'VERSION') < 0) {
        /** @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' => 'text',
            'label' => 'Custom Attribute',
            'input' => 'select',
            'source' => Options::class,
            'required' => false,
            'visible' => true,
            'user_defined' => true,
            'sort_order' => 999,
            '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', 'customer_account_edit', 'customer_account_create'],
            ]);
        $attribute->save();
    }
}

you have to define a source class, which shows options you want to show in dropdown. for that, create a class named option.

vendor\module\Model\Config;

use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource;

class Options extends AbstractSource
{

/**
 * Retrieve All options
 *
 * @return array
 */
public function getAllOptions()
  {
    $this->_options = [
        ['label'=>__('Label 1'),'value'=>'label1'],
        ['label'=>__('Label 2'),'value'=>'label2'],
        ['label'=>__('Label 3'),'value'=>'label3'],
        ['label'=>__('Label 4'),'value'=>'label4']
    ];

    return $this->_options;
   }
}

Hope this will help you!!

1
  • please accept as answer if you found it right, so it will be helpful to other also. Commented Mar 30, 2020 at 14:03
0

@Dimple Panchal answer worked for me. Just adding to it: I had to import the class to the top of my UpgradeData.php file

use Company\Name\Model\Config\Classname;

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.