How to get category tree in Magento 2?
I need to show category tree, just like in admin section, in my custom page. I viewed this solution in magento.stackexchange.com. It was good but limited to 2 levels of category. I need all the categories. How can it be done?
magento2 category category-tree category-listing
add a comment |
I need to show category tree, just like in admin section, in my custom page. I viewed this solution in magento.stackexchange.com. It was good but limited to 2 levels of category. I need all the categories. How can it be done?
magento2 category category-tree category-listing
add a comment |
I need to show category tree, just like in admin section, in my custom page. I viewed this solution in magento.stackexchange.com. It was good but limited to 2 levels of category. I need all the categories. How can it be done?
magento2 category category-tree category-listing
I need to show category tree, just like in admin section, in my custom page. I viewed this solution in magento.stackexchange.com. It was good but limited to 2 levels of category. I need all the categories. How can it be done?
magento2 category category-tree category-listing
magento2 category category-tree category-listing
asked Dec 4 '17 at 7:45
Purushotam SangroulaPurushotam Sangroula
1,055825
1,055825
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
I searched over internet for solution to this but got nothing useful. Then I diverted my research towards Magento core where I found MagentoCatalogBlockAdminhtmlCategoryTree class where I found a function getTree(). Then I tried to observed it's return value in my custom template file. The effort became fruitful as I got the desired result.
I created a block file where I have injected the above class as:
<?php
namespace VendorModuleBlock;
class CategoriesColle extends MagentoFrameworkViewElementTemplate
{
...
protected $adminCategoryTree;
/**
* @param MagentoFrameworkViewElementTemplateContext $context
* @param MagentoCatalogHelperCategory $categoryHelper
* @param array $data
*/
public function __construct(
...
MagentoCatalogBlockAdminhtmlCategoryTree $adminCategoryTree
)
{
...
$this->adminCategoryTree = $adminCategoryTree;
}
public function getTree()
{
return $this->adminCategoryTree->getTree();
}
...
}
The return value of the getTree() is the desired array of the category tree which can be verified by dumping the value in template file.
add a comment |
You can create your own tree with custom collection as follows:
Firstly add a field in your ui-form:
<field name="custom" component="Namespce_Modulename/js/select-category" sortOrder="20" formElement="select">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filterOptions" xsi:type="boolean">true</item>//to add filter in select-ui
<item name="multiple" xsi:type="boolean">false</item>//select multiple or not
<item name="showCheckbox" xsi:type="boolean">true</item>//to show checkboxes
<item name="disableLabel" xsi:type="boolean">true</item>
</item>
</argument>
<settings>
<required>true</required>
<validation>
<rule name="required-entry" xsi:type="boolean">true</rule>
</validation>
<elementTmpl>ui/grid/filters/elements/ui-select</elementTmpl>
<label translate="true">Select Category</label>//label to Field
<dataScope>data.custom</dataScope>//To map
<componentType>field</componentType>
<listens>
<link name="${ $.namespace }.${ $.namespace }:responseData">setParsed</link>
</listens>
</settings>
<formElements>
<select>
<settings>
<options class="NamespaceModuleNameUiComponentFormCategoryOptions"/>
</settings>
</select>
</formElements>
Now create Js file to map the field's value:
Namespace_Modulename/view/adminhtml/web/js/select-category.js
define([
'Magento_Ui/js/form/element/ui-select'
], function (Select) {
'use strict';
return Select.extend({
/**
* Parse data and set it to options.
*
* @param {Object} data - Response data object.
* @returns {Object}
*/
setParsed: function (data) {
var option = this.parseData(data);
if (data.error) {
return this;
}
this.options();
this.setOption(option);
this.set('newOption', option);
},
/**
* Normalize option object.
*
* @param {Object} data - Option object.
* @returns {Object}
*/
parseData: function (data) {
return {
value: data.category.entity_id,
label: data.category.name
};
}
});
});
Create a file to get options to display:
NamespaceModuleNameUiComponentFormCategoryOptions.php
<?php
namespace NamespaceModuleNameUiComponentFormCategory;
use MagentoFrameworkDataOptionSourceInterface;
use MagentoCategoryModelResourceModelCategoryCollectionFactory as CategoryCollectionFactory;
use MagentoFrameworkAppRequestInterface;
/**
* Options tree for "Categories" field
*/
class Options implements OptionSourceInterface
{
protected $categoryCollectionFactory;
/**
* @var RequestInterface
*/
protected $request;
/**
* @var array
*/
protected $categoryTree;
/**
* @param CategoryCollectionFactory $categoryCollectionFactory
* @param RequestInterface $request
*/
public function __construct(
CategoryCollectionFactory $categoryCollectionFactory,
RequestInterface $request
) {
$this->categoryCollectionFactory = $categoryCollectionFactory;
$this->request = $request;
}
/**
* {@inheritdoc}
*/
public function toOptionArray()
{
return $this->getCategoryTree();
}
/**
* Retrieve categories tree
*
* @return array
*/
protected function getCategoryTree()
{
if ($this->categoryTree === null) {
$collection = $this->categoryCollectionFactory->create();
$collection->addNameToSelect();
foreach ($collection as $category) {
$categoryId = $category->getEntityId();
if (!isset($categoryById[$categoryId])) {
$categoryById[$categoryId] = [
'value' => $categoryId
];
}
$categoryById[$categoryId]['label'] = $category->getName();
}
$this->categoryTree = $categoryById;
}
return $this->categoryTree;
}
}
Hope it helps!
can you please help me on this ? magento.stackexchange.com/questions/249360/…
– Nagaraju Kasa
Nov 8 '18 at 7:17
@NagarajuKasa have you followed above steps?
– user00247
Nov 9 '18 at 7:24
yes @user00247 i have followed your steps, can see steps here magento.stackexchange.com/questions/249360/…
– Nagaraju Kasa
Nov 9 '18 at 8:56
add a comment |
// Get all the children categories of given category collection factory
foreach ($collection as $key => $value) {
$temp = $value->getData();
$categoryObj = $this->_repository->get($temp['entity_id']);
$subcategories = $categoryObj->getChildrenCategories();
foreach($subcategories as $key2 => $subcategorie) {
if($subcategorie->hasChildren()) {
$childCategoryObj = $this->_repository->get($subcategorie->getId());
$childSubcategories = $childCategoryObj->getChildrenCategories();
foreach($childSubcategories as $childSubcategorie) {
$temp1['children'] = $temp2;
}
$temp['children'] = $temp1;
}
}
$item[$key] = $temp;
}
// Here you can get all the children upto 2 level in "item" variable
echo "<pre>";
print_r($item);
New contributor
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f204269%2fhow-to-get-category-tree-in-magento-2%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
I searched over internet for solution to this but got nothing useful. Then I diverted my research towards Magento core where I found MagentoCatalogBlockAdminhtmlCategoryTree class where I found a function getTree(). Then I tried to observed it's return value in my custom template file. The effort became fruitful as I got the desired result.
I created a block file where I have injected the above class as:
<?php
namespace VendorModuleBlock;
class CategoriesColle extends MagentoFrameworkViewElementTemplate
{
...
protected $adminCategoryTree;
/**
* @param MagentoFrameworkViewElementTemplateContext $context
* @param MagentoCatalogHelperCategory $categoryHelper
* @param array $data
*/
public function __construct(
...
MagentoCatalogBlockAdminhtmlCategoryTree $adminCategoryTree
)
{
...
$this->adminCategoryTree = $adminCategoryTree;
}
public function getTree()
{
return $this->adminCategoryTree->getTree();
}
...
}
The return value of the getTree() is the desired array of the category tree which can be verified by dumping the value in template file.
add a comment |
I searched over internet for solution to this but got nothing useful. Then I diverted my research towards Magento core where I found MagentoCatalogBlockAdminhtmlCategoryTree class where I found a function getTree(). Then I tried to observed it's return value in my custom template file. The effort became fruitful as I got the desired result.
I created a block file where I have injected the above class as:
<?php
namespace VendorModuleBlock;
class CategoriesColle extends MagentoFrameworkViewElementTemplate
{
...
protected $adminCategoryTree;
/**
* @param MagentoFrameworkViewElementTemplateContext $context
* @param MagentoCatalogHelperCategory $categoryHelper
* @param array $data
*/
public function __construct(
...
MagentoCatalogBlockAdminhtmlCategoryTree $adminCategoryTree
)
{
...
$this->adminCategoryTree = $adminCategoryTree;
}
public function getTree()
{
return $this->adminCategoryTree->getTree();
}
...
}
The return value of the getTree() is the desired array of the category tree which can be verified by dumping the value in template file.
add a comment |
I searched over internet for solution to this but got nothing useful. Then I diverted my research towards Magento core where I found MagentoCatalogBlockAdminhtmlCategoryTree class where I found a function getTree(). Then I tried to observed it's return value in my custom template file. The effort became fruitful as I got the desired result.
I created a block file where I have injected the above class as:
<?php
namespace VendorModuleBlock;
class CategoriesColle extends MagentoFrameworkViewElementTemplate
{
...
protected $adminCategoryTree;
/**
* @param MagentoFrameworkViewElementTemplateContext $context
* @param MagentoCatalogHelperCategory $categoryHelper
* @param array $data
*/
public function __construct(
...
MagentoCatalogBlockAdminhtmlCategoryTree $adminCategoryTree
)
{
...
$this->adminCategoryTree = $adminCategoryTree;
}
public function getTree()
{
return $this->adminCategoryTree->getTree();
}
...
}
The return value of the getTree() is the desired array of the category tree which can be verified by dumping the value in template file.
I searched over internet for solution to this but got nothing useful. Then I diverted my research towards Magento core where I found MagentoCatalogBlockAdminhtmlCategoryTree class where I found a function getTree(). Then I tried to observed it's return value in my custom template file. The effort became fruitful as I got the desired result.
I created a block file where I have injected the above class as:
<?php
namespace VendorModuleBlock;
class CategoriesColle extends MagentoFrameworkViewElementTemplate
{
...
protected $adminCategoryTree;
/**
* @param MagentoFrameworkViewElementTemplateContext $context
* @param MagentoCatalogHelperCategory $categoryHelper
* @param array $data
*/
public function __construct(
...
MagentoCatalogBlockAdminhtmlCategoryTree $adminCategoryTree
)
{
...
$this->adminCategoryTree = $adminCategoryTree;
}
public function getTree()
{
return $this->adminCategoryTree->getTree();
}
...
}
The return value of the getTree() is the desired array of the category tree which can be verified by dumping the value in template file.
answered Dec 4 '17 at 10:43
Purushotam SangroulaPurushotam Sangroula
1,055825
1,055825
add a comment |
add a comment |
You can create your own tree with custom collection as follows:
Firstly add a field in your ui-form:
<field name="custom" component="Namespce_Modulename/js/select-category" sortOrder="20" formElement="select">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filterOptions" xsi:type="boolean">true</item>//to add filter in select-ui
<item name="multiple" xsi:type="boolean">false</item>//select multiple or not
<item name="showCheckbox" xsi:type="boolean">true</item>//to show checkboxes
<item name="disableLabel" xsi:type="boolean">true</item>
</item>
</argument>
<settings>
<required>true</required>
<validation>
<rule name="required-entry" xsi:type="boolean">true</rule>
</validation>
<elementTmpl>ui/grid/filters/elements/ui-select</elementTmpl>
<label translate="true">Select Category</label>//label to Field
<dataScope>data.custom</dataScope>//To map
<componentType>field</componentType>
<listens>
<link name="${ $.namespace }.${ $.namespace }:responseData">setParsed</link>
</listens>
</settings>
<formElements>
<select>
<settings>
<options class="NamespaceModuleNameUiComponentFormCategoryOptions"/>
</settings>
</select>
</formElements>
Now create Js file to map the field's value:
Namespace_Modulename/view/adminhtml/web/js/select-category.js
define([
'Magento_Ui/js/form/element/ui-select'
], function (Select) {
'use strict';
return Select.extend({
/**
* Parse data and set it to options.
*
* @param {Object} data - Response data object.
* @returns {Object}
*/
setParsed: function (data) {
var option = this.parseData(data);
if (data.error) {
return this;
}
this.options();
this.setOption(option);
this.set('newOption', option);
},
/**
* Normalize option object.
*
* @param {Object} data - Option object.
* @returns {Object}
*/
parseData: function (data) {
return {
value: data.category.entity_id,
label: data.category.name
};
}
});
});
Create a file to get options to display:
NamespaceModuleNameUiComponentFormCategoryOptions.php
<?php
namespace NamespaceModuleNameUiComponentFormCategory;
use MagentoFrameworkDataOptionSourceInterface;
use MagentoCategoryModelResourceModelCategoryCollectionFactory as CategoryCollectionFactory;
use MagentoFrameworkAppRequestInterface;
/**
* Options tree for "Categories" field
*/
class Options implements OptionSourceInterface
{
protected $categoryCollectionFactory;
/**
* @var RequestInterface
*/
protected $request;
/**
* @var array
*/
protected $categoryTree;
/**
* @param CategoryCollectionFactory $categoryCollectionFactory
* @param RequestInterface $request
*/
public function __construct(
CategoryCollectionFactory $categoryCollectionFactory,
RequestInterface $request
) {
$this->categoryCollectionFactory = $categoryCollectionFactory;
$this->request = $request;
}
/**
* {@inheritdoc}
*/
public function toOptionArray()
{
return $this->getCategoryTree();
}
/**
* Retrieve categories tree
*
* @return array
*/
protected function getCategoryTree()
{
if ($this->categoryTree === null) {
$collection = $this->categoryCollectionFactory->create();
$collection->addNameToSelect();
foreach ($collection as $category) {
$categoryId = $category->getEntityId();
if (!isset($categoryById[$categoryId])) {
$categoryById[$categoryId] = [
'value' => $categoryId
];
}
$categoryById[$categoryId]['label'] = $category->getName();
}
$this->categoryTree = $categoryById;
}
return $this->categoryTree;
}
}
Hope it helps!
can you please help me on this ? magento.stackexchange.com/questions/249360/…
– Nagaraju Kasa
Nov 8 '18 at 7:17
@NagarajuKasa have you followed above steps?
– user00247
Nov 9 '18 at 7:24
yes @user00247 i have followed your steps, can see steps here magento.stackexchange.com/questions/249360/…
– Nagaraju Kasa
Nov 9 '18 at 8:56
add a comment |
You can create your own tree with custom collection as follows:
Firstly add a field in your ui-form:
<field name="custom" component="Namespce_Modulename/js/select-category" sortOrder="20" formElement="select">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filterOptions" xsi:type="boolean">true</item>//to add filter in select-ui
<item name="multiple" xsi:type="boolean">false</item>//select multiple or not
<item name="showCheckbox" xsi:type="boolean">true</item>//to show checkboxes
<item name="disableLabel" xsi:type="boolean">true</item>
</item>
</argument>
<settings>
<required>true</required>
<validation>
<rule name="required-entry" xsi:type="boolean">true</rule>
</validation>
<elementTmpl>ui/grid/filters/elements/ui-select</elementTmpl>
<label translate="true">Select Category</label>//label to Field
<dataScope>data.custom</dataScope>//To map
<componentType>field</componentType>
<listens>
<link name="${ $.namespace }.${ $.namespace }:responseData">setParsed</link>
</listens>
</settings>
<formElements>
<select>
<settings>
<options class="NamespaceModuleNameUiComponentFormCategoryOptions"/>
</settings>
</select>
</formElements>
Now create Js file to map the field's value:
Namespace_Modulename/view/adminhtml/web/js/select-category.js
define([
'Magento_Ui/js/form/element/ui-select'
], function (Select) {
'use strict';
return Select.extend({
/**
* Parse data and set it to options.
*
* @param {Object} data - Response data object.
* @returns {Object}
*/
setParsed: function (data) {
var option = this.parseData(data);
if (data.error) {
return this;
}
this.options();
this.setOption(option);
this.set('newOption', option);
},
/**
* Normalize option object.
*
* @param {Object} data - Option object.
* @returns {Object}
*/
parseData: function (data) {
return {
value: data.category.entity_id,
label: data.category.name
};
}
});
});
Create a file to get options to display:
NamespaceModuleNameUiComponentFormCategoryOptions.php
<?php
namespace NamespaceModuleNameUiComponentFormCategory;
use MagentoFrameworkDataOptionSourceInterface;
use MagentoCategoryModelResourceModelCategoryCollectionFactory as CategoryCollectionFactory;
use MagentoFrameworkAppRequestInterface;
/**
* Options tree for "Categories" field
*/
class Options implements OptionSourceInterface
{
protected $categoryCollectionFactory;
/**
* @var RequestInterface
*/
protected $request;
/**
* @var array
*/
protected $categoryTree;
/**
* @param CategoryCollectionFactory $categoryCollectionFactory
* @param RequestInterface $request
*/
public function __construct(
CategoryCollectionFactory $categoryCollectionFactory,
RequestInterface $request
) {
$this->categoryCollectionFactory = $categoryCollectionFactory;
$this->request = $request;
}
/**
* {@inheritdoc}
*/
public function toOptionArray()
{
return $this->getCategoryTree();
}
/**
* Retrieve categories tree
*
* @return array
*/
protected function getCategoryTree()
{
if ($this->categoryTree === null) {
$collection = $this->categoryCollectionFactory->create();
$collection->addNameToSelect();
foreach ($collection as $category) {
$categoryId = $category->getEntityId();
if (!isset($categoryById[$categoryId])) {
$categoryById[$categoryId] = [
'value' => $categoryId
];
}
$categoryById[$categoryId]['label'] = $category->getName();
}
$this->categoryTree = $categoryById;
}
return $this->categoryTree;
}
}
Hope it helps!
can you please help me on this ? magento.stackexchange.com/questions/249360/…
– Nagaraju Kasa
Nov 8 '18 at 7:17
@NagarajuKasa have you followed above steps?
– user00247
Nov 9 '18 at 7:24
yes @user00247 i have followed your steps, can see steps here magento.stackexchange.com/questions/249360/…
– Nagaraju Kasa
Nov 9 '18 at 8:56
add a comment |
You can create your own tree with custom collection as follows:
Firstly add a field in your ui-form:
<field name="custom" component="Namespce_Modulename/js/select-category" sortOrder="20" formElement="select">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filterOptions" xsi:type="boolean">true</item>//to add filter in select-ui
<item name="multiple" xsi:type="boolean">false</item>//select multiple or not
<item name="showCheckbox" xsi:type="boolean">true</item>//to show checkboxes
<item name="disableLabel" xsi:type="boolean">true</item>
</item>
</argument>
<settings>
<required>true</required>
<validation>
<rule name="required-entry" xsi:type="boolean">true</rule>
</validation>
<elementTmpl>ui/grid/filters/elements/ui-select</elementTmpl>
<label translate="true">Select Category</label>//label to Field
<dataScope>data.custom</dataScope>//To map
<componentType>field</componentType>
<listens>
<link name="${ $.namespace }.${ $.namespace }:responseData">setParsed</link>
</listens>
</settings>
<formElements>
<select>
<settings>
<options class="NamespaceModuleNameUiComponentFormCategoryOptions"/>
</settings>
</select>
</formElements>
Now create Js file to map the field's value:
Namespace_Modulename/view/adminhtml/web/js/select-category.js
define([
'Magento_Ui/js/form/element/ui-select'
], function (Select) {
'use strict';
return Select.extend({
/**
* Parse data and set it to options.
*
* @param {Object} data - Response data object.
* @returns {Object}
*/
setParsed: function (data) {
var option = this.parseData(data);
if (data.error) {
return this;
}
this.options();
this.setOption(option);
this.set('newOption', option);
},
/**
* Normalize option object.
*
* @param {Object} data - Option object.
* @returns {Object}
*/
parseData: function (data) {
return {
value: data.category.entity_id,
label: data.category.name
};
}
});
});
Create a file to get options to display:
NamespaceModuleNameUiComponentFormCategoryOptions.php
<?php
namespace NamespaceModuleNameUiComponentFormCategory;
use MagentoFrameworkDataOptionSourceInterface;
use MagentoCategoryModelResourceModelCategoryCollectionFactory as CategoryCollectionFactory;
use MagentoFrameworkAppRequestInterface;
/**
* Options tree for "Categories" field
*/
class Options implements OptionSourceInterface
{
protected $categoryCollectionFactory;
/**
* @var RequestInterface
*/
protected $request;
/**
* @var array
*/
protected $categoryTree;
/**
* @param CategoryCollectionFactory $categoryCollectionFactory
* @param RequestInterface $request
*/
public function __construct(
CategoryCollectionFactory $categoryCollectionFactory,
RequestInterface $request
) {
$this->categoryCollectionFactory = $categoryCollectionFactory;
$this->request = $request;
}
/**
* {@inheritdoc}
*/
public function toOptionArray()
{
return $this->getCategoryTree();
}
/**
* Retrieve categories tree
*
* @return array
*/
protected function getCategoryTree()
{
if ($this->categoryTree === null) {
$collection = $this->categoryCollectionFactory->create();
$collection->addNameToSelect();
foreach ($collection as $category) {
$categoryId = $category->getEntityId();
if (!isset($categoryById[$categoryId])) {
$categoryById[$categoryId] = [
'value' => $categoryId
];
}
$categoryById[$categoryId]['label'] = $category->getName();
}
$this->categoryTree = $categoryById;
}
return $this->categoryTree;
}
}
Hope it helps!
You can create your own tree with custom collection as follows:
Firstly add a field in your ui-form:
<field name="custom" component="Namespce_Modulename/js/select-category" sortOrder="20" formElement="select">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filterOptions" xsi:type="boolean">true</item>//to add filter in select-ui
<item name="multiple" xsi:type="boolean">false</item>//select multiple or not
<item name="showCheckbox" xsi:type="boolean">true</item>//to show checkboxes
<item name="disableLabel" xsi:type="boolean">true</item>
</item>
</argument>
<settings>
<required>true</required>
<validation>
<rule name="required-entry" xsi:type="boolean">true</rule>
</validation>
<elementTmpl>ui/grid/filters/elements/ui-select</elementTmpl>
<label translate="true">Select Category</label>//label to Field
<dataScope>data.custom</dataScope>//To map
<componentType>field</componentType>
<listens>
<link name="${ $.namespace }.${ $.namespace }:responseData">setParsed</link>
</listens>
</settings>
<formElements>
<select>
<settings>
<options class="NamespaceModuleNameUiComponentFormCategoryOptions"/>
</settings>
</select>
</formElements>
Now create Js file to map the field's value:
Namespace_Modulename/view/adminhtml/web/js/select-category.js
define([
'Magento_Ui/js/form/element/ui-select'
], function (Select) {
'use strict';
return Select.extend({
/**
* Parse data and set it to options.
*
* @param {Object} data - Response data object.
* @returns {Object}
*/
setParsed: function (data) {
var option = this.parseData(data);
if (data.error) {
return this;
}
this.options();
this.setOption(option);
this.set('newOption', option);
},
/**
* Normalize option object.
*
* @param {Object} data - Option object.
* @returns {Object}
*/
parseData: function (data) {
return {
value: data.category.entity_id,
label: data.category.name
};
}
});
});
Create a file to get options to display:
NamespaceModuleNameUiComponentFormCategoryOptions.php
<?php
namespace NamespaceModuleNameUiComponentFormCategory;
use MagentoFrameworkDataOptionSourceInterface;
use MagentoCategoryModelResourceModelCategoryCollectionFactory as CategoryCollectionFactory;
use MagentoFrameworkAppRequestInterface;
/**
* Options tree for "Categories" field
*/
class Options implements OptionSourceInterface
{
protected $categoryCollectionFactory;
/**
* @var RequestInterface
*/
protected $request;
/**
* @var array
*/
protected $categoryTree;
/**
* @param CategoryCollectionFactory $categoryCollectionFactory
* @param RequestInterface $request
*/
public function __construct(
CategoryCollectionFactory $categoryCollectionFactory,
RequestInterface $request
) {
$this->categoryCollectionFactory = $categoryCollectionFactory;
$this->request = $request;
}
/**
* {@inheritdoc}
*/
public function toOptionArray()
{
return $this->getCategoryTree();
}
/**
* Retrieve categories tree
*
* @return array
*/
protected function getCategoryTree()
{
if ($this->categoryTree === null) {
$collection = $this->categoryCollectionFactory->create();
$collection->addNameToSelect();
foreach ($collection as $category) {
$categoryId = $category->getEntityId();
if (!isset($categoryById[$categoryId])) {
$categoryById[$categoryId] = [
'value' => $categoryId
];
}
$categoryById[$categoryId]['label'] = $category->getName();
}
$this->categoryTree = $categoryById;
}
return $this->categoryTree;
}
}
Hope it helps!
answered May 30 '18 at 11:37
user00247user00247
341218
341218
can you please help me on this ? magento.stackexchange.com/questions/249360/…
– Nagaraju Kasa
Nov 8 '18 at 7:17
@NagarajuKasa have you followed above steps?
– user00247
Nov 9 '18 at 7:24
yes @user00247 i have followed your steps, can see steps here magento.stackexchange.com/questions/249360/…
– Nagaraju Kasa
Nov 9 '18 at 8:56
add a comment |
can you please help me on this ? magento.stackexchange.com/questions/249360/…
– Nagaraju Kasa
Nov 8 '18 at 7:17
@NagarajuKasa have you followed above steps?
– user00247
Nov 9 '18 at 7:24
yes @user00247 i have followed your steps, can see steps here magento.stackexchange.com/questions/249360/…
– Nagaraju Kasa
Nov 9 '18 at 8:56
can you please help me on this ? magento.stackexchange.com/questions/249360/…
– Nagaraju Kasa
Nov 8 '18 at 7:17
can you please help me on this ? magento.stackexchange.com/questions/249360/…
– Nagaraju Kasa
Nov 8 '18 at 7:17
@NagarajuKasa have you followed above steps?
– user00247
Nov 9 '18 at 7:24
@NagarajuKasa have you followed above steps?
– user00247
Nov 9 '18 at 7:24
yes @user00247 i have followed your steps, can see steps here magento.stackexchange.com/questions/249360/…
– Nagaraju Kasa
Nov 9 '18 at 8:56
yes @user00247 i have followed your steps, can see steps here magento.stackexchange.com/questions/249360/…
– Nagaraju Kasa
Nov 9 '18 at 8:56
add a comment |
// Get all the children categories of given category collection factory
foreach ($collection as $key => $value) {
$temp = $value->getData();
$categoryObj = $this->_repository->get($temp['entity_id']);
$subcategories = $categoryObj->getChildrenCategories();
foreach($subcategories as $key2 => $subcategorie) {
if($subcategorie->hasChildren()) {
$childCategoryObj = $this->_repository->get($subcategorie->getId());
$childSubcategories = $childCategoryObj->getChildrenCategories();
foreach($childSubcategories as $childSubcategorie) {
$temp1['children'] = $temp2;
}
$temp['children'] = $temp1;
}
}
$item[$key] = $temp;
}
// Here you can get all the children upto 2 level in "item" variable
echo "<pre>";
print_r($item);
New contributor
add a comment |
// Get all the children categories of given category collection factory
foreach ($collection as $key => $value) {
$temp = $value->getData();
$categoryObj = $this->_repository->get($temp['entity_id']);
$subcategories = $categoryObj->getChildrenCategories();
foreach($subcategories as $key2 => $subcategorie) {
if($subcategorie->hasChildren()) {
$childCategoryObj = $this->_repository->get($subcategorie->getId());
$childSubcategories = $childCategoryObj->getChildrenCategories();
foreach($childSubcategories as $childSubcategorie) {
$temp1['children'] = $temp2;
}
$temp['children'] = $temp1;
}
}
$item[$key] = $temp;
}
// Here you can get all the children upto 2 level in "item" variable
echo "<pre>";
print_r($item);
New contributor
add a comment |
// Get all the children categories of given category collection factory
foreach ($collection as $key => $value) {
$temp = $value->getData();
$categoryObj = $this->_repository->get($temp['entity_id']);
$subcategories = $categoryObj->getChildrenCategories();
foreach($subcategories as $key2 => $subcategorie) {
if($subcategorie->hasChildren()) {
$childCategoryObj = $this->_repository->get($subcategorie->getId());
$childSubcategories = $childCategoryObj->getChildrenCategories();
foreach($childSubcategories as $childSubcategorie) {
$temp1['children'] = $temp2;
}
$temp['children'] = $temp1;
}
}
$item[$key] = $temp;
}
// Here you can get all the children upto 2 level in "item" variable
echo "<pre>";
print_r($item);
New contributor
// Get all the children categories of given category collection factory
foreach ($collection as $key => $value) {
$temp = $value->getData();
$categoryObj = $this->_repository->get($temp['entity_id']);
$subcategories = $categoryObj->getChildrenCategories();
foreach($subcategories as $key2 => $subcategorie) {
if($subcategorie->hasChildren()) {
$childCategoryObj = $this->_repository->get($subcategorie->getId());
$childSubcategories = $childCategoryObj->getChildrenCategories();
foreach($childSubcategories as $childSubcategorie) {
$temp1['children'] = $temp2;
}
$temp['children'] = $temp1;
}
}
$item[$key] = $temp;
}
// Here you can get all the children upto 2 level in "item" variable
echo "<pre>";
print_r($item);
New contributor
New contributor
answered 17 mins ago
vivek kumarvivek kumar
11
11
New contributor
New contributor
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f204269%2fhow-to-get-category-tree-in-magento-2%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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