Need to custom attribute in customer info backend programatically for magento 2 Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?main.CRITICAL: Plugin class doesn't existMagento2 add custom address attributeMagento 2: How to override newsletter Subscriber modelMagento 2.1 Create a filter in the product grid by new attributeSet default value for attribute in Setup Script in Magento 2Magento offline custom Payment method with drop down listHow to solve Front controller reached 100 router match iterations in magento2Magento 2 How to remove price filter from category if module is enable?Magento 2 How to disable price from orders, customer account and order view if custom module is enabled?Magento 2 - Best way to check if the current category is child

Monty Hall Problem-Probability Paradox

A proverb that is used to imply that you have unexpectedly faced a big problem

What would you call this weird metallic apparatus that allows you to lift people?

How does light 'choose' between wave and particle behaviour?

Weaponising the Grasp-at-a-Distance spell

Why weren't discrete x86 CPUs ever used in game hardware?

Why does electrolysis of aqueous concentrated sodium bromide produce bromine at the anode?

Random body shuffle every night—can we still function?

How can I save and copy a screenhot at the same time?

What does 丫 mean? 丫是什么意思?

Should a wizard buy fine inks every time he want to copy spells into his spellbook?

I got rid of Mac OSX and replaced it with linux but now I can't change it back to OSX or windows

Is openssl rand command cryptographically secure?

What order were files/directories output in dir?

Mounting TV on a weird wall that has some material between the drywall and stud

what is the log of the PDF for a Normal Distribution?

Co-worker has annoying ringtone

Wrapping text with mathclap

What initially awakened the Balrog?

Why complex landing gears are used instead of simple,reliability and light weight muscle wire or shape memory alloys?

How can I prevent/balance waiting and turtling as a response to cooldown mechanics

Central Vacuuming: Is it worth it, and how does it compare to normal vacuuming?

Flight departed from the gate 5 min before scheduled departure time. Refund options

Did Mueller's report provide an evidentiary basis for the claim of Russian govt election interference via social media?



Need to custom attribute in customer info backend programatically for magento 2



Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?main.CRITICAL: Plugin class doesn't existMagento2 add custom address attributeMagento 2: How to override newsletter Subscriber modelMagento 2.1 Create a filter in the product grid by new attributeSet default value for attribute in Setup Script in Magento 2Magento offline custom Payment method with drop down listHow to solve Front controller reached 100 router match iterations in magento2Magento 2 How to remove price filter from category if module is enable?Magento 2 How to disable price from orders, customer account and order view if custom module is enabled?Magento 2 - Best way to check if the current category is child



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















enter image description here



I need to add custom attribute same as image in backend in customer information to individual customer. If admin select category customer able to show only selected category.



namespace MetizsoftAllowcustomerModelConfigSource;

use MagentoFrameworkOptionArrayInterface;

class Category implements ArrayInterface

protected $_categoryHelper;
protected $categoryRepository;
protected $categoryList;

public function __construct(
MagentoCatalogHelperCategory $catalogCategory,
MagentoCatalogModelCategoryRepository $categoryRepository
)

$this->_categoryHelper = $catalogCategory;
$this->categoryRepository = $categoryRepository;


/*
* Return categories helper
*/

public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)

return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);


/*
* Option getter
* @return array
*/
public function toOptionArray()



$arr = $this->toArray();
$ret = [];

foreach ($arr as $key => $value)


$ret[] = [
'value' => $key,
'label' => $value
];


return $ret;


/*
* Get options in "key-value" format
* @return array
*/
public function toArray()


$categories = $this->getStoreCategories(true,false,true);
$categoryList = $this->renderCategories($categories);
return $categoryList;


public function renderCategories($_categories)

foreach ($_categories as $category)
$i = 0;
$this->categoryList[$category->getEntityId()] = __($category->getName()); // Main categories
$list = $this->renderSubCat($category,$i);


return $this->categoryList;


public function renderSubCat($cat,$j)

$categoryObj = $this->categoryRepository->get($cat->getId());

$level = $categoryObj->getLevel();
$arrow = str_repeat("---", $level-1);
$subcategories = $categoryObj->getChildrenCategories();

foreach($subcategories as $subcategory)
$this->categoryList[$subcategory->getEntityId()] = __($arrow.$subcategory->getName());

if($subcategory->hasChildren())

$this->renderSubCat($subcategory,$j);




return $this->categoryList;











share|improve this question



















  • 1





    What you have tried so far. Please post those details. Also, kindly don't post fill requirement on the question. At least give some try your self

    – Amit Bera
    2 days ago











  • @Amit Bera, i have created file for select category like image but in not work look above code

    – jay
    2 days ago

















1















enter image description here



I need to add custom attribute same as image in backend in customer information to individual customer. If admin select category customer able to show only selected category.



namespace MetizsoftAllowcustomerModelConfigSource;

use MagentoFrameworkOptionArrayInterface;

class Category implements ArrayInterface

protected $_categoryHelper;
protected $categoryRepository;
protected $categoryList;

public function __construct(
MagentoCatalogHelperCategory $catalogCategory,
MagentoCatalogModelCategoryRepository $categoryRepository
)

$this->_categoryHelper = $catalogCategory;
$this->categoryRepository = $categoryRepository;


/*
* Return categories helper
*/

public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)

return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);


/*
* Option getter
* @return array
*/
public function toOptionArray()



$arr = $this->toArray();
$ret = [];

foreach ($arr as $key => $value)


$ret[] = [
'value' => $key,
'label' => $value
];


return $ret;


/*
* Get options in "key-value" format
* @return array
*/
public function toArray()


$categories = $this->getStoreCategories(true,false,true);
$categoryList = $this->renderCategories($categories);
return $categoryList;


public function renderCategories($_categories)

foreach ($_categories as $category)
$i = 0;
$this->categoryList[$category->getEntityId()] = __($category->getName()); // Main categories
$list = $this->renderSubCat($category,$i);


return $this->categoryList;


public function renderSubCat($cat,$j)

$categoryObj = $this->categoryRepository->get($cat->getId());

$level = $categoryObj->getLevel();
$arrow = str_repeat("---", $level-1);
$subcategories = $categoryObj->getChildrenCategories();

foreach($subcategories as $subcategory)
$this->categoryList[$subcategory->getEntityId()] = __($arrow.$subcategory->getName());

if($subcategory->hasChildren())

$this->renderSubCat($subcategory,$j);




return $this->categoryList;











share|improve this question



















  • 1





    What you have tried so far. Please post those details. Also, kindly don't post fill requirement on the question. At least give some try your self

    – Amit Bera
    2 days ago











  • @Amit Bera, i have created file for select category like image but in not work look above code

    – jay
    2 days ago













1












1








1








enter image description here



I need to add custom attribute same as image in backend in customer information to individual customer. If admin select category customer able to show only selected category.



namespace MetizsoftAllowcustomerModelConfigSource;

use MagentoFrameworkOptionArrayInterface;

class Category implements ArrayInterface

protected $_categoryHelper;
protected $categoryRepository;
protected $categoryList;

public function __construct(
MagentoCatalogHelperCategory $catalogCategory,
MagentoCatalogModelCategoryRepository $categoryRepository
)

$this->_categoryHelper = $catalogCategory;
$this->categoryRepository = $categoryRepository;


/*
* Return categories helper
*/

public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)

return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);


/*
* Option getter
* @return array
*/
public function toOptionArray()



$arr = $this->toArray();
$ret = [];

foreach ($arr as $key => $value)


$ret[] = [
'value' => $key,
'label' => $value
];


return $ret;


/*
* Get options in "key-value" format
* @return array
*/
public function toArray()


$categories = $this->getStoreCategories(true,false,true);
$categoryList = $this->renderCategories($categories);
return $categoryList;


public function renderCategories($_categories)

foreach ($_categories as $category)
$i = 0;
$this->categoryList[$category->getEntityId()] = __($category->getName()); // Main categories
$list = $this->renderSubCat($category,$i);


return $this->categoryList;


public function renderSubCat($cat,$j)

$categoryObj = $this->categoryRepository->get($cat->getId());

$level = $categoryObj->getLevel();
$arrow = str_repeat("---", $level-1);
$subcategories = $categoryObj->getChildrenCategories();

foreach($subcategories as $subcategory)
$this->categoryList[$subcategory->getEntityId()] = __($arrow.$subcategory->getName());

if($subcategory->hasChildren())

$this->renderSubCat($subcategory,$j);




return $this->categoryList;











share|improve this question
















enter image description here



I need to add custom attribute same as image in backend in customer information to individual customer. If admin select category customer able to show only selected category.



namespace MetizsoftAllowcustomerModelConfigSource;

use MagentoFrameworkOptionArrayInterface;

class Category implements ArrayInterface

protected $_categoryHelper;
protected $categoryRepository;
protected $categoryList;

public function __construct(
MagentoCatalogHelperCategory $catalogCategory,
MagentoCatalogModelCategoryRepository $categoryRepository
)

$this->_categoryHelper = $catalogCategory;
$this->categoryRepository = $categoryRepository;


/*
* Return categories helper
*/

public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)

return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);


/*
* Option getter
* @return array
*/
public function toOptionArray()



$arr = $this->toArray();
$ret = [];

foreach ($arr as $key => $value)


$ret[] = [
'value' => $key,
'label' => $value
];


return $ret;


/*
* Get options in "key-value" format
* @return array
*/
public function toArray()


$categories = $this->getStoreCategories(true,false,true);
$categoryList = $this->renderCategories($categories);
return $categoryList;


public function renderCategories($_categories)

foreach ($_categories as $category)
$i = 0;
$this->categoryList[$category->getEntityId()] = __($category->getName()); // Main categories
$list = $this->renderSubCat($category,$i);


return $this->categoryList;


public function renderSubCat($cat,$j)

$categoryObj = $this->categoryRepository->get($cat->getId());

$level = $categoryObj->getLevel();
$arrow = str_repeat("---", $level-1);
$subcategories = $categoryObj->getChildrenCategories();

foreach($subcategories as $subcategory)
$this->categoryList[$subcategory->getEntityId()] = __($arrow.$subcategory->getName());

if($subcategory->hasChildren())

$this->renderSubCat($subcategory,$j);




return $this->categoryList;








magento2






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 2 days ago









Amit Bera

60.2k1678178




60.2k1678178










asked 2 days ago









jayjay

227




227







  • 1





    What you have tried so far. Please post those details. Also, kindly don't post fill requirement on the question. At least give some try your self

    – Amit Bera
    2 days ago











  • @Amit Bera, i have created file for select category like image but in not work look above code

    – jay
    2 days ago












  • 1





    What you have tried so far. Please post those details. Also, kindly don't post fill requirement on the question. At least give some try your self

    – Amit Bera
    2 days ago











  • @Amit Bera, i have created file for select category like image but in not work look above code

    – jay
    2 days ago







1




1





What you have tried so far. Please post those details. Also, kindly don't post fill requirement on the question. At least give some try your self

– Amit Bera
2 days ago





What you have tried so far. Please post those details. Also, kindly don't post fill requirement on the question. At least give some try your self

– Amit Bera
2 days ago













@Amit Bera, i have created file for select category like image but in not work look above code

– jay
2 days ago





@Amit Bera, i have created file for select category like image but in not work look above code

– jay
2 days ago










1 Answer
1






active

oldest

votes


















0














You cannot use MagentoFrameworkOptionArrayInterface type for as Source Model of a multi-select EAV attribute.




MetizsoftAllowcustomerModelCustomerAttributeSourceHideCategory




Should be extended MagentoEavModelEntityAttributeSourceAbstractSource or your class will be the interface of MagentoFrameworkDataOptionSourceInterface.



InstallData.php code attribute create code must have source model and backend model that



 $customerSetup->addAttribute(MagentoCustomerModelCustomer::ENTITY, 'hide_category', [
'type' => 'varchar',
'label' => 'Hide Categories',
'input' => 'multiselect',
'source' => 'MetizsoftAllowcustomerModelCustomerAttributeSourceHideCategory',
'required' => false,
'visible' => true,
'position' => 333,
'system' => false,
'backend' => 'MagentoEavModelEntityAttributeBackendArrayBackend'
]);


Source Model Class code



<?php


namespace MetizsoftAllowcustomerModelCustomerAttributeSource;

class HideCategory extends MagentoEavModelEntityAttributeSourceAbstractSource

/**
* @var MagentoCatalogModelResourceModelCategoryCollectionFactory
*/
private $collectionFactory;
/**
* @var MagentoCatalogHelperCategory
*/
private $catalogCategory;

public function __construct(
MagentoCatalogHelperCategory $catalogCategory,
MagentoCatalogModelResourceModelCategoryCollectionFactory $collectionFactory
)

$this->catalogCategory = $catalogCategory;
$this->collectionFactory = $collectionFactory;

/**
* getAllOptions
*
* @return array
*/
public function getAllOptions()

$options = $this->optionDataInArray();
array_unshift($options, ['value' => '', 'label' => __('Please Selec')]);
$this->_options = $options;

return $options;

public function optionDataInArray(): array

$categories = $this->catalogCategory->getStoreCategories(true, false, true) ;
$options = [];
foreach ($categories as $category)
$options[] = ['value' => $category->getId(), 'label' => $category->getName()];
$options =$this->secondLevelCategories($category->getId(),$category->getName(),$options);

return $options;

private function secondLevelCategories($parentCatId,$parentCatName,$options)


$categoryCollection = $this->collectionFactory->create();
$categoryCollection->addAttributeToSelect(
'url_key'
)->addAttributeToSelect(
'name'
)->addAttributeToSelect(
'all_children'
)->addAttributeToSelect(
'is_anchor'
)->addAttributeToFilter(
'parent_id',
$parentCatId
)->addAttributeToFilter(
'is_active',
1
)->setOrder(
'position',
MagentoFrameworkDBSelect::SQL_ASC
)->joinUrlRewrite();

foreach($categoryCollection as $category)
$options[] = ['value' => $category->getId(), 'label' => $parentCatName.'-->'. $category->getName()];

return $options;




Also, your module must have below files & folders structure.



enter image description here



InstallData.php full code



<?php

namespace MetizsoftAllowcustomerSetup;

use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoCustomerModelCustomer;
use MagentoCustomerSetupCustomerSetupFactory;

class InstallData implements InstallDataInterface


private $customerSetupFactory;

/**
* Constructor
*
* @param MagentoCustomerSetupCustomerSetupFactory $customerSetupFactory
*/
public function __construct(
CustomerSetupFactory $customerSetupFactory
)
$this->customerSetupFactory = $customerSetupFactory;


/**
* @inheritdoc
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
)
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

$customerSetup->addAttribute(MagentoCustomerModelCustomer::ENTITY, 'hide_category', [
'type' => 'varchar',
'label' => 'Hide Categories',
'input' => 'multiselect',
'source' => 'MetizsoftAllowcustomerModelCustomerAttributeSourceHideCategory',
'required' => false,
'visible' => true,
'position' => 333,
'system' => false,
'backend' => 'MagentoEavModelEntityAttributeBackendArrayBackend'
]);

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




Output on magento 2 sample data Instance
enter image description here






share|improve this answer

























  • hello why we used extension_attributes.xml i am not understand about it can you able to give that file code

    – jay
    2 days ago












  • extension attribute need to enable your attribute for API

    – Amit Bera
    yesterday











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
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f270615%2fneed-to-custom-attribute-in-customer-info-backend-programatically-for-magento-2%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














You cannot use MagentoFrameworkOptionArrayInterface type for as Source Model of a multi-select EAV attribute.




MetizsoftAllowcustomerModelCustomerAttributeSourceHideCategory




Should be extended MagentoEavModelEntityAttributeSourceAbstractSource or your class will be the interface of MagentoFrameworkDataOptionSourceInterface.



InstallData.php code attribute create code must have source model and backend model that



 $customerSetup->addAttribute(MagentoCustomerModelCustomer::ENTITY, 'hide_category', [
'type' => 'varchar',
'label' => 'Hide Categories',
'input' => 'multiselect',
'source' => 'MetizsoftAllowcustomerModelCustomerAttributeSourceHideCategory',
'required' => false,
'visible' => true,
'position' => 333,
'system' => false,
'backend' => 'MagentoEavModelEntityAttributeBackendArrayBackend'
]);


Source Model Class code



<?php


namespace MetizsoftAllowcustomerModelCustomerAttributeSource;

class HideCategory extends MagentoEavModelEntityAttributeSourceAbstractSource

/**
* @var MagentoCatalogModelResourceModelCategoryCollectionFactory
*/
private $collectionFactory;
/**
* @var MagentoCatalogHelperCategory
*/
private $catalogCategory;

public function __construct(
MagentoCatalogHelperCategory $catalogCategory,
MagentoCatalogModelResourceModelCategoryCollectionFactory $collectionFactory
)

$this->catalogCategory = $catalogCategory;
$this->collectionFactory = $collectionFactory;

/**
* getAllOptions
*
* @return array
*/
public function getAllOptions()

$options = $this->optionDataInArray();
array_unshift($options, ['value' => '', 'label' => __('Please Selec')]);
$this->_options = $options;

return $options;

public function optionDataInArray(): array

$categories = $this->catalogCategory->getStoreCategories(true, false, true) ;
$options = [];
foreach ($categories as $category)
$options[] = ['value' => $category->getId(), 'label' => $category->getName()];
$options =$this->secondLevelCategories($category->getId(),$category->getName(),$options);

return $options;

private function secondLevelCategories($parentCatId,$parentCatName,$options)


$categoryCollection = $this->collectionFactory->create();
$categoryCollection->addAttributeToSelect(
'url_key'
)->addAttributeToSelect(
'name'
)->addAttributeToSelect(
'all_children'
)->addAttributeToSelect(
'is_anchor'
)->addAttributeToFilter(
'parent_id',
$parentCatId
)->addAttributeToFilter(
'is_active',
1
)->setOrder(
'position',
MagentoFrameworkDBSelect::SQL_ASC
)->joinUrlRewrite();

foreach($categoryCollection as $category)
$options[] = ['value' => $category->getId(), 'label' => $parentCatName.'-->'. $category->getName()];

return $options;




Also, your module must have below files & folders structure.



enter image description here



InstallData.php full code



<?php

namespace MetizsoftAllowcustomerSetup;

use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoCustomerModelCustomer;
use MagentoCustomerSetupCustomerSetupFactory;

class InstallData implements InstallDataInterface


private $customerSetupFactory;

/**
* Constructor
*
* @param MagentoCustomerSetupCustomerSetupFactory $customerSetupFactory
*/
public function __construct(
CustomerSetupFactory $customerSetupFactory
)
$this->customerSetupFactory = $customerSetupFactory;


/**
* @inheritdoc
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
)
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

$customerSetup->addAttribute(MagentoCustomerModelCustomer::ENTITY, 'hide_category', [
'type' => 'varchar',
'label' => 'Hide Categories',
'input' => 'multiselect',
'source' => 'MetizsoftAllowcustomerModelCustomerAttributeSourceHideCategory',
'required' => false,
'visible' => true,
'position' => 333,
'system' => false,
'backend' => 'MagentoEavModelEntityAttributeBackendArrayBackend'
]);

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




Output on magento 2 sample data Instance
enter image description here






share|improve this answer

























  • hello why we used extension_attributes.xml i am not understand about it can you able to give that file code

    – jay
    2 days ago












  • extension attribute need to enable your attribute for API

    – Amit Bera
    yesterday















0














You cannot use MagentoFrameworkOptionArrayInterface type for as Source Model of a multi-select EAV attribute.




MetizsoftAllowcustomerModelCustomerAttributeSourceHideCategory




Should be extended MagentoEavModelEntityAttributeSourceAbstractSource or your class will be the interface of MagentoFrameworkDataOptionSourceInterface.



InstallData.php code attribute create code must have source model and backend model that



 $customerSetup->addAttribute(MagentoCustomerModelCustomer::ENTITY, 'hide_category', [
'type' => 'varchar',
'label' => 'Hide Categories',
'input' => 'multiselect',
'source' => 'MetizsoftAllowcustomerModelCustomerAttributeSourceHideCategory',
'required' => false,
'visible' => true,
'position' => 333,
'system' => false,
'backend' => 'MagentoEavModelEntityAttributeBackendArrayBackend'
]);


Source Model Class code



<?php


namespace MetizsoftAllowcustomerModelCustomerAttributeSource;

class HideCategory extends MagentoEavModelEntityAttributeSourceAbstractSource

/**
* @var MagentoCatalogModelResourceModelCategoryCollectionFactory
*/
private $collectionFactory;
/**
* @var MagentoCatalogHelperCategory
*/
private $catalogCategory;

public function __construct(
MagentoCatalogHelperCategory $catalogCategory,
MagentoCatalogModelResourceModelCategoryCollectionFactory $collectionFactory
)

$this->catalogCategory = $catalogCategory;
$this->collectionFactory = $collectionFactory;

/**
* getAllOptions
*
* @return array
*/
public function getAllOptions()

$options = $this->optionDataInArray();
array_unshift($options, ['value' => '', 'label' => __('Please Selec')]);
$this->_options = $options;

return $options;

public function optionDataInArray(): array

$categories = $this->catalogCategory->getStoreCategories(true, false, true) ;
$options = [];
foreach ($categories as $category)
$options[] = ['value' => $category->getId(), 'label' => $category->getName()];
$options =$this->secondLevelCategories($category->getId(),$category->getName(),$options);

return $options;

private function secondLevelCategories($parentCatId,$parentCatName,$options)


$categoryCollection = $this->collectionFactory->create();
$categoryCollection->addAttributeToSelect(
'url_key'
)->addAttributeToSelect(
'name'
)->addAttributeToSelect(
'all_children'
)->addAttributeToSelect(
'is_anchor'
)->addAttributeToFilter(
'parent_id',
$parentCatId
)->addAttributeToFilter(
'is_active',
1
)->setOrder(
'position',
MagentoFrameworkDBSelect::SQL_ASC
)->joinUrlRewrite();

foreach($categoryCollection as $category)
$options[] = ['value' => $category->getId(), 'label' => $parentCatName.'-->'. $category->getName()];

return $options;




Also, your module must have below files & folders structure.



enter image description here



InstallData.php full code



<?php

namespace MetizsoftAllowcustomerSetup;

use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoCustomerModelCustomer;
use MagentoCustomerSetupCustomerSetupFactory;

class InstallData implements InstallDataInterface


private $customerSetupFactory;

/**
* Constructor
*
* @param MagentoCustomerSetupCustomerSetupFactory $customerSetupFactory
*/
public function __construct(
CustomerSetupFactory $customerSetupFactory
)
$this->customerSetupFactory = $customerSetupFactory;


/**
* @inheritdoc
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
)
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

$customerSetup->addAttribute(MagentoCustomerModelCustomer::ENTITY, 'hide_category', [
'type' => 'varchar',
'label' => 'Hide Categories',
'input' => 'multiselect',
'source' => 'MetizsoftAllowcustomerModelCustomerAttributeSourceHideCategory',
'required' => false,
'visible' => true,
'position' => 333,
'system' => false,
'backend' => 'MagentoEavModelEntityAttributeBackendArrayBackend'
]);

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




Output on magento 2 sample data Instance
enter image description here






share|improve this answer

























  • hello why we used extension_attributes.xml i am not understand about it can you able to give that file code

    – jay
    2 days ago












  • extension attribute need to enable your attribute for API

    – Amit Bera
    yesterday













0












0








0







You cannot use MagentoFrameworkOptionArrayInterface type for as Source Model of a multi-select EAV attribute.




MetizsoftAllowcustomerModelCustomerAttributeSourceHideCategory




Should be extended MagentoEavModelEntityAttributeSourceAbstractSource or your class will be the interface of MagentoFrameworkDataOptionSourceInterface.



InstallData.php code attribute create code must have source model and backend model that



 $customerSetup->addAttribute(MagentoCustomerModelCustomer::ENTITY, 'hide_category', [
'type' => 'varchar',
'label' => 'Hide Categories',
'input' => 'multiselect',
'source' => 'MetizsoftAllowcustomerModelCustomerAttributeSourceHideCategory',
'required' => false,
'visible' => true,
'position' => 333,
'system' => false,
'backend' => 'MagentoEavModelEntityAttributeBackendArrayBackend'
]);


Source Model Class code



<?php


namespace MetizsoftAllowcustomerModelCustomerAttributeSource;

class HideCategory extends MagentoEavModelEntityAttributeSourceAbstractSource

/**
* @var MagentoCatalogModelResourceModelCategoryCollectionFactory
*/
private $collectionFactory;
/**
* @var MagentoCatalogHelperCategory
*/
private $catalogCategory;

public function __construct(
MagentoCatalogHelperCategory $catalogCategory,
MagentoCatalogModelResourceModelCategoryCollectionFactory $collectionFactory
)

$this->catalogCategory = $catalogCategory;
$this->collectionFactory = $collectionFactory;

/**
* getAllOptions
*
* @return array
*/
public function getAllOptions()

$options = $this->optionDataInArray();
array_unshift($options, ['value' => '', 'label' => __('Please Selec')]);
$this->_options = $options;

return $options;

public function optionDataInArray(): array

$categories = $this->catalogCategory->getStoreCategories(true, false, true) ;
$options = [];
foreach ($categories as $category)
$options[] = ['value' => $category->getId(), 'label' => $category->getName()];
$options =$this->secondLevelCategories($category->getId(),$category->getName(),$options);

return $options;

private function secondLevelCategories($parentCatId,$parentCatName,$options)


$categoryCollection = $this->collectionFactory->create();
$categoryCollection->addAttributeToSelect(
'url_key'
)->addAttributeToSelect(
'name'
)->addAttributeToSelect(
'all_children'
)->addAttributeToSelect(
'is_anchor'
)->addAttributeToFilter(
'parent_id',
$parentCatId
)->addAttributeToFilter(
'is_active',
1
)->setOrder(
'position',
MagentoFrameworkDBSelect::SQL_ASC
)->joinUrlRewrite();

foreach($categoryCollection as $category)
$options[] = ['value' => $category->getId(), 'label' => $parentCatName.'-->'. $category->getName()];

return $options;




Also, your module must have below files & folders structure.



enter image description here



InstallData.php full code



<?php

namespace MetizsoftAllowcustomerSetup;

use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoCustomerModelCustomer;
use MagentoCustomerSetupCustomerSetupFactory;

class InstallData implements InstallDataInterface


private $customerSetupFactory;

/**
* Constructor
*
* @param MagentoCustomerSetupCustomerSetupFactory $customerSetupFactory
*/
public function __construct(
CustomerSetupFactory $customerSetupFactory
)
$this->customerSetupFactory = $customerSetupFactory;


/**
* @inheritdoc
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
)
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

$customerSetup->addAttribute(MagentoCustomerModelCustomer::ENTITY, 'hide_category', [
'type' => 'varchar',
'label' => 'Hide Categories',
'input' => 'multiselect',
'source' => 'MetizsoftAllowcustomerModelCustomerAttributeSourceHideCategory',
'required' => false,
'visible' => true,
'position' => 333,
'system' => false,
'backend' => 'MagentoEavModelEntityAttributeBackendArrayBackend'
]);

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




Output on magento 2 sample data Instance
enter image description here






share|improve this answer















You cannot use MagentoFrameworkOptionArrayInterface type for as Source Model of a multi-select EAV attribute.




MetizsoftAllowcustomerModelCustomerAttributeSourceHideCategory




Should be extended MagentoEavModelEntityAttributeSourceAbstractSource or your class will be the interface of MagentoFrameworkDataOptionSourceInterface.



InstallData.php code attribute create code must have source model and backend model that



 $customerSetup->addAttribute(MagentoCustomerModelCustomer::ENTITY, 'hide_category', [
'type' => 'varchar',
'label' => 'Hide Categories',
'input' => 'multiselect',
'source' => 'MetizsoftAllowcustomerModelCustomerAttributeSourceHideCategory',
'required' => false,
'visible' => true,
'position' => 333,
'system' => false,
'backend' => 'MagentoEavModelEntityAttributeBackendArrayBackend'
]);


Source Model Class code



<?php


namespace MetizsoftAllowcustomerModelCustomerAttributeSource;

class HideCategory extends MagentoEavModelEntityAttributeSourceAbstractSource

/**
* @var MagentoCatalogModelResourceModelCategoryCollectionFactory
*/
private $collectionFactory;
/**
* @var MagentoCatalogHelperCategory
*/
private $catalogCategory;

public function __construct(
MagentoCatalogHelperCategory $catalogCategory,
MagentoCatalogModelResourceModelCategoryCollectionFactory $collectionFactory
)

$this->catalogCategory = $catalogCategory;
$this->collectionFactory = $collectionFactory;

/**
* getAllOptions
*
* @return array
*/
public function getAllOptions()

$options = $this->optionDataInArray();
array_unshift($options, ['value' => '', 'label' => __('Please Selec')]);
$this->_options = $options;

return $options;

public function optionDataInArray(): array

$categories = $this->catalogCategory->getStoreCategories(true, false, true) ;
$options = [];
foreach ($categories as $category)
$options[] = ['value' => $category->getId(), 'label' => $category->getName()];
$options =$this->secondLevelCategories($category->getId(),$category->getName(),$options);

return $options;

private function secondLevelCategories($parentCatId,$parentCatName,$options)


$categoryCollection = $this->collectionFactory->create();
$categoryCollection->addAttributeToSelect(
'url_key'
)->addAttributeToSelect(
'name'
)->addAttributeToSelect(
'all_children'
)->addAttributeToSelect(
'is_anchor'
)->addAttributeToFilter(
'parent_id',
$parentCatId
)->addAttributeToFilter(
'is_active',
1
)->setOrder(
'position',
MagentoFrameworkDBSelect::SQL_ASC
)->joinUrlRewrite();

foreach($categoryCollection as $category)
$options[] = ['value' => $category->getId(), 'label' => $parentCatName.'-->'. $category->getName()];

return $options;




Also, your module must have below files & folders structure.



enter image description here



InstallData.php full code



<?php

namespace MetizsoftAllowcustomerSetup;

use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoCustomerModelCustomer;
use MagentoCustomerSetupCustomerSetupFactory;

class InstallData implements InstallDataInterface


private $customerSetupFactory;

/**
* Constructor
*
* @param MagentoCustomerSetupCustomerSetupFactory $customerSetupFactory
*/
public function __construct(
CustomerSetupFactory $customerSetupFactory
)
$this->customerSetupFactory = $customerSetupFactory;


/**
* @inheritdoc
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
)
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

$customerSetup->addAttribute(MagentoCustomerModelCustomer::ENTITY, 'hide_category', [
'type' => 'varchar',
'label' => 'Hide Categories',
'input' => 'multiselect',
'source' => 'MetizsoftAllowcustomerModelCustomerAttributeSourceHideCategory',
'required' => false,
'visible' => true,
'position' => 333,
'system' => false,
'backend' => 'MagentoEavModelEntityAttributeBackendArrayBackend'
]);

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




Output on magento 2 sample data Instance
enter image description here







share|improve this answer














share|improve this answer



share|improve this answer








edited 2 days ago

























answered 2 days ago









Amit BeraAmit Bera

60.2k1678178




60.2k1678178












  • hello why we used extension_attributes.xml i am not understand about it can you able to give that file code

    – jay
    2 days ago












  • extension attribute need to enable your attribute for API

    – Amit Bera
    yesterday

















  • hello why we used extension_attributes.xml i am not understand about it can you able to give that file code

    – jay
    2 days ago












  • extension attribute need to enable your attribute for API

    – Amit Bera
    yesterday
















hello why we used extension_attributes.xml i am not understand about it can you able to give that file code

– jay
2 days ago






hello why we used extension_attributes.xml i am not understand about it can you able to give that file code

– jay
2 days ago














extension attribute need to enable your attribute for API

– Amit Bera
yesterday





extension attribute need to enable your attribute for API

– Amit Bera
yesterday

















draft saved

draft discarded
















































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%2f270615%2fneed-to-custom-attribute-in-customer-info-backend-programatically-for-magento-2%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

Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form