Magento 2.3 - Add custom customer entity attribute with service contractHow can I add customer attribute in Magento 2?EAV collection problem with Customer entityMagento 2: What's a Service ContractMagento 2: How to add a custom attribute to the CMS Pageservice contract save method flow - magento 2Magento 2.1.5 How to create Module which can use Eav functionalities (addAttribute in my case)How to update customer data faster and more efficientlyMagento 2. Update customer attribute outside Setup [Install|Upgrade]DataHow to implement a Customer custom attribute using EAV?magento 2.2.5: Adding Custom Attribute to Customer Edit Form in Admin

Weird lines in Microsoft Word

Offset in split text content

Recursively move files within sub directories

Would a primitive species be able to learn English from reading books alone?

How to test the sharpness of a knife?

When is the exact date for EOL of Ubuntu 14.04 LTS?

Reasons for having MCU pin-states default to pull-up/down out of reset

Is there a POSIX way to shutdown a UNIX machine?

Do people actually use the word "kaputt" in conversation?

Trouble reading roman numeral notation with flats

Put the phone down / Put down the phone

Do native speakers use "ultima" and "proxima" frequently in spoken English?

Derivative of an interpolated function

A seasonal riddle

Is there a distance limit for minecart tracks?

How do you justify more code being written by following clean code practices?

What is the purpose of using a decision tree?

How to preserve electronics (computers, ipads, phones) for hundreds of years?

Not hide and seek

How can I, as DM, avoid the Conga Line of Death occurring when implementing some form of flanking rule?

Can you take a "free object interaction" while incapacitated?

Strange behavior in TikZ draw command

Friend wants my recommendation but I don't want to give it to him

Should a narrator ever describe things based on a character's view instead of facts?



Magento 2.3 - Add custom customer entity attribute with service contract


How can I add customer attribute in Magento 2?EAV collection problem with Customer entityMagento 2: What's a Service ContractMagento 2: How to add a custom attribute to the CMS Pageservice contract save method flow - magento 2Magento 2.1.5 How to create Module which can use Eav functionalities (addAttribute in my case)How to update customer data faster and more efficientlyMagento 2. Update customer attribute outside Setup [Install|Upgrade]DataHow to implement a Customer custom attribute using EAV?magento 2.2.5: Adding Custom Attribute to Customer Edit Form in Admin













3















I have some problem to save custom customer entity attribute in database.

I've created a Patch to add this attribute to the customer entity. The attribute is shown correctly in the backend, but when I try to save it, the value doesn't save in the database.



My code is the following:



<?php
declare(strict_types=1);

namespace PedReferralSetupPatchData;

use MagentoCustomerModelCustomer;
use MagentoCustomerSetupCustomerSetupFactory;
use MagentoEavApiAttributeRepositoryInterface;
use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoFrameworkSetupPatchDataPatchInterface;
use MagentoEavSetupEavSetupFactory;

class AddCustomerReferralCodeAttribute implements DataPatchInterface
void
* @throws MagentoFrameworkExceptionLocalizedException
* @throws MagentoFrameworkExceptionStateException
*/
public function apply()

$this->removeReferralCodeAttribute();
$this->addReferralCodeAttribute();


/**
* Remove referral_code customer attribute
*/
private function removeReferralCodeAttribute()

$eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
$eavSetup->removeAttribute(Customer::ENTITY, 'referral_code');


/**
* Add referral_code customer attribute
* @throws MagentoFrameworkExceptionLocalizedException
* @throws MagentoFrameworkExceptionStateException
*/
private function addReferralCodeAttribute()

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

$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();

$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

$customerSetup->addAttribute(
Customer::ENTITY,
'referral_code',
[
'type' => 'varchar',
'label' => 'Referral Code',
'input' => 'text',
'required' => false,
'sort_order' => 999,
'position' => 999,
'visible' => true,
'default' => '',
'user_defined' => true,
'system' => 0,
'unique' => true,
]
);

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

$this->attributeRepository->save($referralCodeAttribute);




If I replace $this->attributeRepository->save($referralCodeAttribute); with $referralCodeAttribute->save() all works properly, but I don't want to use the save() method of attribute entity, because is deprecated.



I know that now I should use the resource model/api interface to save attribute, but in both cases, the attribute is showing on the admin panel, but when I try to save, it doesn't work. Why?



How can I use the resource model/api interface correctly to save the custom attribute?










share|improve this question









New contributor




Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • did you try using MagentoEavApiAttributeSetRepositoryInterface ?

    – magefms
    17 hours ago












  • No, I will try it and I'll say you if it works

    – Mirko Rapisarda
    17 hours ago











  • I have modified your code, please check and let me know if it works or not

    – magefms
    17 hours ago















3















I have some problem to save custom customer entity attribute in database.

I've created a Patch to add this attribute to the customer entity. The attribute is shown correctly in the backend, but when I try to save it, the value doesn't save in the database.



My code is the following:



<?php
declare(strict_types=1);

namespace PedReferralSetupPatchData;

use MagentoCustomerModelCustomer;
use MagentoCustomerSetupCustomerSetupFactory;
use MagentoEavApiAttributeRepositoryInterface;
use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoFrameworkSetupPatchDataPatchInterface;
use MagentoEavSetupEavSetupFactory;

class AddCustomerReferralCodeAttribute implements DataPatchInterface
void
* @throws MagentoFrameworkExceptionLocalizedException
* @throws MagentoFrameworkExceptionStateException
*/
public function apply()

$this->removeReferralCodeAttribute();
$this->addReferralCodeAttribute();


/**
* Remove referral_code customer attribute
*/
private function removeReferralCodeAttribute()

$eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
$eavSetup->removeAttribute(Customer::ENTITY, 'referral_code');


/**
* Add referral_code customer attribute
* @throws MagentoFrameworkExceptionLocalizedException
* @throws MagentoFrameworkExceptionStateException
*/
private function addReferralCodeAttribute()

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

$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();

$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

$customerSetup->addAttribute(
Customer::ENTITY,
'referral_code',
[
'type' => 'varchar',
'label' => 'Referral Code',
'input' => 'text',
'required' => false,
'sort_order' => 999,
'position' => 999,
'visible' => true,
'default' => '',
'user_defined' => true,
'system' => 0,
'unique' => true,
]
);

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

$this->attributeRepository->save($referralCodeAttribute);




If I replace $this->attributeRepository->save($referralCodeAttribute); with $referralCodeAttribute->save() all works properly, but I don't want to use the save() method of attribute entity, because is deprecated.



I know that now I should use the resource model/api interface to save attribute, but in both cases, the attribute is showing on the admin panel, but when I try to save, it doesn't work. Why?



How can I use the resource model/api interface correctly to save the custom attribute?










share|improve this question









New contributor




Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • did you try using MagentoEavApiAttributeSetRepositoryInterface ?

    – magefms
    17 hours ago












  • No, I will try it and I'll say you if it works

    – Mirko Rapisarda
    17 hours ago











  • I have modified your code, please check and let me know if it works or not

    – magefms
    17 hours ago













3












3








3








I have some problem to save custom customer entity attribute in database.

I've created a Patch to add this attribute to the customer entity. The attribute is shown correctly in the backend, but when I try to save it, the value doesn't save in the database.



My code is the following:



<?php
declare(strict_types=1);

namespace PedReferralSetupPatchData;

use MagentoCustomerModelCustomer;
use MagentoCustomerSetupCustomerSetupFactory;
use MagentoEavApiAttributeRepositoryInterface;
use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoFrameworkSetupPatchDataPatchInterface;
use MagentoEavSetupEavSetupFactory;

class AddCustomerReferralCodeAttribute implements DataPatchInterface
void
* @throws MagentoFrameworkExceptionLocalizedException
* @throws MagentoFrameworkExceptionStateException
*/
public function apply()

$this->removeReferralCodeAttribute();
$this->addReferralCodeAttribute();


/**
* Remove referral_code customer attribute
*/
private function removeReferralCodeAttribute()

$eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
$eavSetup->removeAttribute(Customer::ENTITY, 'referral_code');


/**
* Add referral_code customer attribute
* @throws MagentoFrameworkExceptionLocalizedException
* @throws MagentoFrameworkExceptionStateException
*/
private function addReferralCodeAttribute()

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

$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();

$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

$customerSetup->addAttribute(
Customer::ENTITY,
'referral_code',
[
'type' => 'varchar',
'label' => 'Referral Code',
'input' => 'text',
'required' => false,
'sort_order' => 999,
'position' => 999,
'visible' => true,
'default' => '',
'user_defined' => true,
'system' => 0,
'unique' => true,
]
);

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

$this->attributeRepository->save($referralCodeAttribute);




If I replace $this->attributeRepository->save($referralCodeAttribute); with $referralCodeAttribute->save() all works properly, but I don't want to use the save() method of attribute entity, because is deprecated.



I know that now I should use the resource model/api interface to save attribute, but in both cases, the attribute is showing on the admin panel, but when I try to save, it doesn't work. Why?



How can I use the resource model/api interface correctly to save the custom attribute?










share|improve this question









New contributor




Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












I have some problem to save custom customer entity attribute in database.

I've created a Patch to add this attribute to the customer entity. The attribute is shown correctly in the backend, but when I try to save it, the value doesn't save in the database.



My code is the following:



<?php
declare(strict_types=1);

namespace PedReferralSetupPatchData;

use MagentoCustomerModelCustomer;
use MagentoCustomerSetupCustomerSetupFactory;
use MagentoEavApiAttributeRepositoryInterface;
use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoFrameworkSetupPatchDataPatchInterface;
use MagentoEavSetupEavSetupFactory;

class AddCustomerReferralCodeAttribute implements DataPatchInterface
void
* @throws MagentoFrameworkExceptionLocalizedException
* @throws MagentoFrameworkExceptionStateException
*/
public function apply()

$this->removeReferralCodeAttribute();
$this->addReferralCodeAttribute();


/**
* Remove referral_code customer attribute
*/
private function removeReferralCodeAttribute()

$eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
$eavSetup->removeAttribute(Customer::ENTITY, 'referral_code');


/**
* Add referral_code customer attribute
* @throws MagentoFrameworkExceptionLocalizedException
* @throws MagentoFrameworkExceptionStateException
*/
private function addReferralCodeAttribute()

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

$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();

$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

$customerSetup->addAttribute(
Customer::ENTITY,
'referral_code',
[
'type' => 'varchar',
'label' => 'Referral Code',
'input' => 'text',
'required' => false,
'sort_order' => 999,
'position' => 999,
'visible' => true,
'default' => '',
'user_defined' => true,
'system' => 0,
'unique' => true,
]
);

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

$this->attributeRepository->save($referralCodeAttribute);




If I replace $this->attributeRepository->save($referralCodeAttribute); with $referralCodeAttribute->save() all works properly, but I don't want to use the save() method of attribute entity, because is deprecated.



I know that now I should use the resource model/api interface to save attribute, but in both cases, the attribute is showing on the admin panel, but when I try to save, it doesn't work. Why?



How can I use the resource model/api interface correctly to save the custom attribute?







customer-attribute eav service-contract






share|improve this question









New contributor




Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 17 hours ago









magefms

1,8321425




1,8321425






New contributor




Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 17 hours ago









Mirko RapisardaMirko Rapisarda

264




264




New contributor




Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • did you try using MagentoEavApiAttributeSetRepositoryInterface ?

    – magefms
    17 hours ago












  • No, I will try it and I'll say you if it works

    – Mirko Rapisarda
    17 hours ago











  • I have modified your code, please check and let me know if it works or not

    – magefms
    17 hours ago

















  • did you try using MagentoEavApiAttributeSetRepositoryInterface ?

    – magefms
    17 hours ago












  • No, I will try it and I'll say you if it works

    – Mirko Rapisarda
    17 hours ago











  • I have modified your code, please check and let me know if it works or not

    – magefms
    17 hours ago
















did you try using MagentoEavApiAttributeSetRepositoryInterface ?

– magefms
17 hours ago






did you try using MagentoEavApiAttributeSetRepositoryInterface ?

– magefms
17 hours ago














No, I will try it and I'll say you if it works

– Mirko Rapisarda
17 hours ago





No, I will try it and I'll say you if it works

– Mirko Rapisarda
17 hours ago













I have modified your code, please check and let me know if it works or not

– magefms
17 hours ago





I have modified your code, please check and let me know if it works or not

– magefms
17 hours ago










2 Answers
2






active

oldest

votes


















1














Try this one using MagentoEavApiAttributeSetRepositoryInterface:



<?php
/*declare(strict_types=1);*/

namespace PedReferralSetupPatchData;

use MagentoCustomerModelCustomer;
use MagentoCustomerSetupCustomerSetupFactory;
use MagentoEavApiAttributeRepositoryInterface;
use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoFrameworkSetupPatchDataPatchInterface;
use MagentoEavSetupEavSetupFactory;
//add this AttributeSetRepositoryInterface
use MagentoEavApiAttributeSetRepositoryInterface;

class AddCustomerReferralCodeAttribute implements DataPatchInterface
void
* @throws MagentoFrameworkExceptionLocalizedException
* @throws MagentoFrameworkExceptionStateException
*/
public function apply()

$this->removeReferralCodeAttribute();
$this->addReferralCodeAttribute();


/**
* Remove referral_code customer attribute
*/
private function removeReferralCodeAttribute()

$eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
$eavSetup->removeAttribute(Customer::ENTITY, 'referral_code');


/**
* @throws MagentoFrameworkExceptionInputException
* @throws MagentoFrameworkExceptionLocalizedException
* @throws MagentoFrameworkExceptionNoSuchEntityException
*/
private function addReferralCodeAttribute()

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

$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();

$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

$customerSetup->addAttribute(
Customer::ENTITY,
'referral_code',
[
'type' => 'varchar',
'label' => 'Referral Code',
'input' => 'text',
'required' => false,
'sort_order' => 999,
'position' => 999,
'visible' => true,
'default' => '',
'user_defined' => true,
'system' => 0,
'unique' => true,
]
);

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

//$this->attributeRepository->save($referralCodeAttribute);
$this->attribute->save($referralCodeAttribute);







share|improve this answer























  • No, it doesn't work, I receive this error: "Fatal error: Uncaught TypeError: Argument 1 passed to MagentoEavModelAttributeSetRepositoryInterceptor::save() must implement interface MagentoEavApiDataAttributeSetInterface, instance of MagentoCustomerModelAttribute given, called in /var/www/html/app/code/Ped/Referral/Setup/Patch/Data/AddCustomerReferralCodeAttribute.php on line 138 and defined in /var/www/html/generated/code/Magento/Eav/Model/AttributeSetRepository/Interceptor.php:20"

    – Mirko Rapisarda
    16 hours ago



















1














I found the solution by dump the ResourceModel classname used by the save() method that was deprecated in favor of service contract. The resource model that I should used is MagentoCustomerModelResourceModelAttribute. Here the complete code:



<?php 
namespace PedReferralSetupPatchData;

use MagentoCustomerModelCustomer;
use MagentoCustomerModelResourceModelAttribute as AttributeResourceModel;
use MagentoCustomerSetupCustomerSetupFactory;
use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoFrameworkSetupPatchDataPatchInterface;

class AddCustomerReferralCodeAttribute implements DataPatchInterface

private const REFERRAL_CODE_FIELD_NAME = 'referral_code';

/**
* @var ModuleDataSetupInterface
*/
private $moduleDataSetup;

/**
* @var CustomerSetupFactory
*/
private $customerSetupFactory;

/**
* @var AttributeSetFactory
*/
private $attributeSetFactory;

/**
* @var EavSetupFactory
*/
private $eavSetupFactory;

/**
* @var AttributeResourceModel
*/
private $attributeResourceModel;

public function __construct(
ModuleDataSetupInterface $moduleDataSetup,
CustomerSetupFactory $customerSetupFactory,
AttributeSetFactory $attributeSetFactory,
EavSetupFactory $eavSetupFactory,
AttributeResourceModel $attributeResourceModel
)
$this->moduleDataSetup = $moduleDataSetup;
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
$this->eavSetupFactory = $eavSetupFactory;
$this->attributeResourceModel = $attributeResourceModel;


/**
* @inheritdoc
*/
public static function getDependencies()

return [];


/**
* @inheritdoc
*/
public function getAliases()

return [];


/**
* @inheritdoc
* @throws MagentoFrameworkExceptionLocalizedException
*/
public function apply()

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

$customerEntity = $customerSetup->getEavConfig()->getEntityType(Customer::ENTITY);
$attributeSetId = $customerEntity->getDefaultAttributeSetId();

$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

$customerSetup->addAttribute(
Customer::ENTITY,
static::REFERRAL_CODE_FIELD_NAME,
[
'type' => 'varchar',
'label' => 'Referral Code',
'input' => 'text',
'required' => false,
'sort_order' => 999,
'position' => 999,
'visible' => true,
'default' => '',
'user_defined' => true,
'system' => 0,
'unique' => true,
]
);

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

$this->attributeResourceModel->save($referralCodeAttribute);








share|improve this answer










New contributor




Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.



















    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "479"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );






    Mirko Rapisarda is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f266481%2fmagento-2-3-add-custom-customer-entity-attribute-with-service-contract%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Try this one using MagentoEavApiAttributeSetRepositoryInterface:



    <?php
    /*declare(strict_types=1);*/

    namespace PedReferralSetupPatchData;

    use MagentoCustomerModelCustomer;
    use MagentoCustomerSetupCustomerSetupFactory;
    use MagentoEavApiAttributeRepositoryInterface;
    use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
    use MagentoFrameworkSetupModuleDataSetupInterface;
    use MagentoFrameworkSetupPatchDataPatchInterface;
    use MagentoEavSetupEavSetupFactory;
    //add this AttributeSetRepositoryInterface
    use MagentoEavApiAttributeSetRepositoryInterface;

    class AddCustomerReferralCodeAttribute implements DataPatchInterface
    void
    * @throws MagentoFrameworkExceptionLocalizedException
    * @throws MagentoFrameworkExceptionStateException
    */
    public function apply()

    $this->removeReferralCodeAttribute();
    $this->addReferralCodeAttribute();


    /**
    * Remove referral_code customer attribute
    */
    private function removeReferralCodeAttribute()

    $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
    $eavSetup->removeAttribute(Customer::ENTITY, 'referral_code');


    /**
    * @throws MagentoFrameworkExceptionInputException
    * @throws MagentoFrameworkExceptionLocalizedException
    * @throws MagentoFrameworkExceptionNoSuchEntityException
    */
    private function addReferralCodeAttribute()

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

    $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
    $attributeSetId = $customerEntity->getDefaultAttributeSetId();

    $attributeSet = $this->attributeSetFactory->create();
    $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

    $customerSetup->addAttribute(
    Customer::ENTITY,
    'referral_code',
    [
    'type' => 'varchar',
    'label' => 'Referral Code',
    'input' => 'text',
    'required' => false,
    'sort_order' => 999,
    'position' => 999,
    'visible' => true,
    'default' => '',
    'user_defined' => true,
    'system' => 0,
    'unique' => true,
    ]
    );

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

    //$this->attributeRepository->save($referralCodeAttribute);
    $this->attribute->save($referralCodeAttribute);







    share|improve this answer























    • No, it doesn't work, I receive this error: "Fatal error: Uncaught TypeError: Argument 1 passed to MagentoEavModelAttributeSetRepositoryInterceptor::save() must implement interface MagentoEavApiDataAttributeSetInterface, instance of MagentoCustomerModelAttribute given, called in /var/www/html/app/code/Ped/Referral/Setup/Patch/Data/AddCustomerReferralCodeAttribute.php on line 138 and defined in /var/www/html/generated/code/Magento/Eav/Model/AttributeSetRepository/Interceptor.php:20"

      – Mirko Rapisarda
      16 hours ago
















    1














    Try this one using MagentoEavApiAttributeSetRepositoryInterface:



    <?php
    /*declare(strict_types=1);*/

    namespace PedReferralSetupPatchData;

    use MagentoCustomerModelCustomer;
    use MagentoCustomerSetupCustomerSetupFactory;
    use MagentoEavApiAttributeRepositoryInterface;
    use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
    use MagentoFrameworkSetupModuleDataSetupInterface;
    use MagentoFrameworkSetupPatchDataPatchInterface;
    use MagentoEavSetupEavSetupFactory;
    //add this AttributeSetRepositoryInterface
    use MagentoEavApiAttributeSetRepositoryInterface;

    class AddCustomerReferralCodeAttribute implements DataPatchInterface
    void
    * @throws MagentoFrameworkExceptionLocalizedException
    * @throws MagentoFrameworkExceptionStateException
    */
    public function apply()

    $this->removeReferralCodeAttribute();
    $this->addReferralCodeAttribute();


    /**
    * Remove referral_code customer attribute
    */
    private function removeReferralCodeAttribute()

    $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
    $eavSetup->removeAttribute(Customer::ENTITY, 'referral_code');


    /**
    * @throws MagentoFrameworkExceptionInputException
    * @throws MagentoFrameworkExceptionLocalizedException
    * @throws MagentoFrameworkExceptionNoSuchEntityException
    */
    private function addReferralCodeAttribute()

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

    $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
    $attributeSetId = $customerEntity->getDefaultAttributeSetId();

    $attributeSet = $this->attributeSetFactory->create();
    $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

    $customerSetup->addAttribute(
    Customer::ENTITY,
    'referral_code',
    [
    'type' => 'varchar',
    'label' => 'Referral Code',
    'input' => 'text',
    'required' => false,
    'sort_order' => 999,
    'position' => 999,
    'visible' => true,
    'default' => '',
    'user_defined' => true,
    'system' => 0,
    'unique' => true,
    ]
    );

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

    //$this->attributeRepository->save($referralCodeAttribute);
    $this->attribute->save($referralCodeAttribute);







    share|improve this answer























    • No, it doesn't work, I receive this error: "Fatal error: Uncaught TypeError: Argument 1 passed to MagentoEavModelAttributeSetRepositoryInterceptor::save() must implement interface MagentoEavApiDataAttributeSetInterface, instance of MagentoCustomerModelAttribute given, called in /var/www/html/app/code/Ped/Referral/Setup/Patch/Data/AddCustomerReferralCodeAttribute.php on line 138 and defined in /var/www/html/generated/code/Magento/Eav/Model/AttributeSetRepository/Interceptor.php:20"

      – Mirko Rapisarda
      16 hours ago














    1












    1








    1







    Try this one using MagentoEavApiAttributeSetRepositoryInterface:



    <?php
    /*declare(strict_types=1);*/

    namespace PedReferralSetupPatchData;

    use MagentoCustomerModelCustomer;
    use MagentoCustomerSetupCustomerSetupFactory;
    use MagentoEavApiAttributeRepositoryInterface;
    use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
    use MagentoFrameworkSetupModuleDataSetupInterface;
    use MagentoFrameworkSetupPatchDataPatchInterface;
    use MagentoEavSetupEavSetupFactory;
    //add this AttributeSetRepositoryInterface
    use MagentoEavApiAttributeSetRepositoryInterface;

    class AddCustomerReferralCodeAttribute implements DataPatchInterface
    void
    * @throws MagentoFrameworkExceptionLocalizedException
    * @throws MagentoFrameworkExceptionStateException
    */
    public function apply()

    $this->removeReferralCodeAttribute();
    $this->addReferralCodeAttribute();


    /**
    * Remove referral_code customer attribute
    */
    private function removeReferralCodeAttribute()

    $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
    $eavSetup->removeAttribute(Customer::ENTITY, 'referral_code');


    /**
    * @throws MagentoFrameworkExceptionInputException
    * @throws MagentoFrameworkExceptionLocalizedException
    * @throws MagentoFrameworkExceptionNoSuchEntityException
    */
    private function addReferralCodeAttribute()

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

    $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
    $attributeSetId = $customerEntity->getDefaultAttributeSetId();

    $attributeSet = $this->attributeSetFactory->create();
    $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

    $customerSetup->addAttribute(
    Customer::ENTITY,
    'referral_code',
    [
    'type' => 'varchar',
    'label' => 'Referral Code',
    'input' => 'text',
    'required' => false,
    'sort_order' => 999,
    'position' => 999,
    'visible' => true,
    'default' => '',
    'user_defined' => true,
    'system' => 0,
    'unique' => true,
    ]
    );

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

    //$this->attributeRepository->save($referralCodeAttribute);
    $this->attribute->save($referralCodeAttribute);







    share|improve this answer













    Try this one using MagentoEavApiAttributeSetRepositoryInterface:



    <?php
    /*declare(strict_types=1);*/

    namespace PedReferralSetupPatchData;

    use MagentoCustomerModelCustomer;
    use MagentoCustomerSetupCustomerSetupFactory;
    use MagentoEavApiAttributeRepositoryInterface;
    use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
    use MagentoFrameworkSetupModuleDataSetupInterface;
    use MagentoFrameworkSetupPatchDataPatchInterface;
    use MagentoEavSetupEavSetupFactory;
    //add this AttributeSetRepositoryInterface
    use MagentoEavApiAttributeSetRepositoryInterface;

    class AddCustomerReferralCodeAttribute implements DataPatchInterface
    void
    * @throws MagentoFrameworkExceptionLocalizedException
    * @throws MagentoFrameworkExceptionStateException
    */
    public function apply()

    $this->removeReferralCodeAttribute();
    $this->addReferralCodeAttribute();


    /**
    * Remove referral_code customer attribute
    */
    private function removeReferralCodeAttribute()

    $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
    $eavSetup->removeAttribute(Customer::ENTITY, 'referral_code');


    /**
    * @throws MagentoFrameworkExceptionInputException
    * @throws MagentoFrameworkExceptionLocalizedException
    * @throws MagentoFrameworkExceptionNoSuchEntityException
    */
    private function addReferralCodeAttribute()

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

    $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
    $attributeSetId = $customerEntity->getDefaultAttributeSetId();

    $attributeSet = $this->attributeSetFactory->create();
    $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

    $customerSetup->addAttribute(
    Customer::ENTITY,
    'referral_code',
    [
    'type' => 'varchar',
    'label' => 'Referral Code',
    'input' => 'text',
    'required' => false,
    'sort_order' => 999,
    'position' => 999,
    'visible' => true,
    'default' => '',
    'user_defined' => true,
    'system' => 0,
    'unique' => true,
    ]
    );

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

    //$this->attributeRepository->save($referralCodeAttribute);
    $this->attribute->save($referralCodeAttribute);








    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 17 hours ago









    magefmsmagefms

    1,8321425




    1,8321425












    • No, it doesn't work, I receive this error: "Fatal error: Uncaught TypeError: Argument 1 passed to MagentoEavModelAttributeSetRepositoryInterceptor::save() must implement interface MagentoEavApiDataAttributeSetInterface, instance of MagentoCustomerModelAttribute given, called in /var/www/html/app/code/Ped/Referral/Setup/Patch/Data/AddCustomerReferralCodeAttribute.php on line 138 and defined in /var/www/html/generated/code/Magento/Eav/Model/AttributeSetRepository/Interceptor.php:20"

      – Mirko Rapisarda
      16 hours ago


















    • No, it doesn't work, I receive this error: "Fatal error: Uncaught TypeError: Argument 1 passed to MagentoEavModelAttributeSetRepositoryInterceptor::save() must implement interface MagentoEavApiDataAttributeSetInterface, instance of MagentoCustomerModelAttribute given, called in /var/www/html/app/code/Ped/Referral/Setup/Patch/Data/AddCustomerReferralCodeAttribute.php on line 138 and defined in /var/www/html/generated/code/Magento/Eav/Model/AttributeSetRepository/Interceptor.php:20"

      – Mirko Rapisarda
      16 hours ago

















    No, it doesn't work, I receive this error: "Fatal error: Uncaught TypeError: Argument 1 passed to MagentoEavModelAttributeSetRepositoryInterceptor::save() must implement interface MagentoEavApiDataAttributeSetInterface, instance of MagentoCustomerModelAttribute given, called in /var/www/html/app/code/Ped/Referral/Setup/Patch/Data/AddCustomerReferralCodeAttribute.php on line 138 and defined in /var/www/html/generated/code/Magento/Eav/Model/AttributeSetRepository/Interceptor.php:20"

    – Mirko Rapisarda
    16 hours ago






    No, it doesn't work, I receive this error: "Fatal error: Uncaught TypeError: Argument 1 passed to MagentoEavModelAttributeSetRepositoryInterceptor::save() must implement interface MagentoEavApiDataAttributeSetInterface, instance of MagentoCustomerModelAttribute given, called in /var/www/html/app/code/Ped/Referral/Setup/Patch/Data/AddCustomerReferralCodeAttribute.php on line 138 and defined in /var/www/html/generated/code/Magento/Eav/Model/AttributeSetRepository/Interceptor.php:20"

    – Mirko Rapisarda
    16 hours ago














    1














    I found the solution by dump the ResourceModel classname used by the save() method that was deprecated in favor of service contract. The resource model that I should used is MagentoCustomerModelResourceModelAttribute. Here the complete code:



    <?php 
    namespace PedReferralSetupPatchData;

    use MagentoCustomerModelCustomer;
    use MagentoCustomerModelResourceModelAttribute as AttributeResourceModel;
    use MagentoCustomerSetupCustomerSetupFactory;
    use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
    use MagentoEavSetupEavSetupFactory;
    use MagentoFrameworkSetupModuleDataSetupInterface;
    use MagentoFrameworkSetupPatchDataPatchInterface;

    class AddCustomerReferralCodeAttribute implements DataPatchInterface

    private const REFERRAL_CODE_FIELD_NAME = 'referral_code';

    /**
    * @var ModuleDataSetupInterface
    */
    private $moduleDataSetup;

    /**
    * @var CustomerSetupFactory
    */
    private $customerSetupFactory;

    /**
    * @var AttributeSetFactory
    */
    private $attributeSetFactory;

    /**
    * @var EavSetupFactory
    */
    private $eavSetupFactory;

    /**
    * @var AttributeResourceModel
    */
    private $attributeResourceModel;

    public function __construct(
    ModuleDataSetupInterface $moduleDataSetup,
    CustomerSetupFactory $customerSetupFactory,
    AttributeSetFactory $attributeSetFactory,
    EavSetupFactory $eavSetupFactory,
    AttributeResourceModel $attributeResourceModel
    )
    $this->moduleDataSetup = $moduleDataSetup;
    $this->customerSetupFactory = $customerSetupFactory;
    $this->attributeSetFactory = $attributeSetFactory;
    $this->eavSetupFactory = $eavSetupFactory;
    $this->attributeResourceModel = $attributeResourceModel;


    /**
    * @inheritdoc
    */
    public static function getDependencies()

    return [];


    /**
    * @inheritdoc
    */
    public function getAliases()

    return [];


    /**
    * @inheritdoc
    * @throws MagentoFrameworkExceptionLocalizedException
    */
    public function apply()

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

    $customerEntity = $customerSetup->getEavConfig()->getEntityType(Customer::ENTITY);
    $attributeSetId = $customerEntity->getDefaultAttributeSetId();

    $attributeSet = $this->attributeSetFactory->create();
    $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

    $customerSetup->addAttribute(
    Customer::ENTITY,
    static::REFERRAL_CODE_FIELD_NAME,
    [
    'type' => 'varchar',
    'label' => 'Referral Code',
    'input' => 'text',
    'required' => false,
    'sort_order' => 999,
    'position' => 999,
    'visible' => true,
    'default' => '',
    'user_defined' => true,
    'system' => 0,
    'unique' => true,
    ]
    );

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

    $this->attributeResourceModel->save($referralCodeAttribute);








    share|improve this answer










    New contributor




    Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.
























      1














      I found the solution by dump the ResourceModel classname used by the save() method that was deprecated in favor of service contract. The resource model that I should used is MagentoCustomerModelResourceModelAttribute. Here the complete code:



      <?php 
      namespace PedReferralSetupPatchData;

      use MagentoCustomerModelCustomer;
      use MagentoCustomerModelResourceModelAttribute as AttributeResourceModel;
      use MagentoCustomerSetupCustomerSetupFactory;
      use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
      use MagentoEavSetupEavSetupFactory;
      use MagentoFrameworkSetupModuleDataSetupInterface;
      use MagentoFrameworkSetupPatchDataPatchInterface;

      class AddCustomerReferralCodeAttribute implements DataPatchInterface

      private const REFERRAL_CODE_FIELD_NAME = 'referral_code';

      /**
      * @var ModuleDataSetupInterface
      */
      private $moduleDataSetup;

      /**
      * @var CustomerSetupFactory
      */
      private $customerSetupFactory;

      /**
      * @var AttributeSetFactory
      */
      private $attributeSetFactory;

      /**
      * @var EavSetupFactory
      */
      private $eavSetupFactory;

      /**
      * @var AttributeResourceModel
      */
      private $attributeResourceModel;

      public function __construct(
      ModuleDataSetupInterface $moduleDataSetup,
      CustomerSetupFactory $customerSetupFactory,
      AttributeSetFactory $attributeSetFactory,
      EavSetupFactory $eavSetupFactory,
      AttributeResourceModel $attributeResourceModel
      )
      $this->moduleDataSetup = $moduleDataSetup;
      $this->customerSetupFactory = $customerSetupFactory;
      $this->attributeSetFactory = $attributeSetFactory;
      $this->eavSetupFactory = $eavSetupFactory;
      $this->attributeResourceModel = $attributeResourceModel;


      /**
      * @inheritdoc
      */
      public static function getDependencies()

      return [];


      /**
      * @inheritdoc
      */
      public function getAliases()

      return [];


      /**
      * @inheritdoc
      * @throws MagentoFrameworkExceptionLocalizedException
      */
      public function apply()

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

      $customerEntity = $customerSetup->getEavConfig()->getEntityType(Customer::ENTITY);
      $attributeSetId = $customerEntity->getDefaultAttributeSetId();

      $attributeSet = $this->attributeSetFactory->create();
      $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

      $customerSetup->addAttribute(
      Customer::ENTITY,
      static::REFERRAL_CODE_FIELD_NAME,
      [
      'type' => 'varchar',
      'label' => 'Referral Code',
      'input' => 'text',
      'required' => false,
      'sort_order' => 999,
      'position' => 999,
      'visible' => true,
      'default' => '',
      'user_defined' => true,
      'system' => 0,
      'unique' => true,
      ]
      );

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

      $this->attributeResourceModel->save($referralCodeAttribute);








      share|improve this answer










      New contributor




      Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















        1












        1








        1







        I found the solution by dump the ResourceModel classname used by the save() method that was deprecated in favor of service contract. The resource model that I should used is MagentoCustomerModelResourceModelAttribute. Here the complete code:



        <?php 
        namespace PedReferralSetupPatchData;

        use MagentoCustomerModelCustomer;
        use MagentoCustomerModelResourceModelAttribute as AttributeResourceModel;
        use MagentoCustomerSetupCustomerSetupFactory;
        use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
        use MagentoEavSetupEavSetupFactory;
        use MagentoFrameworkSetupModuleDataSetupInterface;
        use MagentoFrameworkSetupPatchDataPatchInterface;

        class AddCustomerReferralCodeAttribute implements DataPatchInterface

        private const REFERRAL_CODE_FIELD_NAME = 'referral_code';

        /**
        * @var ModuleDataSetupInterface
        */
        private $moduleDataSetup;

        /**
        * @var CustomerSetupFactory
        */
        private $customerSetupFactory;

        /**
        * @var AttributeSetFactory
        */
        private $attributeSetFactory;

        /**
        * @var EavSetupFactory
        */
        private $eavSetupFactory;

        /**
        * @var AttributeResourceModel
        */
        private $attributeResourceModel;

        public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        CustomerSetupFactory $customerSetupFactory,
        AttributeSetFactory $attributeSetFactory,
        EavSetupFactory $eavSetupFactory,
        AttributeResourceModel $attributeResourceModel
        )
        $this->moduleDataSetup = $moduleDataSetup;
        $this->customerSetupFactory = $customerSetupFactory;
        $this->attributeSetFactory = $attributeSetFactory;
        $this->eavSetupFactory = $eavSetupFactory;
        $this->attributeResourceModel = $attributeResourceModel;


        /**
        * @inheritdoc
        */
        public static function getDependencies()

        return [];


        /**
        * @inheritdoc
        */
        public function getAliases()

        return [];


        /**
        * @inheritdoc
        * @throws MagentoFrameworkExceptionLocalizedException
        */
        public function apply()

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

        $customerEntity = $customerSetup->getEavConfig()->getEntityType(Customer::ENTITY);
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

        $attributeSet = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

        $customerSetup->addAttribute(
        Customer::ENTITY,
        static::REFERRAL_CODE_FIELD_NAME,
        [
        'type' => 'varchar',
        'label' => 'Referral Code',
        'input' => 'text',
        'required' => false,
        'sort_order' => 999,
        'position' => 999,
        'visible' => true,
        'default' => '',
        'user_defined' => true,
        'system' => 0,
        'unique' => true,
        ]
        );

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

        $this->attributeResourceModel->save($referralCodeAttribute);








        share|improve this answer










        New contributor




        Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.










        I found the solution by dump the ResourceModel classname used by the save() method that was deprecated in favor of service contract. The resource model that I should used is MagentoCustomerModelResourceModelAttribute. Here the complete code:



        <?php 
        namespace PedReferralSetupPatchData;

        use MagentoCustomerModelCustomer;
        use MagentoCustomerModelResourceModelAttribute as AttributeResourceModel;
        use MagentoCustomerSetupCustomerSetupFactory;
        use MagentoEavModelEntityAttributeSetFactory as AttributeSetFactory;
        use MagentoEavSetupEavSetupFactory;
        use MagentoFrameworkSetupModuleDataSetupInterface;
        use MagentoFrameworkSetupPatchDataPatchInterface;

        class AddCustomerReferralCodeAttribute implements DataPatchInterface

        private const REFERRAL_CODE_FIELD_NAME = 'referral_code';

        /**
        * @var ModuleDataSetupInterface
        */
        private $moduleDataSetup;

        /**
        * @var CustomerSetupFactory
        */
        private $customerSetupFactory;

        /**
        * @var AttributeSetFactory
        */
        private $attributeSetFactory;

        /**
        * @var EavSetupFactory
        */
        private $eavSetupFactory;

        /**
        * @var AttributeResourceModel
        */
        private $attributeResourceModel;

        public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        CustomerSetupFactory $customerSetupFactory,
        AttributeSetFactory $attributeSetFactory,
        EavSetupFactory $eavSetupFactory,
        AttributeResourceModel $attributeResourceModel
        )
        $this->moduleDataSetup = $moduleDataSetup;
        $this->customerSetupFactory = $customerSetupFactory;
        $this->attributeSetFactory = $attributeSetFactory;
        $this->eavSetupFactory = $eavSetupFactory;
        $this->attributeResourceModel = $attributeResourceModel;


        /**
        * @inheritdoc
        */
        public static function getDependencies()

        return [];


        /**
        * @inheritdoc
        */
        public function getAliases()

        return [];


        /**
        * @inheritdoc
        * @throws MagentoFrameworkExceptionLocalizedException
        */
        public function apply()

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

        $customerEntity = $customerSetup->getEavConfig()->getEntityType(Customer::ENTITY);
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

        $attributeSet = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

        $customerSetup->addAttribute(
        Customer::ENTITY,
        static::REFERRAL_CODE_FIELD_NAME,
        [
        'type' => 'varchar',
        'label' => 'Referral Code',
        'input' => 'text',
        'required' => false,
        'sort_order' => 999,
        'position' => 999,
        'visible' => true,
        'default' => '',
        'user_defined' => true,
        'system' => 0,
        'unique' => true,
        ]
        );

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

        $this->attributeResourceModel->save($referralCodeAttribute);









        share|improve this answer










        New contributor




        Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        share|improve this answer



        share|improve this answer








        edited 14 hours ago





















        New contributor




        Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        answered 16 hours ago









        Mirko RapisardaMirko Rapisarda

        264




        264




        New contributor




        Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.





        New contributor





        Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






        Mirko Rapisarda is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.




















            Mirko Rapisarda is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            Mirko Rapisarda is a new contributor. Be nice, and check out our Code of Conduct.












            Mirko Rapisarda is a new contributor. Be nice, and check out our Code of Conduct.











            Mirko Rapisarda is a new contributor. Be nice, and check out our Code of Conduct.














            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f266481%2fmagento-2-3-add-custom-customer-entity-attribute-with-service-contract%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Sum ergo cogito? 1 nng

            三茅街道4182Guuntc Dn precexpngmageondP