Skip to main content
5 of 7
added 30 characters in body
harri
  • 5.5k
  • 6
  • 46
  • 103

Add Dropdown Customer Attribute in Magento 2.2.1

I have looked over a few tutorials on how to add a customer attribute to the customer edit page within admin.

This however does not seem to be working completely for me. I added the below to my InstallData.php file:

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {

    $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, 'cp_permissions', [
        'type' => 'text',
        'label' => 'Account Type',
        'input' => 'select',
        'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Table',
        'required' => false,
        'visible' => true,
        'user_defined' => true,
        'sort_order' => 101,
        'position' => 101,
        'system' => 0,
        'option' =>
            array (
                'values' =>
                    array (
                        0 => 'Master',
                        1 => 'Branch'
                    ),
            ),
    ]);

    $attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'cp_permissions')
        ->addData([
            'attribute_set_id' => $attributeSetId,
            'attribute_group_id' => $attributeGroupId,
            'used_in_forms' => ['adminhtml_customer'],
        ]);

    $attribute->save();

    }
}

And run setup:upgrade to install the plugin. This works fine it seems and the attribute cp_permissions is added within the eav_attribute table however when checking the customer edit page within admin no attribute is visible. What am i doing wrong here?

UPDATE

I compared my attribute to the gender attribute and matched a lot of the values where there where differences and its shown up. Main issues seems to be that the type was static for gender, the source wasn't being set and need to work out how to make sure this is correct.

Ok not sure what i changed really but this seems to work now but only because i changed the database slightly. Not sure how to get this to work with the setup script still.

harri
  • 5.5k
  • 6
  • 46
  • 103