1

Below is code for creating customer attribute.

namespace Namespace\Modulename\Setup;

use Magento\Customer\Model\Customer;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{

    private $customerSetupFactory;

    /**
     * Constructor
     *
     * @param \Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory
     */
    public function __construct(
        CustomerSetupFactory $customerSetupFactory
    ) {
        $this->customerSetupFactory = $customerSetupFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function install(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {

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

        $customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'attribute_code', [
            'type' => 'text',
            'label' => 'Status',
            'input' => 'select',
            'source' => 'Namespace\Modulename\Model\Customer\Attribute\Source\AttributeData',
            'required' => false,
            'visible' => true,
            'position' => 333,
            'system' => false,
            'user_defined' => false,
            'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
            'backend' => ''
        ]);

        $attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'attribute_code')
        ->addData(['used_in_forms' => [
                'customer_account_edit'
            ]
        ]);
        $attribute->save();

        //Your install script
    }
}

Attribute is displayed on customer edit page in admin but when I set value and save customer, data for custom attribute is not being saved.

Am I missing anything here?

3

If You want to enable this attribute for admin customer form then you have to add below form area.

'adminhtml_customer'

By changing

 ->addData(['used_in_forms' => [
                'customer_account_edit'
            ]
        ])

tO

->addData(['used_in_forms' => [
                'customer_account_edit','adminhtml_customer'
            ]
        ])

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.