I have created a custom attribute for a customer in Magento 2 and when I tried to save the value it gives me an error "Trying to get property of non-object".
How can I save the attribute value? Here is my code to save the attribute. Any help.
$customer
is the factory class of customer
$customer->setCustomAttribute('custom', 'hello');
$customer->save();
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
$customerSetup->addAttribute(
\Magento\Customer\Model\Customer::ENTITY,
'custom',
[
'type' => 'varchar',
'label' => 'custom',
'input' => 'text',
'required' => false,
'visible' => false,
'user_defined' => true,
'sort_order' => 90,
'position' => 90,
'system' => 0,
]
);
$attribute = $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'custom')
->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_checkout','adminhtml_customer','adminhtml_customer_address','customer_account_edit','customer_address_edit','customer_register_address'],
]);
$attribute->save();