Question

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!

Was it helpful?

Solution

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!!

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top