How to save the data for customer custom attribute in magento 2
-
15-04-2021 - |
Question
I created a custom customer attribute using an install script.
$customerSetup -> addAttribute(\Magento\Customer\Model\Customer::ENTITY,
'is_mpowersync',
[
'label' => 'Is Mpowersync',
'system' => false,
'position' => 120,
'sort_order' =>120,
'visible' => true,
'type' => 'int',
'input' => 'select',
"source" => "\Magento\Eav\Model\Entity\Attribute\Source\Boolean",
'required' => false,
'default' => '0',
'group' => 'Account Information',
]
);
$customerSetup -> getEavConfig() -> getAttribute('customer', 'is_mpowersync')->setData('is_user_defined',1)->setData('is_required',0)->setData('used_in_forms', ['adminhtml_customer', 'customer_account_create', 'customer_account_edit']) -> save();
I want to set a value the above created custom attribute programmatically creating the customer. I tried below 3 methods, but data is not saving.
1 . $newcustomer->setData('is_mpowersync','1');
2 . $newcustomer->setCustomAttribute('is_mpowersync',1);
3 . $newcustomer->setIsMpowersync(1);
Both method not saving the data, if I save from backend admin customer creation it saving the data for the custom attribute.
How can I save custom customer attribute in Magento 2 programmatically?
Solution
Here in this example, I have tried to save custom attribute value using the Controller file in custom extension. To fix this issue, firstly we need to create ‘controller.php’ file at below location.
app\code\Vendor\Extension\Controller\Index
<?php
Namespace Vendor\Extension\Controller\Index;
class Controller extends \Magento\Framework\App\Action\Action
{
protected $customer;
protected $customerFactory;
public function __construct(
\Magento\Customer\Model\Customer $customer
\Magento\Customer\Model\ResourceModel\CustomerFactory $customerFactory
)
{
$this->customer = $customer;
$this->customerFactory = $customerFactory;
}
public function execute()
{
$custom = $this->_customerFactory ->create();
$custom = $custom->setWebsiteId($helperData->getWebsiteId());
$custom = $custom->loadByEmail("abc123@xyz.com");
$custom->setCustomAttributeCode(custom attribute value);
// Main code to resolve this issue.
$customerData = $custom->getDataModel();
$customerData->setCustomAttribute('custom_attribute code', 'custom attribute value');
$custom->updateData($customerData);
$custom->save();
}
}
Note : Above code is not tested. you have to check.
I hope it helps!
OTHER TIPS
For anyone still struggling to save a boolean custom registration field value in the db make sure that your form field has a default value for the checkbox : value="1"
<div class="control">
<input type="checkbox" checked name="gj_newsletter" id="gj_newsletter" title="<?php /* @escapeNotVerified */
echo __('Subscribe to Newsletter') ?>" class="input-text" autocomplete="off" value="1">
</div>