How to add multi-select category tree at admin end in magento 2?Magento 2 : Selected categories are not...

Why is the underscore command _ useful?

Can someone publish a story that happened to you?

Why did C use the -> operator instead of reusing the . operator?

Combinatorics problem, right solution?

Where was the County of Thurn und Taxis located?

What is the most expensive material in the world that could be used to create Pun-Pun's lute?

Why do real positive eigenvalues result in an unstable system? What about eigenvalues between 0 and 1? or 1?

Find the identical rows in a matrix

Nails holding drywall

What was Apollo 13's "Little Jolt" after MECO?

Check if a string is entirely made of the same substring

"Whatever a Russian does, they end up making the Kalashnikov gun"? Are there any similar proverbs in English?

How do I reattach a shelf to the wall when it ripped out of the wall?

What to do with someone that cheated their way through university and a PhD program?

Is it acceptable to use working hours to read general interest books?

Are there moral objections to a life motivated purely by money? How to sway a person from this lifestyle?

Why do distances seem to matter in the Foundation world?

Why did Rep. Omar conclude her criticism of US troops with the phrase "NotTodaySatan"?

A Paper Record is What I Hamper

A strange hotel

Does a large simulator bay have standard public address announcements?

Co-worker works way more than he should

Why doesn't the standard consider a template constructor as a copy constructor?

Is there really no use for MD5 anymore?



How to add multi-select category tree at admin end in magento 2?


Magento 2 : Selected categories are not visible in edit formMagento 2 : Show admin category tree on frontendHow to get category tree in Magento 2?Magento 2 Add Category Tree Renderer Input With Modal Buttonhow to add Category tree structure like product edit/add in custom moduleMagento 2 - Add tree category selector on backend moduleUnit Test for overwrite collection class in magento2How to add filtering to custom table field column in Customers admin grid in Magento2?Magento 2: How to override newsletter Subscriber modelWhy Getting categories and names on product view page Magento 2 fails?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 Add new field to Magento_User admin formMagento 2 Custom Module admin form category treeTwo categories are loading every available product in categoryMagento 2.3 Can't view module's front end page output?Magento 2 How to remove price filter from category if module is enable?






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







3















I would like to display *Category Tree Names** in multi select field in magento 2 admin end?



I have tried with below code but displaying only first cateogires could you please any one help on this?



$field = $fieldset->addField(
'wp_test',
'multiselect',
[
'name' => 'wp_test',
'label' => __("Test"),
'values' => $categorylistsource->toOptionArray(),
'value' => $this->_getTest(),
'title' => __('Test.'),
'note' => __('Test')

]
);



HelloConfigurableSkuModelConfigSource




<?php
/**

@copyright Copyright
*/
namespace HelloConfigurableSkuModelConfigSource;

use MagentoFrameworkOptionArrayInterface;

class Categorylist implements ArrayInterface
{
protected $_categoryFactory;
protected $_categoryCollectionFactory;

public function __construct(
MagentoCatalogModelCategoryFactory $categoryFactory,
MagentoCatalogModelResourceModelCategoryCollectionFactory $categoryCollectionFactory
)
{
$this->_categoryFactory = $categoryFactory;
$this->_categoryCollectionFactory = $categoryCollectionFactory;
}

public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
{
$collection = $this->_categoryCollectionFactory->create();
$collection->addAttributeToSelect('*');

// select only active categories
if ($isActive) {
$collection->addIsActiveFilter();
}

// select categories of certain level
if ($level) {
$collection->addLevelFilter($level);
}

// sort categories by some value
if ($sortBy) {
$collection->addOrderField($sortBy);
}

// select certain number of categories
if ($pageSize) {
$collection->setPageSize($pageSize);
}

return $collection;
}

public function toOptionArray()
{
$arr = $this->_toArray();
$ret = [];

foreach ($arr as $key => $value)
{
$ret[] = [
'value' => $key,
'label' => $value
];
}

return $ret;
}

private function _toArray()
{
$categories = $this->getCategoryCollection(true, false, false, false);

$catagoryList = array();
foreach ($categories as $category)
{
$catagoryList[$category->getEntityId()] = __($this->_getParentName($category->getPath()) . $category->getName());
}

return $catagoryList;
}

private function _getParentName($path = '')
{
$parentName = '';
$rootCats = array(1,2);

$catTree = explode("/", $path);
// Deleting category itself
array_pop($catTree);

if($catTree && (count($catTree) > count($rootCats)))
{
foreach ($catTree as $catId)
{
if(!in_array($catId, $rootCats))
{
$category = $this->_categoryFactory->create()->load($catId);
$categoryName = $category->getName();
$parentName .= $categoryName . ' -> ';
}
}
}

return $parentName;
}
}


But As per the above logic displaying only single line but i need to display like tree as mentioned below screenshot. how to achieve?



OUT PUT I WANT:-
enter image description here










share|improve this question

























  • Did you try with this one? magento.stackexchange.com/a/148556/33057

    – Khoa TruongDinh
    Nov 8 '18 at 7:41











  • yes @KhoaTruongDinh but no luck

    – Nagaraju Kasa
    Nov 8 '18 at 8:25











  • Did you try with some code lines? Could you post here?

    – Khoa TruongDinh
    Nov 8 '18 at 8:30











  • Sure I will update the same

    – Nagaraju Kasa
    Nov 8 '18 at 8:30











  • hi @KhoaTruongDinh updated my post please suggest

    – Nagaraju Kasa
    Nov 8 '18 at 8:50


















3















I would like to display *Category Tree Names** in multi select field in magento 2 admin end?



I have tried with below code but displaying only first cateogires could you please any one help on this?



$field = $fieldset->addField(
'wp_test',
'multiselect',
[
'name' => 'wp_test',
'label' => __("Test"),
'values' => $categorylistsource->toOptionArray(),
'value' => $this->_getTest(),
'title' => __('Test.'),
'note' => __('Test')

]
);



HelloConfigurableSkuModelConfigSource




<?php
/**

@copyright Copyright
*/
namespace HelloConfigurableSkuModelConfigSource;

use MagentoFrameworkOptionArrayInterface;

class Categorylist implements ArrayInterface
{
protected $_categoryFactory;
protected $_categoryCollectionFactory;

public function __construct(
MagentoCatalogModelCategoryFactory $categoryFactory,
MagentoCatalogModelResourceModelCategoryCollectionFactory $categoryCollectionFactory
)
{
$this->_categoryFactory = $categoryFactory;
$this->_categoryCollectionFactory = $categoryCollectionFactory;
}

public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
{
$collection = $this->_categoryCollectionFactory->create();
$collection->addAttributeToSelect('*');

// select only active categories
if ($isActive) {
$collection->addIsActiveFilter();
}

// select categories of certain level
if ($level) {
$collection->addLevelFilter($level);
}

// sort categories by some value
if ($sortBy) {
$collection->addOrderField($sortBy);
}

// select certain number of categories
if ($pageSize) {
$collection->setPageSize($pageSize);
}

return $collection;
}

public function toOptionArray()
{
$arr = $this->_toArray();
$ret = [];

foreach ($arr as $key => $value)
{
$ret[] = [
'value' => $key,
'label' => $value
];
}

return $ret;
}

private function _toArray()
{
$categories = $this->getCategoryCollection(true, false, false, false);

$catagoryList = array();
foreach ($categories as $category)
{
$catagoryList[$category->getEntityId()] = __($this->_getParentName($category->getPath()) . $category->getName());
}

return $catagoryList;
}

private function _getParentName($path = '')
{
$parentName = '';
$rootCats = array(1,2);

$catTree = explode("/", $path);
// Deleting category itself
array_pop($catTree);

if($catTree && (count($catTree) > count($rootCats)))
{
foreach ($catTree as $catId)
{
if(!in_array($catId, $rootCats))
{
$category = $this->_categoryFactory->create()->load($catId);
$categoryName = $category->getName();
$parentName .= $categoryName . ' -> ';
}
}
}

return $parentName;
}
}


But As per the above logic displaying only single line but i need to display like tree as mentioned below screenshot. how to achieve?



OUT PUT I WANT:-
enter image description here










share|improve this question

























  • Did you try with this one? magento.stackexchange.com/a/148556/33057

    – Khoa TruongDinh
    Nov 8 '18 at 7:41











  • yes @KhoaTruongDinh but no luck

    – Nagaraju Kasa
    Nov 8 '18 at 8:25











  • Did you try with some code lines? Could you post here?

    – Khoa TruongDinh
    Nov 8 '18 at 8:30











  • Sure I will update the same

    – Nagaraju Kasa
    Nov 8 '18 at 8:30











  • hi @KhoaTruongDinh updated my post please suggest

    – Nagaraju Kasa
    Nov 8 '18 at 8:50














3












3








3


1






I would like to display *Category Tree Names** in multi select field in magento 2 admin end?



I have tried with below code but displaying only first cateogires could you please any one help on this?



$field = $fieldset->addField(
'wp_test',
'multiselect',
[
'name' => 'wp_test',
'label' => __("Test"),
'values' => $categorylistsource->toOptionArray(),
'value' => $this->_getTest(),
'title' => __('Test.'),
'note' => __('Test')

]
);



HelloConfigurableSkuModelConfigSource




<?php
/**

@copyright Copyright
*/
namespace HelloConfigurableSkuModelConfigSource;

use MagentoFrameworkOptionArrayInterface;

class Categorylist implements ArrayInterface
{
protected $_categoryFactory;
protected $_categoryCollectionFactory;

public function __construct(
MagentoCatalogModelCategoryFactory $categoryFactory,
MagentoCatalogModelResourceModelCategoryCollectionFactory $categoryCollectionFactory
)
{
$this->_categoryFactory = $categoryFactory;
$this->_categoryCollectionFactory = $categoryCollectionFactory;
}

public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
{
$collection = $this->_categoryCollectionFactory->create();
$collection->addAttributeToSelect('*');

// select only active categories
if ($isActive) {
$collection->addIsActiveFilter();
}

// select categories of certain level
if ($level) {
$collection->addLevelFilter($level);
}

// sort categories by some value
if ($sortBy) {
$collection->addOrderField($sortBy);
}

// select certain number of categories
if ($pageSize) {
$collection->setPageSize($pageSize);
}

return $collection;
}

public function toOptionArray()
{
$arr = $this->_toArray();
$ret = [];

foreach ($arr as $key => $value)
{
$ret[] = [
'value' => $key,
'label' => $value
];
}

return $ret;
}

private function _toArray()
{
$categories = $this->getCategoryCollection(true, false, false, false);

$catagoryList = array();
foreach ($categories as $category)
{
$catagoryList[$category->getEntityId()] = __($this->_getParentName($category->getPath()) . $category->getName());
}

return $catagoryList;
}

private function _getParentName($path = '')
{
$parentName = '';
$rootCats = array(1,2);

$catTree = explode("/", $path);
// Deleting category itself
array_pop($catTree);

if($catTree && (count($catTree) > count($rootCats)))
{
foreach ($catTree as $catId)
{
if(!in_array($catId, $rootCats))
{
$category = $this->_categoryFactory->create()->load($catId);
$categoryName = $category->getName();
$parentName .= $categoryName . ' -> ';
}
}
}

return $parentName;
}
}


But As per the above logic displaying only single line but i need to display like tree as mentioned below screenshot. how to achieve?



OUT PUT I WANT:-
enter image description here










share|improve this question
















I would like to display *Category Tree Names** in multi select field in magento 2 admin end?



I have tried with below code but displaying only first cateogires could you please any one help on this?



$field = $fieldset->addField(
'wp_test',
'multiselect',
[
'name' => 'wp_test',
'label' => __("Test"),
'values' => $categorylistsource->toOptionArray(),
'value' => $this->_getTest(),
'title' => __('Test.'),
'note' => __('Test')

]
);



HelloConfigurableSkuModelConfigSource




<?php
/**

@copyright Copyright
*/
namespace HelloConfigurableSkuModelConfigSource;

use MagentoFrameworkOptionArrayInterface;

class Categorylist implements ArrayInterface
{
protected $_categoryFactory;
protected $_categoryCollectionFactory;

public function __construct(
MagentoCatalogModelCategoryFactory $categoryFactory,
MagentoCatalogModelResourceModelCategoryCollectionFactory $categoryCollectionFactory
)
{
$this->_categoryFactory = $categoryFactory;
$this->_categoryCollectionFactory = $categoryCollectionFactory;
}

public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
{
$collection = $this->_categoryCollectionFactory->create();
$collection->addAttributeToSelect('*');

// select only active categories
if ($isActive) {
$collection->addIsActiveFilter();
}

// select categories of certain level
if ($level) {
$collection->addLevelFilter($level);
}

// sort categories by some value
if ($sortBy) {
$collection->addOrderField($sortBy);
}

// select certain number of categories
if ($pageSize) {
$collection->setPageSize($pageSize);
}

return $collection;
}

public function toOptionArray()
{
$arr = $this->_toArray();
$ret = [];

foreach ($arr as $key => $value)
{
$ret[] = [
'value' => $key,
'label' => $value
];
}

return $ret;
}

private function _toArray()
{
$categories = $this->getCategoryCollection(true, false, false, false);

$catagoryList = array();
foreach ($categories as $category)
{
$catagoryList[$category->getEntityId()] = __($this->_getParentName($category->getPath()) . $category->getName());
}

return $catagoryList;
}

private function _getParentName($path = '')
{
$parentName = '';
$rootCats = array(1,2);

$catTree = explode("/", $path);
// Deleting category itself
array_pop($catTree);

if($catTree && (count($catTree) > count($rootCats)))
{
foreach ($catTree as $catId)
{
if(!in_array($catId, $rootCats))
{
$category = $this->_categoryFactory->create()->load($catId);
$categoryName = $category->getName();
$parentName .= $categoryName . ' -> ';
}
}
}

return $parentName;
}
}


But As per the above logic displaying only single line but i need to display like tree as mentioned below screenshot. how to achieve?



OUT PUT I WANT:-
enter image description here







magento2 attributes product-attribute category-tree






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 3:12







Nagaraju Kasa

















asked Nov 8 '18 at 5:27









Nagaraju KasaNagaraju Kasa

2,80621742




2,80621742













  • Did you try with this one? magento.stackexchange.com/a/148556/33057

    – Khoa TruongDinh
    Nov 8 '18 at 7:41











  • yes @KhoaTruongDinh but no luck

    – Nagaraju Kasa
    Nov 8 '18 at 8:25











  • Did you try with some code lines? Could you post here?

    – Khoa TruongDinh
    Nov 8 '18 at 8:30











  • Sure I will update the same

    – Nagaraju Kasa
    Nov 8 '18 at 8:30











  • hi @KhoaTruongDinh updated my post please suggest

    – Nagaraju Kasa
    Nov 8 '18 at 8:50



















  • Did you try with this one? magento.stackexchange.com/a/148556/33057

    – Khoa TruongDinh
    Nov 8 '18 at 7:41











  • yes @KhoaTruongDinh but no luck

    – Nagaraju Kasa
    Nov 8 '18 at 8:25











  • Did you try with some code lines? Could you post here?

    – Khoa TruongDinh
    Nov 8 '18 at 8:30











  • Sure I will update the same

    – Nagaraju Kasa
    Nov 8 '18 at 8:30











  • hi @KhoaTruongDinh updated my post please suggest

    – Nagaraju Kasa
    Nov 8 '18 at 8:50

















Did you try with this one? magento.stackexchange.com/a/148556/33057

– Khoa TruongDinh
Nov 8 '18 at 7:41





Did you try with this one? magento.stackexchange.com/a/148556/33057

– Khoa TruongDinh
Nov 8 '18 at 7:41













yes @KhoaTruongDinh but no luck

– Nagaraju Kasa
Nov 8 '18 at 8:25





yes @KhoaTruongDinh but no luck

– Nagaraju Kasa
Nov 8 '18 at 8:25













Did you try with some code lines? Could you post here?

– Khoa TruongDinh
Nov 8 '18 at 8:30





Did you try with some code lines? Could you post here?

– Khoa TruongDinh
Nov 8 '18 at 8:30













Sure I will update the same

– Nagaraju Kasa
Nov 8 '18 at 8:30





Sure I will update the same

– Nagaraju Kasa
Nov 8 '18 at 8:30













hi @KhoaTruongDinh updated my post please suggest

– Nagaraju Kasa
Nov 8 '18 at 8:50





hi @KhoaTruongDinh updated my post please suggest

– Nagaraju Kasa
Nov 8 '18 at 8:50










2 Answers
2






active

oldest

votes


















1














please follow the below logic to get the category collection as tree structure. please let me know if u need any help.



<?php
namespace HelloConfigurableSkuModelConfigSource;

use MagentoFrameworkOptionArrayInterface;
use MagentoCatalogHelperCategory;

class Categorylist 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 answer
























  • Thanks for your answer will check and getback

    – Nagaraju Kasa
    Nov 14 '18 at 6:24



















-1














Good answer! I applied it in my project.






share|improve this answer
























    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%2f249360%2fhow-to-add-multi-select-category-tree-at-admin-end-in-magento-2%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














    please follow the below logic to get the category collection as tree structure. please let me know if u need any help.



    <?php
    namespace HelloConfigurableSkuModelConfigSource;

    use MagentoFrameworkOptionArrayInterface;
    use MagentoCatalogHelperCategory;

    class Categorylist 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 answer
























    • Thanks for your answer will check and getback

      – Nagaraju Kasa
      Nov 14 '18 at 6:24
















    1














    please follow the below logic to get the category collection as tree structure. please let me know if u need any help.



    <?php
    namespace HelloConfigurableSkuModelConfigSource;

    use MagentoFrameworkOptionArrayInterface;
    use MagentoCatalogHelperCategory;

    class Categorylist 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 answer
























    • Thanks for your answer will check and getback

      – Nagaraju Kasa
      Nov 14 '18 at 6:24














    1












    1








    1







    please follow the below logic to get the category collection as tree structure. please let me know if u need any help.



    <?php
    namespace HelloConfigurableSkuModelConfigSource;

    use MagentoFrameworkOptionArrayInterface;
    use MagentoCatalogHelperCategory;

    class Categorylist 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 answer













    please follow the below logic to get the category collection as tree structure. please let me know if u need any help.



    <?php
    namespace HelloConfigurableSkuModelConfigSource;

    use MagentoFrameworkOptionArrayInterface;
    use MagentoCatalogHelperCategory;

    class Categorylist 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 answer












    share|improve this answer



    share|improve this answer










    answered Nov 14 '18 at 6:20









    Kavya cheeralaKavya cheerala

    464




    464













    • Thanks for your answer will check and getback

      – Nagaraju Kasa
      Nov 14 '18 at 6:24



















    • Thanks for your answer will check and getback

      – Nagaraju Kasa
      Nov 14 '18 at 6:24

















    Thanks for your answer will check and getback

    – Nagaraju Kasa
    Nov 14 '18 at 6:24





    Thanks for your answer will check and getback

    – Nagaraju Kasa
    Nov 14 '18 at 6:24













    -1














    Good answer! I applied it in my project.






    share|improve this answer




























      -1














      Good answer! I applied it in my project.






      share|improve this answer


























        -1












        -1








        -1







        Good answer! I applied it in my project.






        share|improve this answer













        Good answer! I applied it in my project.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 1 hour ago









        AndradaAndrada

        145




        145






























            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%2f249360%2fhow-to-add-multi-select-category-tree-at-admin-end-in-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

            “%fieldName is a required field.”, in Magento2 REST API Call for GET Method Type The Next...

            How to change City field to a dropdown in Checkout step Magento 2Magento 2 : How to change UI field(s)...

            夢乃愛華...