Magento2 Custom attribute is not saving during customer registration from frontend - magento

I am trying to add the custom attribute to registration form. And i have added the attribute successfully by the following code
class InstallData implements InstallDataInterface
{
/**
* #var EavSetupFactory Magento\Eav\Setup\EavSetupFactory
*/
private $eavSetupFactory;
/**
* #var $_eavConfig Config
*/
protected $eavConfig;
public function __construct(EavSetupFactory $eavSetupFactory, Config $eavConfig)
{
$this->eavSetupFactory = $eavSetupFactory;
$this->eavConfig = $eavConfig;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(
\Magento\Customer\Model\Customer::ENTITY,
'mobile',
[
'type' => 'varchar',
'label' => 'Mobile',
'input' => 'text',
'required' => false,
'system' => false,
'position' => 100,
'visible' => true,
'user_defined' => true
]
);
$mobile = $this->eavConfig->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'mobile');
//$forms = ['adminhtml_customer', 'checkout_register', 'customer_account_create', 'customer_account_edit'];
$forms = ['adminhtml_customer'];
$mobile->setData(
'used_in_forms',
$forms
);
$mobile->save();
}
}
And to show at front-end i am using the layout handler customer_account_create with the following code
<referenceContainer name="form.additional.info">
<block class="Namespace\SMS\Block\Active" name="sms_block">
<action method="setTemplate" ifconfig="sms/actions/register" ifvalue="1">
<argument name="template" xsi:type="string">Namespace_SMS::sms/register.phtml</argument>
</action>
</block>
</referenceContainer>
Now it is showing the mobile field during registration. But when i try to create account mobile field value is empty after create account.
Note: I know if i add the 'customer_account_create', 'customer_account_edit' with used_in_form then mobile value save. But after this i can not use a specific template file to render mobile field.
Can you please let me know how can i solve this issue? Thank you very much.

I do not know whether it is 100% correct according to the coding rules. But I have resolved this issue using the observer and little bit changes in InstallData script.
InstallData.php is like this
class InstallData implements InstallDataInterface
{
/**
* Customer setup factory
*
* #var \Magento\Customer\Setup\CustomerSetupFactory
*/
private $customerSetupFactory;
/**
* Init
*
* #param \Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory
*/
public function __construct(\Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory) {
$this->customerSetupFactory = $customerSetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
/** #var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerSetup->addAttribute(
\Magento\Customer\Model\Customer::ENTITY,
'mobile',
[
'type' => 'varchar',
'label' => 'Mobile',
'input' => 'text',
'required' => false,
'system' => false,
'position' => 100,
'visible' => true,
'user_defined' => true
]
);
$customerSetup->updateAttribute('customer', 'mobile', 'is_used_for_customer_segment', '1');
//$forms = ['adminhtml_customer', 'checkout_register', 'customer_account_create', 'customer_account_edit'];
$forms = ['adminhtml_customer'];
$attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'mobile');
$attribute->setData('used_in_forms', ['adminhtml_customer']);
$attribute->addData([
'attribute_set_id' => 1,
'attribute_group_id' => 1
]);
$attribute->save();
$setup->endSetup();
}
}
then events.xml is like this
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="customer_register_success">
<observer name="sMSHandleCustomerSaveAfter" instance="\Namepace\SMS\Observer\CustomerRegisterObserver" />
</event>
</config>
And the observer is like this
class CustomerRegisterObserver implements ObserverInterface
{
/**
* #var \Magento\Customer\Model\CustomerFactory
*/
protected $_customerFactory;
function __construct(CustomerFactory $customerFactory)
{
$this->_customerFactory = $customerFactory;
}
public function execute(Observer $observer)
{
$customerData = $observer->getCustomer();
if($_POST['mobile']) {
$customer = $this->_customerFactory->create()->load($customerData->getId());
$customer->setData('mobile', $_POST['mobile']);
$customer->save();
}
}
}

IF someone is looking for the solution, nearly to the #Abbas answer, but modified in observer part:
<?php
namespace {Vendor}\Module\Observer;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
class CustomerRegisterObserver implements ObserverInterface
{
/**
* #var \Magento\Customer\Model\CustomerFactory
*/
protected $_customerFactory;
protected $_customerRepository;
function __construct(
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Psr\Log\LoggerInterface $logger
) {
$this->_customerFactory = $customerFactory;
$this->_logger = $logger;
}
public function execute(EventObserver $observer)
{
//$this->_logger->info("Observer CustomerRegisterObserver Loaded !");
$event = $observer->getEvent();
$customerData = $event->getCustomer();
if($_POST['mobile']) {
$customer = $this->_customerFactory->create()->load($customerData->getId());
$customer->setData('mobile', $_POST['mobile']);
$customer->save();
}
}
}

Related

filter product attributes with laravel and vuejs

I tried to make Laravel-Vue-Sidebar-Filters and it works for categories,brands and prices but how to do it with attributes , attributevalues and productAttributes and thank you very much
I tried this code but nothing show in the page(for attributeValues)so please how to do it with the right way thank you very much:
public function prodat()
{
$sizes = AttributeValue::whereHas('attribute', function ($query) {
$query->where('code', 'size')->where('is_filterable', 1);
})->get();
return response()->json($sizes);
}
front.vue:
<h3 class="mt-2">Sizes </h3>
<div class="form-check" v-for="(size, index) in sizes">
<input class="form-check-input" type="checkbox" :value="size.id" :id="'size'+index" v-model="selected.sizes">
<label class="form-check-label" :for="'size' + index">
{{ size.value }}
</label>
</div>
I followed https://github.com/LaravelDaily/Laravel-Vue-Sidebar-Filters/commit/0dbffb076c9c16cace8a1b9cddef268e734af808
and how to make it for product attributes if I have this:
product.php:
protected $fillable = [
'brand_id', 'sku', 'name', 'slug', 'description', 'quantity',
'weight', 'price', 'sale_price', 'status', 'featured',
];
/**
* #var array
*/
protected $casts = [
'quantity' => 'integer',
'brand_id' => 'integer',
'status' => 'boolean',
'featured' => 'boolean'
];
/**
* #param $value
*/
public function setNameAttribute($value)
{
$this->attributes['name'] = $value;
$this->attributes['slug'] = Str::slug($value);
}
/**
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function attributes()
{
return $this->hasMany(ProductAttribute::class);
}
attribute.php:
protected $fillable = [
'code', 'name', 'frontend_type', 'is_filterable', 'is_required'
];
/**
* #var array
*/
protected $casts = [
'is_filterable' => 'boolean',
'is_required' => 'boolean',
];
/**
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function values()
{
return $this->hasMany(AttributeValue::class);
}
attributeValue.php:
protected $fillable = [
'attribute_id', 'value', 'price'
];
/**
* #var array
*/
protected $casts = [
'attribute_id' => 'integer',
];
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function attribute()
{
return $this->belongsTo(Attribute::class);
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function productAttributes()
{
return $this->belongsToMany(ProductAttribute::class);
}
productAttribute.php:
protected $fillable = ['attribute_id', 'product_id', 'value', 'quantity', 'price'];
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function product()
{
return $this->belongsTo(Product::class);
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function attribute()
{
return $this->belongsTo(Attribute::class);
}

Magento 2 add custom image attribute to customer profile and show thumbnail

Magento 2 newbie here.
I have built an extension that adds to custom attribute to the customer object. The attributes are in the database and show up on the forms.
My problem is with the image attribute that I called "photo_id". What is the right way of actually uploading, saving the image, showing a thumbnail that expands to full image when clicked? see image below
Here is my installData.php
namespace Lemon\Veripass\Setup;
use Magento\Customer\Model\Customer;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements \Magento\Framework\Setup\InstallDataInterface
{
private $eavSetupFactory;
private $eavConfig;
private $attributeResource;
public function __construct(
\Magento\Eav\Setup\EavSetupFactory $eavSetupFactory,
\Magento\Eav\Model\Config $eavConfig,
\Magento\Customer\Model\ResourceModel\Attribute $attributeResource
) {
$this->eavSetupFactory = $eavSetupFactory;
$this->eavConfig = $eavConfig;
$this->attributeResource = $attributeResource;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(
\Magento\Customer\Model\Customer::ENTITY,
'is_verified',
[
'type' => 'int',
'label' => 'Verified',
'input' => 'boolean',
'required' => false,
'visible' => true,
'user_defined' => true,
'position' => 999,
'system' => 0,
]
);
$verifiedAttribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'is_verified');
// more used_in_forms ['adminhtml_checkout','adminhtml_customer','adminhtml_customer_address','customer_account_edit','customer_address_edit','customer_register_address']
$verifiedAttribute->setData(
'used_in_forms',
['adminhtml_customer']
);
$verifiedAttribute->save();
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(Customer::ENTITY, 'photo_id', [
'type' => 'varchar',
'label' => 'Photo ID',
'input' => 'image',
'required' => false,
'visible' => true,
'user_defined' => true,
'sort_order' => 1000,
'position' => 1000,
'system' => 0,
]);
$attribute = $this->eavConfig->getAttribute(Customer::ENTITY, 'photo_id');
$attribute->setData('used_in_forms', ['adminhtml_customer','customer_account_edit']);
$this->attributeResource->save($attribute);
}
}
my customer_form.xml
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<fieldset name="customer">
<field name="is_verified" formElement="checkbox">
<settings>
<visible>true</visible>
</settings>
</field>
<field name="photo_id" formElement="image">
<settings>
<visible>true</visible>
</settings>
</field>
</fieldset>
</form>
You can using this code like sample.
customer_form.xml
<field name="photo_image" sortOrder="40" formElement="fileUploader">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="source" xsi:type="string">customer</item>
</item>
</argument>
<settings>
<elementTmpl>ui/form/element/uploader/uploader</elementTmpl>
<dataType>string</dataType>
<label translate="true">Photo Image</label>
<visible>true</visible>
<required>true</required>
</settings>
<formElements>
<fileUploader>
<settings>
<required>false</required>
<uploaderConfig>
<param xsi:type="url" name="url" path="your_module_router/media/upload"/>
</uploaderConfig>
<previewTmpl>Magento_Catalog/image-preview</previewTmpl>
</settings>
</fileUploader>
</formElements>
</field>
Namspace_Module/Controller/Adminhtml/Media/Upload.php
/**
* Class Upload
*/
class Upload extends \Magento\Backend\App\Action
{
/**
* Image uploader
*
* #var \Magento\Catalog\Model\ImageUploader
*/
protected $imageUploader;
/**
* Upload constructor.
*
* #param \Magento\Backend\App\Action\Context $context
* #param \Magento\Catalog\Model\ImageUploader $imageUploader
*/
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Catalog\Model\ImageUploader $imageUploader
) {
parent::__construct($context);
$this->imageUploader = $imageUploader;
}
/**
* Check admin permissions for this controller
*
* #return boolean
*/
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Mageaddons_Customs::customs');
}
/**
* Upload file controller action
*
* #return \Magento\Framework\Controller\ResultInterface
*/
public function execute()
{
$imageId = $this->_request->getParam('param_name', 'image');
try {
$result = $this->imageUploader->saveFileToTmpDir($imageId);
$result['cookie'] = [
'name' => $this->_getSession()->getName(),
'value' => $this->_getSession()->getSessionId(),
'lifetime' => $this->_getSession()->getCookieLifetime(),
'path' => $this->_getSession()->getCookiePath(),
'domain' => $this->_getSession()->getCookieDomain(),
];
} catch (\Exception $e) {
$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
}
return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
}
}
Note: This code sample help you add so if want this code working you must modifier for right with your module

Error Adding image in signup form yii2 advanced

i want to add profile avatar in frontend/web/site/signup but there is an error
it said
Unknown Method – yii\base\UnknownMethodException
Calling unknown method: frontend\models\SignupForm::save()
this is the signup.php on frontend/views/site/signup.php
<?php
/* #var $this yii\web\View */
/* #var $form yii\bootstrap\ActiveForm */
/* #var $model \frontend\models\SignupForm */
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
$this->title = 'Signup';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-signup">
<h1><?= Html::encode($this->title) ?></h1>
<p>Please fill out the following fields to signup:</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'form-signup'],['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'first_name')->textInput(['placeholder' => "First Name"]) ?>
<?= $form->field($model, 'last_name')->textInput(['placeholder' => "Last Name"]) ?>
<?= $form->field($model, 'username')->textInput(['placeholder' => "Username"]) ?>
<?= $form->field($model, 'email')->textInput(['placeholder' => "Email"]) ?>
<?= $form->field($model, 'password')->passwordInput(['placeholder' => "Password"]) ?>
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
this is the SiteController.php
<?php namespace frontend\controllers;
use Yii; use yii\base\InvalidParamException; use yii\web\BadRequestHttpException; use yii\web\Controller; use yii\web\UploadedFile; use yii\filters\VerbFilter; use yii\filters\AccessControl; use common\models\LoginForm; use frontend\models\PasswordResetRequestForm; use frontend\models\ResetPasswordForm; use frontend\models\SignupForm; use frontend\models\ContactForm;
/** * Site controller */ class SiteController extends Controller {
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* #inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
/**
* Displays homepage.
*
* #return mixed
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Logs in a user.
*
* #return mixed
*/
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
/**
* Logs out the current user.
*
* #return mixed
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
/**
* Displays contact page.
*
* #return mixed
*/
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending your message.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
/**
* Displays about page.
*
* #return mixed
*/
public function actionAbout()
{
return $this->render('about');
}
/**
* Signs user up.
*
* #return mixed
*/
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
//upload file
$path = Yii::getAlias('#frontend') .'/web/upload/';
$imageName = $model->username;
$model->file = UploadedFile::getInstance($model,'file');
$model->file->saveAs( 'uploads/img/user'.$imageName.'.'.$model->file->extension );
$model->file->saveAs( $path.$imageName.'.'.$model->file->extension );
//save in database
$model->avatar = 'uploads/'.$imageName.'.'.$model->file->extension;
$model->save();
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}else{
return $this->render('signup', [
'model' => $model,
]);
}
}
/**
* Requests password reset.
*
* #return mixed
*/
public function actionRequestPasswordReset()
{
$model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail()) {
Yii::$app->session->setFlash('success', 'Check your email for further instructions.');
return $this->goHome();
} else {
Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for the provided email address.');
}
}
return $this->render('requestPasswordResetToken', [
'model' => $model,
]);
}
/**
* Resets password.
*
* #param string $token
* #return mixed
* #throws BadRequestHttpException
*/
public function actionResetPassword($token)
{
try {
$model = new ResetPasswordForm($token);
} catch (InvalidParamException $e) {
throw new BadRequestHttpException($e->getMessage());
}
if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
Yii::$app->session->setFlash('success', 'New password saved.');
return $this->goHome();
}
return $this->render('resetPassword', [
'model' => $model,
]);
} }
<?php
namespace frontend\controllers;
use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\web\UploadedFile;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
/**
* Site controller
*/
class SiteController extends Controller
and this is the SignupForm.php on frontend/models/SignupForm.php
<?php
namespace frontend\models;
use yii\base\Model;
use common\models\User;
/**
* Signup form
*/
class SignupForm extends Model
{
public $first_name;
public $last_name;
public $username;
public $email;
public $password;
public $avatar;
public $file;
/**
* #inheritdoc
*/
public function rules()
{
return [
['first_name', 'required'],
['last_name', 'required'],
[['file'],'file', 'extensions'=>'jpg, gif, png'],
['username', 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
['password', 'required'],
['password', 'string', 'min' => 6],
];
}
/**
* Signs user up.
*
* #return User|null the saved model or null if saving fails
*/
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$user->first_name = $this->first_name;
$user->first_name = $this->first_name;
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$user->avatar = $this->file;
return $user->save() ? $user : null;
}
}
In your controller SiteController, in action actionSignup() youre using:
$model->save()
Your model doesn't extends ActiveRecord class, so it don't have method save().
Remove this $model->save() from controller, youre saving user anyway in method signup().

How to upload customer profile image in magento 2

I want create a customer image attribute,so customer and admin can upload, update and delete profile image like avatar. I know how is this possible in magento 1,but not in magento 2
.If anyone have any idea please share. Thanks in advance.
create below module files. It worked on magento 2.1.4
Create : app\code\Sashas\CustomerAttribute\etc\module.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Sashas_CustomerAttribute" setup_version="1.0.0">
<sequence>
<module name="Magento_Customer"/>
</sequence>
</module>
</config>
Create: app\code\Sashas\CustomerAttribute\Setup\InstallData.php
<?php
/**
* #author Sashas
* #category Sashas
* #package Sashas_CustomerAttribute
* #copyright Copyright (c) 2015 Sashas IT Support Inc. (http://www.extensions.sashas.org)
*/
namespace Sashas\CustomerAttribute\Setup;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
/**
* #codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{
/**
* #var CustomerSetupFactory
*/
protected $customerSetupFactory;
/**
* #var AttributeSetFactory
*/
private $attributeSetFactory;
/**
* #param CustomerSetupFactory $customerSetupFactory
* #param AttributeSetFactory $attributeSetFactory
*/
public function __construct(
CustomerSetupFactory $customerSetupFactory,
AttributeSetFactory $attributeSetFactory
) {
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
}
/**
* {#inheritdoc}
*/
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
/** #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, 'magento_username', [
'type' => 'varchar',
'label' => 'Magento Username',
'input' => 'image',
'required' => false,
'visible' => true,
'user_defined' => true,
'sort_order' => 1000,
'position' => 1000,
'system' => 0,
]);
$attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'magento_username')
->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer'],
]);
$attribute->save();
}
}
Create : app\code\Sashas\CustomerAttribute\registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Sashas_customerAttribute',
__DIR__
);
?>

Set custom Customer attribute value programmatically Magento 2

I am importing some customers with :
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerFactory = $objectManager->create('\Magento\Customer\Model\CustomerFactory');
$customer = $objectManager->create('Magento\Customer\Model\Customer')->setWebsiteId(1)->loadByEmail('customrr#custom.com');
try {
if(!empty($customer->getData('email')))
{
$customer->setAttr1(1); // Attr1 = Name of the custom Attribute
$customer->setAttr2(2); // Attr2 = Name of the custom Attribute
}
else
{
$customer = $customerFactory->create()->setWebsiteId(1);
}
$customer->setLastname("Lastname");
$customer->setFirstname("Firsty");
.....
$customer->save();
The customer is saved with all his standard attributes correctly but my new attributes won't be saved anyway. I've also tried :
$customer->setCustomAttribute('Attr1','value');
but this didn't work too.
The custom Attribute are shown correclty in Magentos 2 backoffice and the values are saved correctly too if creating a customer manually.
Have you tried:
$customer-> setData('Attr1','value');
and don't forget to save and log the information:
try {
$customer->save();
} catch (\Exception $e) {
// log exception so you can debug the issue if there is one
}
<?php
namespace Custom\Module\Setup;
use Magento\Eav\Model\Config;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
private $eavSetupFactory;
public function __construct(
EavSetupFactory $eavSetupFactory,
Config $eavConfig
) {
$this->eavSetupFactory = $eavSetupFactory;
$this->eavConfig = $eavConfig;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$eavSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'custom_attribute', [
'label' => 'Label',
'system' => 0,
'position' => 720,
'sort_order' => 720,
'visible' => true,
'note' => '',
'type' => 'int',
'input' => 'boolean',
'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
'backend' => \Custom\Module\Model\Customer\Attribute\Backend\DoWHatEver::class,
]
);
$attribute = $this->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'custom_attribute');
$attribute->addData([
'is_user_defined' => 1,
'is_required' => 0,
'default_value' => 0,
'used_in_forms', ['adminhtml_customer']
])->save();
}
public function getEavConfig()
{
return $this->eavConfig;
}
}

Resources