Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Public Member Functions | Protected Member Functions | Protected Attributes
Tree Class Reference
Inheritance diagram for Tree:
AbstractCategory Template Template AbstractBlock DataObject BlockInterface Tree Chooser Chooser

Public Member Functions

 __construct (\Magento\Backend\Block\Template\Context $context, \Magento\Catalog\Model\ResourceModel\Category\Tree $categoryTree, \Magento\Framework\Registry $registry, \Magento\Catalog\Model\CategoryFactory $categoryFactory, \Magento\Framework\Json\EncoderInterface $jsonEncoder, \Magento\Framework\DB\Helper $resourceHelper, \Magento\Backend\Model\Auth\Session $backendSession, array $data=[])
 
 getSuggestedCategoriesJson ($namePart)
 
 getAddRootButtonHtml ()
 
 getAddSubButtonHtml ()
 
 getExpandButtonHtml ()
 
 getCollapseButtonHtml ()
 
 getStoreSwitcherHtml ()
 
 getLoadTreeUrl ($expanded=null)
 
 getNodesUrl ()
 
 getSwitchTreeUrl ()
 
 getIsWasExpanded ()
 
 getMoveUrl ()
 
 getTree ($parenNodeCategory=null)
 
 getTreeJson ($parenNodeCategory=null)
 
 getBreadcrumbsJavascript ($path, $javascriptVarName)
 
 buildNodeName ($node)
 
 isClearEdit ()
 
 canAddRootCategory ()
 
 canAddSubCategory ()
 
- Public Member Functions inherited from AbstractCategory
 __construct (\Magento\Backend\Block\Template\Context $context, \Magento\Catalog\Model\ResourceModel\Category\Tree $categoryTree, \Magento\Framework\Registry $registry, \Magento\Catalog\Model\CategoryFactory $categoryFactory, array $data=[])
 
 getCategory ()
 
 getCategoryId ()
 
 getCategoryName ()
 
 getCategoryPath ()
 
 hasStoreRootCategory ()
 
 getStore ()
 
 getRoot ($parentNodeCategory=null, $recursionLevel=3)
 
 getCategoryCollection ()
 
 getRootByIds ($ids)
 
 getNode ($parentNodeCategory, $recursionLevel=2)
 
 getSaveUrl (array $args=[])
 
 getEditUrl ()
 
 getRootIds ()
 
- Public Member Functions inherited from Template
 __construct (\Magento\Backend\Block\Template\Context $context, array $data=[])
 
 getFormKey ()
 
 isOutputEnabled ($moduleName=null)
 
 getAuthorization ()
 
 getToolbar ()
 
- Public Member Functions inherited from Template
 __construct (Template\Context $context, array $data=[])
 
 setTemplateContext ($templateContext)
 
 getTemplate ()
 
 setTemplate ($template)
 
 getTemplateFile ($template=null)
 
 getArea ()
 
 assign ($key, $value=null)
 
 fetchView ($fileName)
 
 getBaseUrl ()
 
 getObjectData (\Magento\Framework\DataObject $object, $key)
 
 getCacheKeyInfo ()
 
- Public Member Functions inherited from AbstractBlock
 __construct (\Magento\Framework\View\Element\Context $context, array $data=[])
 
 getJsLayout ()
 
 getRequest ()
 
 getParentBlock ()
 
 setLayout (\Magento\Framework\View\LayoutInterface $layout)
 
 getLayout ()
 
 setNameInLayout ($name)
 
 getChildNames ()
 
 setAttribute ($name, $value=null)
 
 setChild ($alias, $block)
 
 addChild ($alias, $block, $data=[])
 
 unsetChild ($alias)
 
 unsetCallChild ($alias, $callback, $result, $params)
 
 unsetChildren ()
 
 getChildBlock ($alias)
 
 getChildHtml ($alias='', $useCache=true)
 
 getChildChildHtml ($alias, $childChildAlias='', $useCache=true)
 
 getBlockHtml ($name)
 
 insert ($element, $siblingName=0, $after=true, $alias='')
 
 append ($element, $alias='')
 
 getGroupChildNames ($groupName)
 
 getChildData ($alias, $key='')
 
 getUiId ($arg1=null, $arg2=null, $arg3=null, $arg4=null, $arg5=null)
 
 getJsId ($arg1=null, $arg2=null, $arg3=null, $arg4=null, $arg5=null)
 
 getUrl ($route='', $params=[])
 
 getViewFileUrl ($fileId, array $params=[])
 
 formatDate ( $date=null, $format=\IntlDateFormatter::SHORT, $showTime=false, $timezone=null)
 
 formatTime ( $time=null, $format=\IntlDateFormatter::SHORT, $showDate=false)
 
 getModuleName ()
 
 escapeHtml ($data, $allowedTags=null)
 
 escapeJs ($string)
 
 escapeHtmlAttr ($string, $escapeSingleQuote=true)
 
 escapeCss ($string)
 
 stripTags ($data, $allowableTags=null, $allowHtmlEntities=false)
 
 escapeUrl ($string)
 
 escapeXssInUrl ($data)
 
 escapeQuote ($data, $addSlashes=false)
 
 escapeJsQuote ($data, $quote='\'')
 
 getNameInLayout ()
 
 getCacheKeyInfo ()
 
 getCacheKey ()
 
 getVar ($name, $module=null)
 
 isScopePrivate ()
 
- Public Member Functions inherited from DataObject
 __construct (array $data=[])
 
 addData (array $arr)
 
 setData ($key, $value=null)
 
 unsetData ($key=null)
 
 getData ($key='', $index=null)
 
 getDataByPath ($path)
 
 getDataByKey ($key)
 
 setDataUsingMethod ($key, $args=[])
 
 getDataUsingMethod ($key, $args=null)
 
 hasData ($key='')
 
 toArray (array $keys=[])
 
 convertToArray (array $keys=[])
 
 toXml (array $keys=[], $rootName='item', $addOpenTag=false, $addCdata=true)
 
 convertToXml (array $arrAttributes=[], $rootName='item', $addOpenTag=false, $addCdata=true)
 
 toJson (array $keys=[])
 
 convertToJson (array $keys=[])
 
 toString ($format='')
 
 __call ($method, $args)
 
 isEmpty ()
 
 serialize ($keys=[], $valueSeparator='=', $fieldSeparator=' ', $quote='"')
 
 debug ($data=null, &$objects=[])
 
 offsetSet ($offset, $value)
 
 offsetExists ($offset)
 
 offsetUnset ($offset)
 
 offsetGet ($offset)
 
- Public Member Functions inherited from BlockInterface
 toHtml ()
 

Protected Member Functions

 _construct ()
 
 _prepareLayout ()
 
 _getNodeJson ($node, $level=0)
 
 _isCategoryMoveable ($node)
 
 _isParentSelectedCategory ($node)
 
- Protected Member Functions inherited from AbstractCategory
 _getDefaultStoreId ()
 
- Protected Member Functions inherited from Template
 _toHtml ()
 
- Protected Member Functions inherited from Template
 _construct ()
 
 _toHtml ()
 
 getRootDirectory ()
 
 getMediaDirectory ()
 
- Protected Member Functions inherited from AbstractBlock
 _construct ()
 
 _prepareLayout ()
 
 _beforeToHtml ()
 
 _afterToHtml ($html)
 
 _toHtml ()
 
 _getNotFoundUrl ($route='', $params=['_direct'=> 'core/index/notFound'])
 
 getCacheTags ()
 
 getCacheLifetime ()
 
 _loadCache ()
 
 _saveCache ($data)
 
 _getSidPlaceholder ($cacheKey=null)
 
- Protected Member Functions inherited from DataObject
 _getData ($key)
 
 _underscore ($name)
 

Protected Attributes

 $_template = 'Magento_Catalog::catalog/category/tree.phtml'
 
 $_backendSession
 
 $_resourceHelper
 
 $_jsonEncoder
 
- Protected Attributes inherited from AbstractCategory
 $_coreRegistry = null
 
 $_categoryTree
 
 $_categoryFactory
 
 $_withProductCount
 
- Protected Attributes inherited from Template
 $_authorization
 
 $mathRandom
 
 $_backendSession
 
 $formKey
 
 $nameBuilder
 
- Protected Attributes inherited from Template
 $_viewVars = []
 
 $_baseUrl
 
 $_jsUrl
 
 $_allowSymlinks
 
 $_filesystem
 
 $_template
 
 $templateEnginePool
 
 $_storeManager
 
 $_appState
 
 $directory
 
 $templateContext
 
 $pageConfig
 
 $resolver
 
 $validator
 
- Protected Attributes inherited from AbstractBlock
 $_design
 
 $_session
 
 $_sidResolver
 
 $_nameInLayout
 
 $_layout
 
 $jsLayout = []
 
 $_request
 
 $_urlBuilder
 
 $_eventManager
 
 $_frontController
 
 $_assetRepo
 
 $_viewConfig
 
 $_cacheState
 
 $_logger
 
 $_escaper
 
 $filterManager
 
 $_localeDate
 
 $inlineTranslation
 
 $_isScopePrivate = false
 
 $_scopeConfig
 
 $_cache
 
- Protected Attributes inherited from DataObject
 $_data = []
 

Additional Inherited Members

- Static Public Member Functions inherited from AbstractBlock
static extractModuleName ($className)
 
- Data Fields inherited from Template
const XML_PATH_TEMPLATE_ALLOW_SYMLINK = 'dev/template/allow_symlink'
 
- Data Fields inherited from AbstractBlock
const CACHE_GROUP = \Magento\Framework\App\Cache\Type\Block::TYPE_IDENTIFIER
 
const CACHE_KEY_PREFIX = 'BLOCK_'
 
- Static Protected Attributes inherited from DataObject
static $_underscoreCache = []
 

Detailed Description

Definition at line 25 of file Tree.php.

Constructor & Destructor Documentation

◆ __construct()

__construct ( \Magento\Backend\Block\Template\Context  $context,
\Magento\Catalog\Model\ResourceModel\Category\Tree  $categoryTree,
\Magento\Framework\Registry  $registry,
\Magento\Catalog\Model\CategoryFactory  $categoryFactory,
\Magento\Framework\Json\EncoderInterface  $jsonEncoder,
\Magento\Framework\DB\Helper  $resourceHelper,
\Magento\Backend\Model\Auth\Session  $backendSession,
array  $data = [] 
)
Parameters
\Magento\Backend\Block\Template\Context$context
\Magento\Catalog\Model\ResourceModel\Category\Tree$categoryTree
\Magento\Framework\Registry$registry
\Magento\Catalog\Model\CategoryFactory$categoryFactory
\Magento\Framework\Json\EncoderInterface$jsonEncoder
\Magento\Framework\DB\Helper$resourceHelper
\Magento\Backend\Model\Auth\Session$backendSession
array$data

Definition at line 57 of file Tree.php.

66  {
67  $this->_jsonEncoder = $jsonEncoder;
68  $this->_resourceHelper = $resourceHelper;
69  $this->_backendSession = $backendSession;
70  parent::__construct($context, $categoryTree, $registry, $categoryFactory, $data);
71  }

Member Function Documentation

◆ _construct()

_construct ( )
protected
Returns
void

Definition at line 76 of file Tree.php.

77  {
78  parent::_construct();
79  $this->setUseAjax(0);
80  }

◆ _getNodeJson()

_getNodeJson (   $node,
  $level = 0 
)
protected

Get JSON of a tree node or an associative array

Parameters
Node | array$node
int$level
Returns
array @SuppressWarnings(PHPMD.CyclomaticComplexity) @SuppressWarnings(PHPMD.NPathComplexity)

Definition at line 332 of file Tree.php.

333  {
334  // create a node from data array
335  if (is_array($node)) {
336  $node = new Node($node, 'entity_id', new \Magento\Framework\Data\Tree());
337  }
338 
339  $item = [];
340  $item['text'] = $this->buildNodeName($node);
341 
342  $rootForStores = in_array($node->getEntityId(), $this->getRootIds());
343 
344  $item['id'] = $node->getId();
345  $item['store'] = (int)$this->getStore()->getId();
346  $item['path'] = $node->getData('path');
347 
348  $item['cls'] = 'folder ' . ($node->getIsActive() ? 'active-category' : 'no-active-category');
349  //$item['allowDrop'] = ($level<3) ? true : false;
350  $allowMove = $this->_isCategoryMoveable($node);
351  $item['allowDrop'] = $allowMove;
352  // disallow drag if it's first level and category is root of a store
353  $item['allowDrag'] = $allowMove && ($node->getLevel() == 1 && $rootForStores ? false : true);
354 
355  if ((int)$node->getChildrenCount() > 0) {
356  $item['children'] = [];
357  }
358 
359  $isParent = $this->_isParentSelectedCategory($node);
360 
361  if ($node->hasChildren()) {
362  $item['children'] = [];
363  if (!($this->getUseAjax() && $node->getLevel() > 1 && !$isParent)) {
364  foreach ($node->getChildren() as $child) {
365  $item['children'][] = $this->_getNodeJson($child, $level + 1);
366  }
367  }
368  }
369 
370  if ($isParent || $node->getLevel() < 2) {
371  $item['expanded'] = true;
372  }
373 
374  return $item;
375  }
return false
Definition: gallery.phtml:36

◆ _isCategoryMoveable()

_isCategoryMoveable (   $node)
protected
Parameters
Node | array$node
Returns
bool

Definition at line 396 of file Tree.php.

397  {
398  $options = new \Magento\Framework\DataObject(['is_moveable' => true, 'category' => $node]);
399 
400  $this->_eventManager->dispatch('adminhtml_catalog_category_tree_is_moveable', ['options' => $options]);
401 
402  return $options->getIsMoveable();
403  }

◆ _isParentSelectedCategory()

_isParentSelectedCategory (   $node)
protected
Parameters
Node | array$node
Returns
bool

Definition at line 409 of file Tree.php.

410  {
411  if ($node && $this->getCategory()) {
412  $pathIds = $this->getCategory()->getPathIds();
413  if (in_array($node->getId(), $pathIds)) {
414  return true;
415  }
416  }
417 
418  return false;
419  }

◆ _prepareLayout()

_prepareLayout ( )
protected
Returns
$this

Definition at line 85 of file Tree.php.

86  {
87  $addUrl = $this->getUrl("*/*/add", ['_current' => false, 'id' => null, '_query' => false]);
88  if ($this->getStore()->getId() == Store::DEFAULT_STORE_ID) {
89  $this->addChild(
90  'add_sub_button',
91  \Magento\Backend\Block\Widget\Button::class,
92  [
93  'label' => __('Add Subcategory'),
94  'onclick' => "addNew('" . $addUrl . "', false)",
95  'class' => 'add',
96  'id' => 'add_subcategory_button',
97  'style' => $this->canAddSubCategory() ? '' : 'display: none;'
98  ]
99  );
100 
101  if ($this->canAddRootCategory()) {
102  $this->addChild(
103  'add_root_button',
104  \Magento\Backend\Block\Widget\Button::class,
105  [
106  'label' => __('Add Root Category'),
107  'onclick' => "addNew('" . $addUrl . "', true)",
108  'class' => 'add',
109  'id' => 'add_root_category_button'
110  ]
111  );
112  }
113  }
114 
115  return parent::_prepareLayout();
116  }
__()
Definition: __.php:13

◆ buildNodeName()

buildNodeName (   $node)

Get category name

Parameters
\Magento\Framework\DataObject$node
Returns
string

Definition at line 383 of file Tree.php.

384  {
385  $result = $this->escapeHtml($node->getName());
386  if ($this->_withProductCount) {
387  $result .= ' (' . $node->getProductCount() . ')';
388  }
389  return $result;
390  }

◆ canAddRootCategory()

canAddRootCategory ( )

Check availability of adding root category

Returns
boolean

Definition at line 436 of file Tree.php.

437  {
438  $options = new \Magento\Framework\DataObject(['is_allow' => true]);
439  $this->_eventManager->dispatch(
440  'adminhtml_catalog_category_tree_can_add_root_category',
441  ['category' => $this->getCategory(), 'options' => $options, 'store' => $this->getStore()->getId()]
442  );
443 
444  return $options->getIsAllow();
445  }

◆ canAddSubCategory()

canAddSubCategory ( )

Check availability of adding sub category

Returns
boolean

Definition at line 452 of file Tree.php.

453  {
454  $options = new \Magento\Framework\DataObject(['is_allow' => true]);
455  $this->_eventManager->dispatch(
456  'adminhtml_catalog_category_tree_can_add_sub_category',
457  ['category' => $this->getCategory(), 'options' => $options, 'store' => $this->getStore()->getId()]
458  );
459 
460  return $options->getIsAllow();
461  }

◆ getAddRootButtonHtml()

getAddRootButtonHtml ( )
Returns
string

Definition at line 187 of file Tree.php.

188  {
189  return $this->getChildHtml('add_root_button');
190  }

◆ getAddSubButtonHtml()

getAddSubButtonHtml ( )
Returns
string

Definition at line 195 of file Tree.php.

196  {
197  return $this->getChildHtml('add_sub_button');
198  }

◆ getBreadcrumbsJavascript()

getBreadcrumbsJavascript (   $path,
  $javascriptVarName 
)

Get JSON of array of categories, that are breadcrumbs for specified category path

Parameters
string$path
string$javascriptVarName
Returns
string

Definition at line 302 of file Tree.php.

303  {
304  if (empty($path)) {
305  return '';
306  }
307 
308  $categories = $this->_categoryTree->setStoreId($this->getStore()->getId())->loadBreadcrumbsArray($path);
309  if (empty($categories)) {
310  return '';
311  }
312  foreach ($categories as $key => $category) {
313  $categories[$key] = $this->_getNodeJson($category);
314  }
315  return '<script>require(["prototype"], function(){' . $javascriptVarName . ' = ' . $this->_jsonEncoder->encode(
317  ) .
318  ';' .
319  ($this->canAddSubCategory() ? '$("add_subcategory_button").show();' : '$("add_subcategory_button").hide();')
320  . '});</script>';
321  }
$categories

◆ getCollapseButtonHtml()

getCollapseButtonHtml ( )
Returns
string

Definition at line 211 of file Tree.php.

212  {
213  return $this->getChildHtml('collapse_button');
214  }

◆ getExpandButtonHtml()

getExpandButtonHtml ( )
Returns
string

Definition at line 203 of file Tree.php.

204  {
205  return $this->getChildHtml('expand_button');
206  }

◆ getIsWasExpanded()

getIsWasExpanded ( )
Returns
bool @SuppressWarnings(PHPMD.BooleanGetMethodName)

Definition at line 260 of file Tree.php.

261  {
262  return $this->_backendSession->getIsTreeWasExpanded();
263  }

◆ getLoadTreeUrl()

getLoadTreeUrl (   $expanded = null)
Parameters
bool | null$expanded
Returns
string

Definition at line 228 of file Tree.php.

229  {
230  $params = ['_current' => true, 'id' => null, 'store' => null];
231  if ($expanded === null && $this->_backendSession->getIsTreeWasExpanded() || $expanded == true) {
232  $params['expand_all'] = true;
233  }
234  return $this->getUrl('*/*/categoriesJson', $params);
235  }
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE]
Definition: website.php:18

◆ getMoveUrl()

getMoveUrl ( )
Returns
string

Definition at line 268 of file Tree.php.

269  {
270  return $this->getUrl('catalog/category/move', ['store' => $this->getRequest()->getParam('store')]);
271  }

◆ getNodesUrl()

getNodesUrl ( )
Returns
string

Definition at line 240 of file Tree.php.

241  {
242  return $this->getUrl('catalog/category/jsonTree');
243  }

◆ getStoreSwitcherHtml()

getStoreSwitcherHtml ( )
Returns
string

Definition at line 219 of file Tree.php.

220  {
221  return $this->getChildHtml('store_switcher');
222  }

◆ getSuggestedCategoriesJson()

getSuggestedCategoriesJson (   $namePart)

Retrieve list of categories with name containing $namePart and their parents

Parameters
string$namePart
Returns
string

Definition at line 124 of file Tree.php.

125  {
126  $storeId = $this->getRequest()->getParam('store', $this->_getDefaultStoreId());
127 
128  /* @var $collection Collection */
129  $collection = $this->_categoryFactory->create()->getCollection();
130 
131  $matchingNamesCollection = clone $collection;
132  $escapedNamePart = $this->_resourceHelper->addLikeEscape(
133  $namePart,
134  ['position' => 'any']
135  );
136  $matchingNamesCollection->addAttributeToFilter(
137  'name',
138  ['like' => $escapedNamePart]
139  )->addAttributeToFilter(
140  'entity_id',
141  ['neq' => \Magento\Catalog\Model\Category::TREE_ROOT_ID]
142  )->addAttributeToSelect(
143  'path'
144  )->setStoreId(
145  $storeId
146  );
147 
148  $shownCategoriesIds = [];
149  foreach ($matchingNamesCollection as $category) {
150  foreach (explode('/', $category->getPath()) as $parentId) {
151  $shownCategoriesIds[$parentId] = 1;
152  }
153  }
154 
155  $collection->addAttributeToFilter(
156  'entity_id',
157  ['in' => array_keys($shownCategoriesIds)]
158  )->addAttributeToSelect(
159  ['name', 'is_active', 'parent_id']
160  )->setStoreId(
161  $storeId
162  );
163 
164  $categoryById = [
167  'children' => [],
168  ],
169  ];
170  foreach ($collection as $category) {
171  foreach ([$category->getId(), $category->getParentId()] as $categoryId) {
172  if (!isset($categoryById[$categoryId])) {
173  $categoryById[$categoryId] = ['id' => $categoryId, 'children' => []];
174  }
175  }
176  $categoryById[$category->getId()]['is_active'] = $category->getIsActive();
177  $categoryById[$category->getId()]['label'] = $category->getName();
178  $categoryById[$category->getParentId()]['children'][] = & $categoryById[$category->getId()];
179  }
180 
181  return $this->_jsonEncoder->encode($categoryById[\Magento\Catalog\Model\Category::TREE_ROOT_ID]['children']);
182  }

◆ getSwitchTreeUrl()

getSwitchTreeUrl ( )
Returns
string

Definition at line 248 of file Tree.php.

249  {
250  return $this->getUrl(
251  'catalog/category/tree',
252  ['_current' => true, 'store' => null, '_query' => false, 'id' => null, 'parent' => null]
253  );
254  }

◆ getTree()

getTree (   $parenNodeCategory = null)
Parameters
mixed | null$parenNodeCategory
Returns
array
Parameters
\Magento\Framework\Data\Tree\Node$node
int$depth
int$currentLevel
Returns
\Magento\Catalog\Api\Data\CategoryTreeInterface

Definition at line 277 of file Tree.php.

278  {
279  $rootArray = $this->_getNodeJson($this->getRoot($parenNodeCategory));
280  $tree = isset($rootArray['children']) ? $rootArray['children'] : [];
281  return $tree;
282  }
getRoot($parentNodeCategory=null, $recursionLevel=3)

◆ getTreeJson()

getTreeJson (   $parenNodeCategory = null)
Parameters
mixed | null$parenNodeCategory
Returns
string

Definition at line 288 of file Tree.php.

289  {
290  $rootArray = $this->_getNodeJson($this->getRoot($parenNodeCategory));
291  $json = $this->_jsonEncoder->encode(isset($rootArray['children']) ? $rootArray['children'] : []);
292  return $json;
293  }
getRoot($parentNodeCategory=null, $recursionLevel=3)

◆ isClearEdit()

isClearEdit ( )

Check if page loaded by outside link to category edit

Returns
boolean

Definition at line 426 of file Tree.php.

427  {
428  return (bool)$this->getRequest()->getParam('clear');
429  }

Field Documentation

◆ $_backendSession

$_backendSession
protected

Definition at line 35 of file Tree.php.

◆ $_jsonEncoder

$_jsonEncoder
protected

Definition at line 45 of file Tree.php.

◆ $_resourceHelper

$_resourceHelper
protected

Definition at line 40 of file Tree.php.

◆ $_template

$_template = 'Magento_Catalog::catalog/category/tree.phtml'
protected

Definition at line 30 of file Tree.php.


The documentation for this class was generated from the following file: