Commit 174fde37 by Manzar Hussain

add taxnomy menu

parent 28e89119
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
CONTENTS OF THIS FILE
---------------------
* Introduction
* Requirements
* Installation
* Configuration
* Maintainers
INTRODUCTION
------------
Hierarchical Taxonomy Menu is a Drupal 8/9 module for creating menus from
taxonomy terms. You can display an image next to a menu item if your terms have
an image field, and there is also an option to make the menu collapsible. This
module comes with a Twig template, so you can customize the HTML structure any
way you want.
* For a full description of the module, visit the project page:
https://www.drupal.org/project/hierarchical_taxonomy_menu
* To submit bug reports and feature suggestions, or to track changes:
https://www.drupal.org/project/issues/hierarchical_taxonomy_menu
REQUIREMENTS
------------
This module requires no modules outside of Drupal core.
INSTALLATION
------------
* Install the Hierarchical Taxonomy Menu module as you would normally install a
contributed Drupal module. Visit https://www.drupal.org/node/1897420 for
further information.
CONFIGURATION
-------------
After you install the module go to the block layout '/admin/structure/block' and
place 'Hierarchical Taxonomy Menu' block to any region you want. In block
settings, you can choose a vocabulary from which you want to create a menu, and
if that vocabulary has image fields you will see multiple options in a select
box. You can limit your menu to a part of taxonomy terms, by selecting a base
term. In this case, menu items will be generated only for its children's terms.
MAINTAINERS
-----------
Current maintainers:
* Goran Nikolovski (gnikolovski) - https://www.drupal.org/u/gnikolovski
This project has been sponsored by:
* Studio Present - https://www.drupal.org/studio-present
{
"name": "drupal/hierarchical_taxonomy_menu",
"description": "Create menus from taxonomy terms.",
"type": "drupal-module",
"homepage": "https://www.drupal.org/project/hierarchical_taxonomy_menu",
"authors": [
{
"name": "Goran Nikolovski",
"email": "goran@gorannikolovski.com",
"homepage": "https://gorannikolovski.com",
"role": "Developer"
}
],
"support": {
"issues": "https://www.drupal.org/project/issues/hierarchical_taxonomy_menu",
"email": "goran@gorannikolovski.com"
},
"license": "GPL-2.0+",
"minimum-stability": "dev",
"require": {
"drupal/core": "^8.6 || ^9"
}
}
block.settings.hierarchical_taxonomy_menu:
type: block_settings
label: 'Hierarchical Taxonomy Menu settings'
mapping:
vocabulary:
type: string
label: 'Use taxonomy terms from this vocabulary to create a menu'
max_depth:
type: integer
label: 'Number of sublevels to display'
dynamic_block_title:
type: boolean
label: 'Make the block title match the current taxonomy term name'
collapsible:
type: boolean
label: 'Make the menu collapsed by default'
stay_open:
type: boolean
label: 'Stay open at the current taxonomy term'
interactive_parent:
type: boolean
label: 'Allow parent items to be collapsible and selectable'
hide_block:
type: boolean
label: 'Hide block if the output is empty'
use_image_style:
type: boolean
label: 'Use image style'
image_height:
type: integer
label: 'Image height (px)'
image_width:
type: integer
label: 'Image width (px)'
image_style:
type: string
label: 'Image style'
max_age:
type: string
label: 'Cache'
base_term:
type: string
label: 'Base term'
dynamic_base_term:
type: boolean
label: 'Dynamic Base term'
show_count:
type: integer
label: 'Show count of referencing entities'
referencing_field:
type: string
label: 'Referencing field'
calculate_count_recursively:
type: boolean
label: 'Calculate count recursively'
.arrow-right {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAALVBMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADBoCg+AAAADnRSTlMAAQsWHyMnQk9hg7bU1uPWfIEAAABZSURBVHgBZY9NGoAgCERHI4gM73/csOlzw1ugPH8AEDETbJrHTMIb8z7mz+jfOXOadce5P58VPUVQ4FgmAMnlVlXQCCzjhYTGiihPyqe7rLJsbay0XoYr478zTgfmno75KQAAAABJRU5ErkJggg==);
background-size: 100% auto;
display: inline-block;
width: 14px;
height: 14px;
cursor: pointer;
}
.arrow-down {
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAALVBMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADBoCg+AAAADnRSTlMAAQsWHyMnQk9hg7bU1uPWfIEAAABlSURBVHjaZY9bEgARDAQH2Y143f+4K0Op2jI/dBMSrIiq4CRYHzPdwuJYx06NPCdv43fMdyXn4qtNwfoXePkOIOMIj0D/QqFE5nHBkpacU2MJOs3mzm9pyMNOY41cw9X6Pdw1/gc85Qfmz9nu9wAAAABJRU5ErkJggg==);
background-size: 100% auto;
display: inline-block;
width: 14px;
height: 14px;
cursor: pointer;
}
/*Hide all submenus by default.*/
.block-taxonomymenu__submenu.collapsed-submenu {
display: none;
}
name: 'Hierarchical Taxonomy Menu'
type: module
description: 'Create menus from taxonomy terms.'
core: 8.x
core_version_requirement: ^8 || ^9
package: Menu
dependencies:
- drupal:taxonomy
- drupal:system (>=8.6.0)
# Information added by Drupal.org packaging script on 2020-11-11
version: '8.x-1.42'
project: 'hierarchical_taxonomy_menu'
datestamp: 1605088406
<?php
/**
* @file
* Installation file for Hierarchical Taxonomy Menu module.
*/
/**
* Convert config values.
*/
function hierarchical_taxonomy_menu_update_8001() {
$config_factory = \Drupal::configFactory();
foreach ($config_factory->listAll('block.block.hierarchicaltaxonomymenu') as $block_config_name) {
$block = $config_factory->getEditable($block_config_name);
$settings = $block->get('settings');
$settings['collapsible'] = (bool) $settings['collapsible'];
$settings['interactive_parent'] = (bool) $settings['interactive_parent'];
$settings['dynamic_base_term'] = (bool) $settings['dynamic_base_term'];
$block->set('settings', $settings);
$block->save();
}
}
/**
* Convert show_count config values from bool to integer.
*/
function hierarchical_taxonomy_menu_update_8002() {
$config_factory = \Drupal::configFactory();
foreach ($config_factory->listAll('block.block.hierarchicaltaxonomymenu') as $block_config_name) {
$block = $config_factory->getEditable($block_config_name);
$settings = $block->get('settings');
$settings['show_count'] = (int) $settings['show_count'];
$block->set('settings', $settings);
$block->save();
}
}
hierarchical_taxonomy_menu:
version: VERSION
css:
theme:
css/hierarchical-taxonomy-menu.css: {}
js:
js/hierarchical-taxonomy-menu.js: {}
dependencies:
- core/jquery
- core/drupal
- core/drupalSettings
<?php
/**
* @file
* Contains hierarchical_taxonomy_menu.module.
*/
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implements hook_help().
*/
function hierarchical_taxonomy_menu_help($route_name, RouteMatchInterface $route_match) {
if ($route_name === 'help.page.hierarchical_taxonomy_menu') {
$readme_file = file_exists(__DIR__ . '/README.md') ? __DIR__ . '/README.md' : __DIR__ . '/README.txt';
if (!file_exists($readme_file)) {
return NULL;
}
$text = file_get_contents($readme_file);
if ($text && !\Drupal::moduleHandler()->moduleExists('markdown')) {
return '<pre>' . $text . '</pre>';
}
else {
// Use the Markdown filter to render the README.
$filter_manager = \Drupal::service('plugin.manager.filter');
$settings = \Drupal::configFactory()->get('markdown.settings')->getRawData();
$config = ['settings' => $settings];
$filter = $filter_manager->createInstance('markdown', $config);
return $filter->process($text, 'en');
}
}
return NULL;
}
/**
* Implements hook_theme().
*/
function hierarchical_taxonomy_menu_theme($existing, $type, $theme, $path) {
return [
'hierarchical_taxonomy_menu' => [
'variables' => [
'menu_tree' => [],
'route_tid' => NULL,
'vocabulary' => NULL,
'current_depth' => 0,
'max_depth' => 0,
'collapsible' => NULL,
],
],
];
}
/**
* Implements template_preprocess_block().
*/
function hierarchical_taxonomy_menu_preprocess_block(&$variables) {
if ($variables['plugin_id'] == 'hierarchical_taxonomy_menu' &&
$variables['configuration']['label_display'] == 'visible' &&
$variables['configuration']['dynamic_block_title']
) {
$term = \Drupal::routeMatch()
->getParameter('taxonomy_term');
if (!$term) {
return NULL;
}
$langcode = \Drupal::languageManager()
->getCurrentLanguage()
->getId();
$translation_languages = $term->getTranslationLanguages();
if (isset($translation_languages[$langcode])) {
$term = $term->getTranslation($langcode);
}
$variables['label'] = $term->getName();
}
}
/**
* Implements hook_theme_suggestions_HOOK().
*/
function hierarchical_taxonomy_menu_theme_suggestions_hierarchical_taxonomy_menu(array $variables) {
if (isset($variables['vocabulary'])) {
return ['hierarchical_taxonomy_menu__' . $variables['vocabulary']];
}
}
<?php
/**
* @file
* Post update functions for hierarchical_taxonomy_menu.
*/
/**
* Clear caches due to config schema changes.
*/
function hierarchical_taxonomy_menu_post_update_updated_config_schema() {
// Empty post-update hook.
}
/**
* @file
* Contains hierarchical-taxonomy-menu.js.
*/
(function ($, Drupal, drupalSettings) {
'use strict';
$(document).ready(function () {
// Show all submenus which have list items with 'menu-item--active' class.
if (drupalSettings.stayOpen === true) {
$('.hierarchical-taxonomy-menu ul.menu').has('.menu-item--active').show();
}
$('.menu-item.menu-item--expanded').each(function (i, obj) {
let self = $(this);
if (self.find('a.active').length) {
self.addClass('active');
if (drupalSettings.interactiveParentMenu) {
if (!self.hasClass('menu-item--active')) {
self.children('i').toggleClass('arrow-right arrow-down');
}
}
}
});
if (drupalSettings.interactiveParentMenu === false) {
$('.hierarchical-taxonomy-menu .menu-item--expanded > a').on('click', function (e) {
e.preventDefault();
let isChildVisible = $(this).parent().children('.menu').is(':visible');
if (isChildVisible) {
$(this).parent().children('.menu').slideUp();
$(this).parent().removeClass('active');
}
else {
$(this).parent().children('.menu').slideDown();
$(this).parent().addClass('active');
}
});
}
else {
$('.hierarchical-taxonomy-menu .menu-item--expanded > .parent-toggle').on('click', function (e) {
e.preventDefault();
$(this).closest('i').toggleClass('arrow-right arrow-down');
let isChildVisible = $(this).parent().children('.menu').is(':visible');
if (isChildVisible) {
$(this).parent().children('.menu').slideUp();
$(this).parent().removeClass('active');
}
else {
$(this).parent().children('.menu').slideDown();
$(this).parent().addClass('active');
}
});
}
});
})(jQuery, Drupal, drupalSettings);
<?php
namespace Drupal\hierarchical_taxonomy_menu\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Routing\ResettableStackedRouteMatchInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a 'HierarchicalTaxonomyMenuBlock' block.
*
* @Block(
* id = "hierarchical_taxonomy_menu",
* admin_label = @Translation("Hierarchical Taxonomy Menu"),
* category = @Translation("Menus")
* )
*/
class HierarchicalTaxonomyMenuBlock extends BlockBase implements ContainerFactoryPluginInterface {
const SHOW_COUNT_NONE = '0';
const SHOW_COUNT_NODE = '1';
const SHOW_COUNT_COMMERCE_PRODUCT = '2';
/**
* Entity mapping.
*
* @var string[]
*/
protected $entitiesMap = [
self::SHOW_COUNT_NONE => '0',
self::SHOW_COUNT_NODE => 'node',
self::SHOW_COUNT_COMMERCE_PRODUCT => 'commerce_product',
];
/**
* The entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManager
*/
protected $entityFieldManager;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* The current route match service.
*
* @var \Drupal\Core\Routing\CurrentRouteMatch
*/
protected $currentRouteMatch;
/**
* The the current primary database.
*
* @var \Drupal\Core\Database\Connection
*/
protected $database;
/**
* The entity type bundle info.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $entityTypeBundleInfo;
/**
* An array to hold the terms cache.
*
* @var array
*/
protected static $terms = [];
/**
* Constructs a HierarchicalTaxonomyMenuBlock object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin ID for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager service.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager service.
* @param \Drupal\Core\Routing\ResettableStackedRouteMatchInterface $current_route_match
* The current route match service.
* @param \Drupal\Core\Database\Connection $database
* The the current primary database.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
* The entity type bundle info.
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
EntityFieldManagerInterface $entity_field_manager,
EntityTypeManagerInterface $entity_type_manager,
LanguageManagerInterface $language_manager,
ResettableStackedRouteMatchInterface $current_route_match,
Connection $database,
EntityTypeBundleInfoInterface $entity_type_bundle_info
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityFieldManager = $entity_field_manager;
$this->entityTypeManager = $entity_type_manager;
$this->languageManager = $language_manager;
$this->currentRouteMatch = $current_route_match;
$this->database = $database;
$this->entityTypeBundleInfo = $entity_type_bundle_info;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_field.manager'),
$container->get('entity_type.manager'),
$container->get('language_manager'),
$container->get('current_route_match'),
$container->get('database'),
$container->get('entity_type.bundle.info')
);
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'vocabulary' => '',
'max_depth' => 100,
'dynamic_block_title' => FALSE,
'collapsible' => FALSE,
'stay_open' => FALSE,
'interactive_parent' => FALSE,
'hide_block' => FALSE,
'use_image_style' => FALSE,
'image_height' => 16,
'image_width' => 16,
'image_style' => '',
'max_age' => 0,
'base_term' => '',
'dynamic_base_term' => FALSE,
'show_count' => '0',
'referencing_field' => '_none',
'calculate_count_recursively' => FALSE,
];
}
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$form['basic'] = [
'#type' => 'details',
'#title' => $this->t('Basic settings'),
];
$form['basic']['vocabulary'] = [
'#title' => $this->t('Use taxonomy terms from this vocabulary to create a menu'),
'#type' => 'select',
'#options' => $this->getVocabularyOptions(),
'#required' => TRUE,
'#default_value' => $this->configuration['vocabulary'],
'#description' => $this->t('You can display an image next to a menu item if your vocabulary has an image field.'),
];
$form['basic']['max_depth'] = [
'#title' => $this->t('Number of sublevels to display'),
'#type' => 'select',
'#options' => [
'0' => '0',
'1' => '1',
'2' => '2',
'3' => '3',
'4' => '4',
'5' => '5',
'6' => '6',
'7' => '7',
'8' => '8',
'9' => '9',
'10' => '10',
'100' => $this->t('Unlimited'),
],
'#default_value' => $this->configuration['max_depth'],
];
$form['basic']['dynamic_block_title'] = [
'#type' => 'checkbox',
'#title' => $this->t('Make the block title match the current taxonomy term name'),
'#default_value' => $this->configuration['dynamic_block_title'],
];
$form['basic']['collapsible'] = [
'#type' => 'checkbox',
'#title' => $this->t('Make the menu collapsed by default'),
'#default_value' => $this->configuration['collapsible'],
];
$form['basic']['stay_open'] = [
'#type' => 'checkbox',
'#title' => $this->t('Stay open at the current taxonomy term'),
'#default_value' => $this->configuration['stay_open'],
'#states' => [
'visible' => [
[
':input[name="settings[basic][collapsible]"]' => ['checked' => TRUE],
],
],
],
];
$form['basic']['interactive_parent'] = [
'#type' => 'checkbox',
'#title' => $this->t('Allow parent items to be collapsible and selectable'),
'#default_value' => $this->configuration['interactive_parent'],
'#states' => [
'visible' => [
[
':input[name="settings[basic][collapsible]"]' => ['checked' => TRUE],
],
],
],
];
$form['basic']['hide_block'] = [
'#type' => 'checkbox',
'#title' => $this->t('Hide block if the output is empty'),
'#default_value' => $this->configuration['hide_block'],
];
$form['image'] = [
'#type' => 'details',
'#title' => $this->t('Image settings'),
];
$form['image']['notice'] = [
'#type' => 'markup',
'#markup' => $this->t('If you are displaying an image next to menu items you can choose the size for that image. You can do that by providing the image size in pixels or by using an image style.'),
];
$form['image']['use_image_style'] = [
'#type' => 'checkbox',
'#title' => $this->t('Use image style'),
'#default_value' => $this->configuration['use_image_style'],
];
$form['image']['image_height'] = [
'#type' => 'number',
'#title' => $this->t('Image height (px)'),
'#default_value' => $this->configuration['image_height'],
'#states' => [
'visible' => [
[
':input[name="settings[image][use_image_style]"]' => ['checked' => FALSE],
],
],
],
];
$form['image']['image_width'] = [
'#type' => 'number',
'#title' => $this->t('Image width (px)'),
'#default_value' => $this->configuration['image_width'],
'#states' => [
'visible' => [
[
':input[name="settings[image][use_image_style]"]' => ['checked' => FALSE],
],
],
],
];
$form['image']['image_style'] = [
'#title' => $this->t('Image style'),
'#type' => 'select',
'#options' => $this->getImageStyleOptions(),
'#default_value' => $this->configuration['image_style'],
'#states' => [
'visible' => [
[
':input[name="settings[image][use_image_style]"]' => ['checked' => TRUE],
],
],
],
];
$form['advanced'] = [
'#type' => 'details',
'#title' => $this->t('Advanced settings'),
];
$form['advanced']['max_age'] = [
'#title' => $this->t('Cache'),
'#type' => 'select',
'#options' => [
'0' => $this->t('No Caching'),
'1800' => $this->t('30 Minutes'),
'3600' => $this->t('1 Hour'),
'21600' => $this->t('6 Hours'),
'43200' => $this->t('12 Hours'),
'86400' => $this->t('1 Day'),
'604800' => $this->t('1 Week'),
'PERMANENT' => $this->t('Permanent'),
],
'#default_value' => $this->configuration['max_age'],
'#description' => $this->t('Set the max age the menu is allowed to be cached for.'),
];
$form['advanced']['base_term'] = [
'#type' => 'textfield',
'#title' => $this->t('Base term'),
'#size' => 20,
'#default_value' => $this->configuration['base_term'],
'#description' => $this->t('Enter a base term and menu items will only be generated for its children. You can enter term ID or term name. Leave empty to generate menu for the entire vocabulary.'),
'#states' => [
'visible' => [
':input[name="settings[advanced][dynamic_base_term]"]' => ['checked' => FALSE],
],
],
];
$form['advanced']['dynamic_base_term'] = [
'#type' => 'checkbox',
'#title' => $this->t('Dynamic Base term'),
'#default_value' => $this->configuration['dynamic_base_term'],
'#description' => $this->t('Automatically set the base term from taxonomy page. The base term is then set to the current term and menu items will only be generated for its children.'),
];
$form['advanced']['show_count'] = [
'#type' => 'radios',
'#title' => $this->t('Show count of referencing entities'),
'#options' => [
0 => $this->t('No'),
1 => $this->t('Show count of referencing nodes'),
2 => $this->t('Show count of referencing commerce products'),
],
'#default_value' => $this->configuration['show_count'],
];
$form['advanced']['referencing_field'] = [
'#type' => 'select',
'#title' => $this->t('Referencing field'),
'#options' => $this->getReferencingFields(),
'#default_value' => $this->configuration['referencing_field'],
'#states' => [
'visible' => [
':input[name="settings[advanced][show_count]"]' => ['value' => '2'],
],
],
];
$form['advanced']['calculate_count_recursively'] = [
'#type' => 'checkbox',
'#title' => $this->t('Calculate count recursively'),
'#default_value' => $this->configuration['calculate_count_recursively'],
];
return $form;
}
/**
* Generates vocabulary select options.
*/
private function getVocabularyOptions() {
$options = [];
$vocabularies = taxonomy_vocabulary_get_names();
foreach ($vocabularies as $vocabulary) {
$fields = $this->entityFieldManager->getFieldDefinitions('taxonomy_term', $vocabulary);
$options[$vocabulary . '|'] = $this->t('@vocabulary (no image)', ['@vocabulary' => ucfirst($vocabulary)]);
foreach ($fields as $field) {
if ($field->getType() == 'image' || $this->isMediaImage($field)) {
$field_name = $field->getName();
$options[$vocabulary . '|' . $field_name] = $this->t('@vocabulary (with image: @image_field)', [
'@vocabulary' => ucfirst($vocabulary),
'@image_field' => $field_name,
]);
}
}
}
return $options;
}
/**
* Whether a field is media type of image.
*
* @param \Drupal\Core\Field\FieldDefinitionInterface $field
* A field to check.
*
* @return bool
* TRUE if this field is media type of image.
*/
protected function isMediaImage(FieldDefinitionInterface $field) {
if ($field->getType() == 'entity_reference' && $field->getSetting('target_type') == 'media') {
if (isset($field->getSetting('handler_settings')['target_bundles']['image'])) {
return TRUE;
}
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function blockValidate($form, FormStateInterface $form_state) {
if (
$form_state->getValue(
[
'advanced',
'show_count',
]
) == self::SHOW_COUNT_COMMERCE_PRODUCT &&
$form_state->getValue(
[
'advanced',
'referencing_field',
]
) == '_none'
) {
$form_state->setErrorByName('advanced][referencing_field', $this->t('Please select referencing field'));
}
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['vocabulary'] = $form_state->getValue(
[
'basic',
'vocabulary',
]
);
$this->configuration['max_depth'] = $form_state->getValue(
[
'basic',
'max_depth',
]
);
$this->configuration['dynamic_block_title'] = $form_state->getValue(
[
'basic',
'dynamic_block_title',
]
);
$this->configuration['collapsible'] = $form_state->getValue(
[
'basic',
'collapsible',
]
);
$this->configuration['stay_open'] = $form_state->getValue(
[
'basic',
'stay_open',
]
);
$this->configuration['interactive_parent'] = $form_state->getValue(
[
'basic',
'interactive_parent',
]
);
$this->configuration['hide_block'] = $form_state->getValue(
[
'basic',
'hide_block',
]
);
$this->configuration['use_image_style'] = $form_state->getValue(
[
'image',
'use_image_style',
]
);
$this->configuration['image_height'] = $form_state->getValue(
[
'image',
'image_height',
]
);
$this->configuration['image_width'] = $form_state->getValue(
[
'image',
'image_width',
]
);
$this->configuration['image_style'] = $form_state->getValue(
[
'image',
'image_style',
]
);
$this->configuration['max_age'] = $form_state->getValue(
[
'advanced',
'max_age',
]
);
$this->configuration['base_term'] = $form_state->getValue(
[
'advanced',
'base_term',
]
);
$this->configuration['dynamic_base_term'] = $form_state->getValue(
[
'advanced',
'dynamic_base_term',
]
);
$this->configuration['show_count'] = $form_state->getValue(
[
'advanced',
'show_count',
]
);
$this->configuration['referencing_field'] = $form_state->getValue(
[
'advanced',
'referencing_field',
]
);
$this->configuration['calculate_count_recursively'] = $form_state->getValue(
[
'advanced',
'calculate_count_recursively',
]
);
}
/**
* {@inheritdoc}
*/
public function build() {
$vocabulary_config = $this->configuration['vocabulary'];
$vocabulary_config = explode('|', $vocabulary_config);
$vocabulary = isset($vocabulary_config[0]) ? $vocabulary_config[0] : NULL;
$base_term = $this->getVocabularyBaseTerm($this->configuration['base_term'], $this->configuration['dynamic_base_term']);
$max_depth = $this->configuration['max_depth'];
$vocabulary_tree = $this->entityTypeManager->getStorage('taxonomy_term')
->loadTree($vocabulary, $base_term, $max_depth + 1);
if ($this->configuration['hide_block'] && !$vocabulary_tree) {
return [];
}
$image_field = isset($vocabulary_config[1]) ? $vocabulary_config[1] : NULL;
$use_image_style = $this->configuration['use_image_style'];
$image_height = $this->configuration['image_height'];
$image_width = $this->configuration['image_width'];
$image_style = $use_image_style == TRUE ? $this->configuration['image_style'] : NULL;
$route_tid = $this->getCurrentRoute();
$max_age = $this->getMaxAge($this->configuration['max_age']);
$interactive_parent = $this->configuration['collapsible'] ? $this->configuration['interactive_parent'] : 0;
$show_count = $this->configuration['show_count'];
$referencing_field = $this->configuration['referencing_field'];
$vocabulary_tree_array = [];
foreach ($vocabulary_tree as $item) {
$vocabulary_tree_array[] = [
'tid' => $item->tid,
'status' => $this->getStatusFromTid($item->tid),
'name' => $this->getNameFromTid($item->tid),
'url' => $this->getLinkFromTid($item->tid),
'parents' => $item->parents,
'use_image_style' => $use_image_style,
'image' => $this->getImageFromTid($item->tid, $image_field, $image_style),
'height' => $image_height != '' ? $image_height : 16,
'width' => $image_width != '' ? $image_width : 16,
'interactive_parent' => $interactive_parent,
'show_count' => $show_count,
'entities' => !empty($show_count) ? $this->getEntityIds($this->entitiesMap[$show_count], $referencing_field, $item->tid, $vocabulary, $this->configuration['calculate_count_recursively']) : [],
];
}
$tree = $this->generateTree($vocabulary_tree_array, $base_term);
return [
'#theme' => 'hierarchical_taxonomy_menu',
'#menu_tree' => $tree,
'#route_tid' => $route_tid,
'#cache' => [
'max-age' => $max_age,
'tags' => [
'taxonomy_term_list',
],
],
'#current_depth' => 0,
'#vocabulary' => $vocabulary,
'#max_depth' => $max_depth,
'#collapsible' => $this->configuration['collapsible'],
'#attached' => [
'library' => [
'hierarchical_taxonomy_menu/hierarchical_taxonomy_menu',
],
'drupalSettings' => [
'stayOpen' => $this->configuration['stay_open'],
'interactiveParentMenu' => $this->configuration['interactive_parent'],
],
],
];
}
/**
* Generates menu tree.
*/
private function generateTree($array, $parent = 0) {
$tree = [];
foreach ($array as $item) {
if (reset($item['parents']) == $parent && $item['status'] == 1) {
$item['subitem'] = isset($item['subitem']) ? $item['subitem'] : $this->generateTree($array, $item['tid']);
$tree[] = $item;
}
}
return $tree;
}
/**
* Gets term name.
*/
private function getNameFromTid($tid) {
$language = $this->languageManager->getCurrentLanguage()->getId();
if (isset(self::$terms[$tid])) {
$term = self::$terms[$tid];
}
else {
$term = $this->entityTypeManager->getStorage('taxonomy_term')->load($tid);
self::$terms[$tid] = $term;
}
$translation_languages = $term->getTranslationLanguages();
if (isset($translation_languages[$language])) {
$term_translated = $term->getTranslation($language);
return $term_translated->getName();
}
return $term->getName();
}
/**
* Gets term status.
*/
private function getStatusFromTid($tid) {
$language = $this->languageManager->getCurrentLanguage()->getId();
if (isset(self::$terms[$tid])) {
$term = self::$terms[$tid];
}
else {
$term = $this->entityTypeManager->getStorage('taxonomy_term')->load($tid);
self::$terms[$tid] = $term;
}
$translation_languages = $term->getTranslationLanguages();
if (isset($translation_languages[$language])) {
$term_translated = $term->getTranslation($language);
return $term_translated->status->value;
}
return $term->status->value;
}
/**
* Gets term url.
*/
private function getLinkFromTid($tid) {
$language = $this->languageManager->getCurrentLanguage()->getId();
if (isset(self::$terms[$tid])) {
$term = self::$terms[$tid];
}
else {
$term = $this->entityTypeManager->getStorage('taxonomy_term')->load($tid);
self::$terms[$tid] = $term;
}
$translation_languages = $term->getTranslationLanguages();
if (isset($translation_languages[$language])) {
/** @var \Drupal\taxonomy\TermInterface $term_translated */
$term_translated = $term->getTranslation($language);
return $term_translated->toUrl();
}
return $term->toUrl();
}
/**
* Gets current route.
*/
private function getCurrentRoute() {
if ($term_id = $this->currentRouteMatch->getRawParameter('taxonomy_term')) {
return $term_id;
}
return NULL;
}
/**
* Gets image from term.
*/
private function getImageFromTid($tid, $image_field, $image_style) {
if (!is_numeric($tid) || $image_field == '') {
return '';
}
if (isset(self::$terms[$tid])) {
$term = self::$terms[$tid];
}
else {
$term = $this->entityTypeManager->getStorage('taxonomy_term')->load($tid);
self::$terms[$tid] = $term;
}
$image_field_name = $term->get($image_field)->getValue();
$image_field_type = $term->get($image_field)->getFieldDefinition()->getType();
if (!isset($image_field_name[0]['target_id'])) {
return '';
}
if ($image_field_type == 'image') {
$fid = $image_field_name[0]['target_id'];
}
else {
// A field of media type.
$fid = FALSE;
foreach ($image_field_name as $value) {
$media = $value['target_id'];
$media = $this->entityTypeManager->getStorage('media')->load($media);
if ($media && $media->bundle() == 'image') {
foreach ($media->referencedEntities() as $item) {
if ($item->getEntityTypeId() == 'file') {
$fid = $item->id();
break;
}
}
}
if ($fid) {
break;
}
}
}
if ($fid) {
$file = $this->entityTypeManager->getStorage('file')->load($fid);
if ($image_style) {
$style = $this->entityTypeManager->getStorage('image_style')->load($image_style);
if ($style) {
$path = $style->buildUrl($file->getFileUri());
}
else {
$path = Url::fromUri(file_create_url($file->getFileUri()));
}
}
else {
$path = Url::fromUri(file_create_url($file->getFileUri()));
}
return $path;
}
return '';
}
/**
* Generates image style select options.
*/
private function getImageStyleOptions() {
$options = [];
$styles = $this->entityTypeManager->getStorage('image_style')->loadMultiple();
foreach ($styles as $style) {
/** @var \Drupal\image\Entity\ImageStyle $style */
$style_name = $style->getName();
$options[$style_name] = $style->label();
}
return $options;
}
/**
* Returns base taxonomy term ID.
*/
private function getVocabularyBaseTerm($base_term, $dynamic_base_term) {
if ($dynamic_base_term) {
if ($term_id = $this->currentRouteMatch->getRawParameter('taxonomy_term')) {
return $term_id;
}
else {
return 0;
}
}
else {
if (!$base_term) {
return 0;
}
if (is_numeric($base_term)) {
return $base_term;
}
else {
$term = $this->entityTypeManager->getStorage('taxonomy_term')
->loadByProperties(['name' => $base_term]);
return $term ? reset($term)->id() : 0;
}
}
}
/**
* Returns Cache Max Age.
*/
public function getMaxAge($max_age) {
if (!$max_age) {
$max_age = 0;
return $max_age;
}
if ($max_age == 'PERMANENT') {
$max_age = Cache::PERMANENT;
return $max_age;
}
else {
return $max_age;
}
}
/**
* Gets all entities referencing the given term.
*/
private function getEntityIds($entity_type_id, $field_name, $tid, $vocabulary, $calculate_count_recursively) {
if (!$calculate_count_recursively) {
return $this->getEntityIdsForTerm($entity_type_id, $field_name, $tid);
}
else {
$entity_ids = $this->getEntityIdsForTerm($entity_type_id, $field_name, $tid);
$child_tids = $this->entityTypeManager
->getStorage('taxonomy_term')
->loadTree($vocabulary, $tid);
foreach ($child_tids as $child_tid) {
$entity_ids = array_merge($entity_ids, $this->getEntityIdsForTerm($entity_type_id, $field_name, $child_tid->tid));
}
return $entity_ids;
}
}
/**
* Gets entities referencing the given term.
*/
private function getEntityIdsForTerm($entity_type_id, $field_name, $tid) {
if (empty($field_name)) {
return [];
}
if ($entity_type_id == 'node') {
return $this->database->select('taxonomy_index', 'ta')
->fields('ta', ['nid'])->distinct(TRUE)
->condition('tid', $tid)
->execute()->fetchCol();
}
else {
return $this->database->select('commerce_product__' . $field_name, 'cp')
->fields('cp', ['entity_id'])->distinct(TRUE)
->condition($field_name . '_target_id', $tid)
->execute()->fetchCol();
}
}
/**
* Gets taxonomy term fields from commerce product entity.
*
* @return array
* An array of taxonomy term fields.
*/
private function getReferencingFields() {
$referencing_fields = [];
$referencing_fields['_none'] = $this->t('- None -');
$bundles = $this->entityTypeBundleInfo
->getBundleInfo('commerce_product');
foreach ($bundles as $bundle => $data) {
$fields = $this->entityFieldManager
->getFieldDefinitions('commerce_product', $bundle);
/** @var \Drupal\Core\Field\FieldDefinitionInterface $field */
foreach ($fields as $field) {
if ($field->getType() == 'entity_reference' && $field->getSetting('target_type') == 'taxonomy_term') {
$referencing_fields[$field->getName()] = $field->getLabel();
}
}
}
return $referencing_fields;
}
/**
* {@inheritdoc}
*/
public function getCacheContexts() {
$dynamic_base_term = $this->configuration['dynamic_base_term'];
if ($dynamic_base_term) {
$base_term = $this->getVocabularyBaseTerm($this->configuration['base_term'], $dynamic_base_term);
if (!$base_term) {
return parent::getCacheContexts();
}
}
return Cache::mergeContexts(parent::getCacheContexts(), ['url.path']);
}
}
{% macro menu_links(menu_tree, route_tid, current_depth, max_depth, collapsible) %}
{% import _self as macros %}
{% for item in menu_tree %}
{%
set liClass = [
item.subitem and current_depth < max_depth ? 'menu-item menu-item--expanded block-taxonomymenu__menu-item block-taxonomymenu__menu-item--expanded' : 'menu-item block-taxonomymenu__menu-item',
route_tid == item.tid ? 'menu-item--active block-taxonomymenu__menu-item--active' : ''
]
%}
<li class="{{ liClass|join(' ') }}">
{% if item.image %}
<img class="menu-item-image block-taxonomymenu__image" src="{{ item.image }}" alt="{{ item.name }}" {% if item.use_image_style == false %}height="{{ item.height }}" width="{{ item.width }}"{% endif %} />
{% endif %}
<a href="{{ item.url }}" class="block-taxonomymenu__link {% if route_tid == item.tid %}active block-taxonomymenu__link--active{% endif %}">{{ item.name }}{% if item.show_count == true %} [{{ item.entities|length }}]{% endif %}</a>
{% if item.subitem and current_depth < max_depth %}
{% if item.interactive_parent %}
<i class="arrow-right parent-toggle" aria-hidden="true"></i><span class="visually-hidden">Expand Secondary Navigation Menu</span>
{% endif %}
{% if collapsible == TRUE %}
<ul class="menu block-taxonomymenu__submenu collapsed-submenu">
{% else %}
<ul class="menu block-taxonomymenu__submenu">
{% endif %}
{{ macros.menu_links(item.subitem, route_tid, current_depth + 1, max_depth, collapsible) }}
</ul>
{% endif %}
</li>
{% endfor %}
{% endmacro %}
{% import _self as macros %}
<ul class="menu hierarchical-taxonomy-menu block-taxonomymenu__menu">
{{ macros.menu_links(menu_tree, route_tid, 0, max_depth, collapsible) }}
</ul>
<?php
namespace Drupal\Tests\hierarchical_taxonomy_menu\Functional;
use Drupal\taxonomy\Entity\Term;
use Drupal\Tests\block\Traits\BlockCreationTrait;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
use Drupal\Tests\taxonomy\Traits\TaxonomyTestTrait;
/**
* Tests the Hierarchical Taxonomy Menu block caching.
*
* @group hierarchical_taxonomy_menu
*/
class HierarchicalTaxonomyMenuCacheTest extends BrowserTestBase {
use BlockCreationTrait;
use TaxonomyTestTrait;
use AssertPageCacheContextsAndTagsTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'block',
'image',
'hierarchical_taxonomy_menu',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* The block.
*
* @var \Drupal\block\Entity\Block
*/
protected $block;
/**
* The user.
*
* @var \Drupal\user\Entity\User
*/
protected $user;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$vocabulary = $this->createVocabulary();
$this->createTerm($vocabulary, [
'name' => 'Term 1',
]);
$this->createTerm($vocabulary, [
'name' => 'Term 2',
]);
$block = $this->drupalPlaceBlock('hierarchical_taxonomy_menu', [
'region' => 'content',
'label' => 'Hierarchical Taxonomy Menu',
'id' => 'hierarchicaltaxonomymenu',
]);
$block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $vocabulary->id() . '|',
'dynamic_block_title' => TRUE,
]);
$block->save();
$this->block = $block;
$user = $this->drupalCreateUser([
'access content',
]);
$this->user = $user;
}
/**
* Tests cache context for anonymous users.
*/
public function testBlockCacheContextAnonymous() {
$this->drupalGet('<front>');
$this->assertCacheContext('url.path');
$this->drupalGet('taxonomy/term/1');
$this->assertCacheContext('url.path');
$block_title_element = $this->getSession()->getPage()->find('css', '#block-hierarchicaltaxonomymenu h2');
$this->assertEqual($block_title_element->getText(), 'Term 1');
$this->drupalGet('taxonomy/term/2');
$this->assertCacheContext('url.path');
$block_title_element = $this->getSession()->getPage()->find('css', '#block-hierarchicaltaxonomymenu h2');
$this->assertEqual($block_title_element->getText(), 'Term 2');
}
/**
* Tests cache context for authenticated users.
*/
public function testBlockCacheContextAuthenticated() {
$this->drupalLogin($this->user);
$this->drupalGet('<front>');
$this->assertCacheContext('url.path');
$this->drupalGet('taxonomy/term/1');
$this->assertCacheContext('url.path');
$block_title_element = $this->getSession()->getPage()->find('css', '#block-hierarchicaltaxonomymenu h2');
$this->assertEqual($block_title_element->getText(), 'Term 1');
$this->drupalGet('taxonomy/term/2');
$this->assertCacheContext('url.path');
$block_title_element = $this->getSession()->getPage()->find('css', '#block-hierarchicaltaxonomymenu h2');
$this->assertEqual($block_title_element->getText(), 'Term 2');
}
/**
* Tests that 'taxonomy_term_list' tag is working for anonymous users.
*/
public function testBlockCacheTagsAnonymous() {
$this->drupalGet('<front>');
$block_element = $this->getSession()->getPage()->find('css', '.block-taxonomymenu__menu');
$this->assertCacheTags(array_merge($this->block->getCacheTags(), [
'block_view',
'config:block_list',
'config:system.site',
'http_response',
'rendered',
'taxonomy_term_list',
]));
$this->assertStringContainsString('Term 1', $block_element->getText());
$this->assertStringContainsString('Term 2', $block_element->getText());
$term1 = Term::load(1);
$term1->name->value = 'Renamed 1';
$term1->save();
$term2 = Term::load(2);
$term2->name->value = 'Renamed 2';
$term2->save();
$this->drupalGet('<front>');
$block_element = $this->getSession()->getPage()->find('css', '.block-taxonomymenu__menu');
$this->assertCacheTags(array_merge($this->block->getCacheTags(), [
'block_view',
'config:block_list',
'config:system.site',
'http_response',
'rendered',
'taxonomy_term_list',
]));
$this->assertStringContainsString('Renamed 1', $block_element->getText());
$this->assertStringContainsString('Renamed 2', $block_element->getText());
}
/**
* Tests that 'taxonomy_term_list' tag is working for authenticated users.
*/
public function testBlockCacheTagsAuthenticated() {
$this->drupalLogin($this->user);
$this->drupalGet('<front>');
$block_element = $this->getSession()->getPage()->find('css', '.block-taxonomymenu__menu');
$this->assertCacheTags(array_merge($this->block->getCacheTags(), [
'block_view',
'config:block_list',
'http_response',
'rendered',
'taxonomy_term_list',
'user_view',
'user:' . $this->user->id(),
]));
$this->assertStringContainsString('Term 1', $block_element->getText());
$this->assertStringContainsString('Term 2', $block_element->getText());
$term1 = Term::load(1);
$term1->name->value = 'Re-renamed 1';
$term1->save();
$term2 = Term::load(2);
$term2->name->value = 'Re-renamed 2';
$term2->save();
$this->drupalGet('<front>');
$block_element = $this->getSession()->getPage()->find('css', '.block-taxonomymenu__menu');
$this->assertCacheTags(array_merge($this->block->getCacheTags(), [
'block_view',
'config:block_list',
'http_response',
'rendered',
'taxonomy_term_list',
'user_view',
'user:' . $this->user->id(),
]));
$this->assertStringContainsString('Re-renamed 1', $block_element->getText());
$this->assertStringContainsString('Re-renamed 2', $block_element->getText());
}
}
<?php
namespace Drupal\Tests\hierarchical_taxonomy_menu\Functional;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\file\Entity\File;
use Drupal\Tests\block\Traits\BlockCreationTrait;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\taxonomy\Traits\TaxonomyTestTrait;
use Drupal\Tests\TestFileCreationTrait;
/**
* Tests the Hierarchical Taxonomy Menu images.
*
* @group hierarchical_taxonomy_menu
*/
class HierarchicalTaxonomyMenuImageTest extends BrowserTestBase {
use BlockCreationTrait;
use TaxonomyTestTrait;
use TestFileCreationTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'block',
'image',
'hierarchical_taxonomy_menu',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* The block.
*
* @var \Drupal\block\Entity\Block
*/
protected $block;
/**
* The vocabulary.
*
* @var \Drupal\taxonomy\VocabularyInterface
*/
protected $vocabulary;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$vocabulary = $this->createVocabulary();
$this->vocabulary = $vocabulary;
FieldStorageConfig::create([
'field_name' => 'field_icon',
'entity_type' => 'taxonomy_term',
'type' => 'image',
'settings' => [],
'cardinality' => 1,
])->save();
$field_config = FieldConfig::create([
'field_name' => 'field_icon',
'label' => 'Icon',
'entity_type' => 'taxonomy_term',
'bundle' => $vocabulary->id(),
'required' => TRUE,
'settings' => [],
'description' => '',
]);
$field_config->save();
$images = $this->getTestFiles('image');
$file1 = File::create([
'uri' => $images[0]->uri,
'status' => FILE_STATUS_PERMANENT,
]);
$file1->save();
$file2 = File::create([
'uri' => $images[1]->uri,
'status' => FILE_STATUS_PERMANENT,
]);
$file2->save();
$this->createTerm($vocabulary, [
'name' => 'Term 1',
'field_icon' => [
'target_id' => $file1->id(),
'alt' => 'First image',
],
]);
$this->createTerm($vocabulary, [
'name' => 'Term 2',
'field_icon' => [
'target_id' => $file2->id(),
'alt' => 'Second image',
],
]);
$block = $this->drupalPlaceBlock('hierarchical_taxonomy_menu', [
'region' => 'content',
'label' => 'Hierarchical Taxonomy Menu',
'id' => 'hierarchicaltaxonomymenu',
]);
$block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $vocabulary->id() . '|field_icon',
'collapsible' => FALSE,
]);
$block->save();
$this->block = $block;
}
/**
* Tests that images are displayed.
*/
public function testBlockImagesEnabled() {
$this->drupalGet('<front>');
$block_element = $this->getSession()->getPage()->find('css', '.block-taxonomymenu__menu');
$this->assertStringContainsString('Term 1', $block_element->getText());
$this->assertStringContainsString('Term 2', $block_element->getText());
$this->assertSession()->elementAttributeContains('css', '.hierarchical-taxonomy-menu li:first-child img', 'alt', 'Term 1');
$this->assertSession()->elementAttributeContains('css', '.hierarchical-taxonomy-menu li:first-child img', 'height', '16');
$this->assertSession()->elementAttributeContains('css', '.hierarchical-taxonomy-menu li:first-child img', 'width', '16');
$this->assertSession()->elementAttributeContains('css', '.hierarchical-taxonomy-menu li:last-child img', 'alt', 'Term 2');
$this->assertSession()->elementAttributeContains('css', '.hierarchical-taxonomy-menu li:last-child img', 'height', '16');
$this->assertSession()->elementAttributeContains('css', '.hierarchical-taxonomy-menu li:last-child img', 'width', '16');
}
/**
* Tests image dimensions.
*/
public function testBlockImageDimensions() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|field_icon',
'collapsible' => FALSE,
'image_height' => 128,
'image_width' => 256,
])->save();
$this->drupalGet('<front>');
$this->assertSession()->elementAttributeContains('css', '.hierarchical-taxonomy-menu li:first-child img', 'height', '128');
$this->assertSession()->elementAttributeContains('css', '.hierarchical-taxonomy-menu li:first-child img', 'width', '256');
$this->assertSession()->elementAttributeContains('css', '.hierarchical-taxonomy-menu li:last-child img', 'height', '128');
$this->assertSession()->elementAttributeContains('css', '.hierarchical-taxonomy-menu li:last-child img', 'width', '256');
}
/**
* Tests image styles.
*/
public function testBlockImageStyles() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|field_icon',
'collapsible' => FALSE,
'use_image_style' => TRUE,
'image_style' => 'medium',
])->save();
$this->drupalGet('<front>');
$image1 = $this->getSession()->getPage()->find('css', '.hierarchical-taxonomy-menu li:first-child img');
$this->assertStringContainsString('files/styles/medium', $image1->getAttribute('src'));
$image2 = $this->getSession()->getPage()->find('css', '.hierarchical-taxonomy-menu li:last-child img');
$this->assertStringContainsString('files/styles/medium', $image2->getAttribute('src'));
}
/**
* Tests that images are not displayed.
*/
public function testBlockImagesDisabled() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|',
'collapsible' => FALSE,
])->save();
$this->drupalGet('<front>');
$block_element = $this->getSession()->getPage()->find('css', '.block-taxonomymenu__menu');
$this->assertStringContainsString('Term 1', $block_element->getText());
$this->assertStringContainsString('Term 2', $block_element->getText());
$this->assertSession()->elementNotExists('css', '.hierarchical-taxonomy-menu li:first-child img');
$this->assertSession()->elementNotExists('css', '.hierarchical-taxonomy-menu li:last-child img');
}
}
<?php
namespace Drupal\Tests\hierarchical_taxonomy_menu\Functional;
use Drupal\Tests\block\Traits\BlockCreationTrait;
use Drupal\Tests\BrowserTestBase;
/**
* Tests the Hierarchical Taxonomy Menu.
*
* @group hierarchical_taxonomy_menu
*/
class HierarchicalTaxonomyMenuTest extends BrowserTestBase {
use BlockCreationTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'block',
'image',
'hierarchical_taxonomy_menu',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$admin_user = $this->drupalCreateUser([
'administer blocks',
'administer site configuration',
'access administration pages',
]);
$this->drupalLogin($admin_user);
}
/**
* Test that the block is available.
*/
public function testBlockAvailability() {
$this->drupalGet('/admin/structure/block');
$this->clickLink('Place block');
$this->assertSession()->pageTextContains('Hierarchical Taxonomy Menu');
$this->assertSession()->linkByHrefExists('admin/structure/block/add/hierarchical_taxonomy_menu/', 0);
}
/**
* Test that the block can be placed.
*/
public function testBlockPlacement() {
$this->drupalPlaceBlock('hierarchical_taxonomy_menu', [
'region' => 'content',
'label' => 'Hierarchical Taxonomy Menu',
'id' => 'hierarchicaltaxonomymenu',
]);
$this->drupalGet('admin/structure/block');
$this->assertSession()->pageTextContains('Hierarchical Taxonomy Menu');
$this->drupalGet('<front>');
$this->assertSession()->pageTextContains('Hierarchical Taxonomy Menu');
}
/**
* Test the block config form integrity.
*/
public function testBlockConfigForm() {
$this->drupalPlaceBlock('hierarchical_taxonomy_menu', [
'region' => 'content',
'label' => 'Hierarchical Taxonomy Menu',
'id' => 'hierarchicaltaxonomymenu',
]);
$this->drupalGet('admin/structure/block/manage/hierarchicaltaxonomymenu');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->fieldExists('settings[basic][vocabulary]');
$this->assertSession()->fieldExists('settings[basic][max_depth]');
$this->assertSession()->optionExists('edit-settings-basic-max-depth', '0');
$this->assertSession()->optionExists('edit-settings-basic-max-depth', '1');
$this->assertSession()->optionExists('edit-settings-basic-max-depth', '2');
$this->assertSession()->optionExists('edit-settings-basic-max-depth', '3');
$this->assertSession()->optionExists('edit-settings-basic-max-depth', '4');
$this->assertSession()->optionExists('edit-settings-basic-max-depth', '5');
$this->assertSession()->optionExists('edit-settings-basic-max-depth', '6');
$this->assertSession()->optionExists('edit-settings-basic-max-depth', '7');
$this->assertSession()->optionExists('edit-settings-basic-max-depth', '8');
$this->assertSession()->optionExists('edit-settings-basic-max-depth', '9');
$this->assertSession()->optionExists('edit-settings-basic-max-depth', '10');
$this->assertSession()->optionExists('edit-settings-basic-max-depth', '100');
$this->assertSession()->fieldExists('settings[basic][dynamic_block_title]');
$this->assertSession()->fieldExists('settings[basic][collapsible]');
$this->assertSession()->fieldExists('settings[basic][stay_open]');
$this->assertSession()->fieldExists('settings[basic][interactive_parent]');
$this->assertSession()->fieldExists('settings[basic][hide_block]');
$this->assertSession()->fieldExists('settings[image][use_image_style]');
$this->assertSession()->fieldExists('settings[image][image_style]');
$this->assertSession()->fieldExists('settings[image][image_height]');
$this->assertSession()->fieldExists('settings[image][image_width]');
$this->assertSession()->optionExists('edit-settings-image-image-style', 'large');
$this->assertSession()->optionExists('edit-settings-image-image-style', 'medium');
$this->assertSession()->optionExists('edit-settings-image-image-style', 'thumbnail');
$this->assertSession()->fieldExists('settings[advanced][max_age]');
$this->assertSession()->optionExists('edit-settings-advanced-max-age', '0');
$this->assertSession()->optionExists('edit-settings-advanced-max-age', '1800');
$this->assertSession()->optionExists('edit-settings-advanced-max-age', '3600');
$this->assertSession()->optionExists('edit-settings-advanced-max-age', '21600');
$this->assertSession()->optionExists('edit-settings-advanced-max-age', '43200');
$this->assertSession()->optionExists('edit-settings-advanced-max-age', '86400');
$this->assertSession()->optionExists('edit-settings-advanced-max-age', '604800');
$this->assertSession()->optionExists('edit-settings-advanced-max-age', 'PERMANENT');
$this->assertSession()->fieldExists('settings[advanced][base_term]');
$this->assertSession()->fieldExists('settings[advanced][dynamic_base_term]');
$this->assertSession()->fieldExists('settings[advanced][show_count]');
$this->assertSession()->fieldExists('settings[advanced][calculate_count_recursively]');
}
}
<?php
namespace Drupal\Tests\hierarchical_taxonomy_menu\Functional;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\taxonomy\Entity\Term;
use Drupal\Tests\block\Traits\BlockCreationTrait;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\taxonomy\Traits\TaxonomyTestTrait;
/**
* Tests the Hierarchical Taxonomy Menu block with translated taxonomy terms.
*
* @group hierarchical_taxonomy_menu
*/
class HierarchicalTaxonomyMenuTranslationTest extends BrowserTestBase {
use BlockCreationTrait;
use TaxonomyTestTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'block',
'image',
'hierarchical_taxonomy_menu',
'taxonomy',
'locale',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$language = ConfigurableLanguage::createFromLangcode('sr');
$language->save();
$admin_user = $this->drupalCreateUser([
'administer blocks',
'administer site configuration',
'access administration pages',
]);
$this->drupalLogin($admin_user);
$vocabulary = $this->createVocabulary();
$parent_term = $this->createTerm($vocabulary, [
'name' => 'Parent',
'langcode' => 'en',
'status' => TRUE,
]);
$child_term = $this->createTerm($vocabulary, [
'name' => 'Child',
'langcode' => 'en',
'status' => TRUE,
]);
$child_term->parent = $parent_term->id();
$child_term->save();
$parent_term_sr = $parent_term->addTranslation('sr');
$parent_term_sr->name = 'Roditelj';
$parent_term_sr->langcode = 'sr';
$parent_term_sr->status = TRUE;
$parent_term_sr->save();
$child_term_sr = $child_term->addTranslation('sr');
$child_term_sr->name = 'Dete';
$child_term_sr->langcode = 'sr';
$child_term_sr->status = TRUE;
$child_term_sr->save();
$block = $this->drupalPlaceBlock('hierarchical_taxonomy_menu', [
'region' => 'content',
'label' => 'Hierarchical Taxonomy Menu',
'id' => 'hierarchicaltaxonomymenu',
]);
$block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $vocabulary->id() . '|',
'dynamic_block_title' => TRUE,
]);
$block->save();
}
/**
* Test translated block content.
*/
public function testTranslatedBlockContent() {
$this->drupalGet('taxonomy/term/1');
$block_element = $this->getSession()->getPage()->find('css', '.block-taxonomymenu__menu');
$this->assertStringContainsString('Parent', $block_element->getText());
$this->assertStringContainsString('Child', $block_element->getText());
$this->drupalGet('sr/taxonomy/term/1');
$block_element = $this->getSession()->getPage()->find('css', '.block-taxonomymenu__menu');
$this->assertStringContainsString('Roditelj', $block_element->getText());
$this->assertStringContainsString('Dete', $block_element->getText());
}
/**
* Test translated terms status.
*/
public function testTranslatedBlockContentWithDisabledChild() {
$this->drupalGet('taxonomy/term/1');
$block_element = $this->getSession()->getPage()->find('css', '.block-taxonomymenu__menu');
$this->assertStringContainsString('Parent', $block_element->getText());
$this->assertStringContainsString('Child', $block_element->getText());
$parent_term = Term::load(1);
$parent_term->status = FALSE;
$parent_term->save();
$this->drupalGet('taxonomy/term/1');
$block_element = $this->getSession()->getPage()->find('css', '.block-taxonomymenu__menu');
$this->assertStringNotContainsString('Parent', $block_element->getText());
$child_term = Term::load(2);
$child_term->status = FALSE;
$child_term->save();
$this->drupalGet('taxonomy/term/1');
$block_element = $this->getSession()->getPage()->find('css', '.block-taxonomymenu__menu');
$this->assertStringNotContainsString('Child', $block_element->getText());
$this->drupalGet('sr/taxonomy/term/1');
$block_element = $this->getSession()->getPage()->find('css', '.block-taxonomymenu__menu');
$this->assertStringContainsString('Roditelj', $block_element->getText());
$this->assertStringContainsString('Dete', $block_element->getText());
$parent_term = Term::load(1);
$parent_term_sr = \Drupal::service('entity.repository')
->getTranslationFromContext($parent_term, 'sr');
$parent_term_sr->status = FALSE;
$parent_term_sr->save();
$this->drupalGet('sr/taxonomy/term/1');
$block_element = $this->getSession()->getPage()->find('css', '.block-taxonomymenu__menu');
$this->assertStringNotContainsString('Roditelj', $block_element->getText());
$child_term = Term::load(2);
$child_term_sr = \Drupal::service('entity.repository')
->getTranslationFromContext($child_term, 'sr');
$child_term_sr->status = FALSE;
$child_term_sr->save();
$this->drupalGet('sr/taxonomy/term/1');
$block_element = $this->getSession()->getPage()->find('css', '.block-taxonomymenu__menu');
$this->assertStringNotContainsString('Dete', $block_element->getText());
}
/**
* Test dynamic block title.
*/
public function testDynamicBlockTitle() {
$this->drupalGet('taxonomy/term/1');
$block_title_element = $this->getSession()->getPage()->find('css', '#block-hierarchicaltaxonomymenu h2');
$this->assertEqual($block_title_element->getText(), 'Parent');
$this->drupalGet('sr/taxonomy/term/1');
$block_title_element = $this->getSession()->getPage()->find('css', '#block-hierarchicaltaxonomymenu h2');
$this->assertEqual($block_title_element->getText(), 'Roditelj');
}
}
<?php
namespace Drupal\Tests\hierarchical_taxonomy_menu\FunctionalJavascript;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
use Drupal\taxonomy\Entity\Term;
use Drupal\Tests\block\Traits\BlockCreationTrait;
use Drupal\Tests\field\Traits\EntityReferenceTestTrait;
use Drupal\Tests\node\Traits\NodeCreationTrait;
use Drupal\Tests\taxonomy\Traits\TaxonomyTestTrait;
/**
* Tests the Hierarchical Taxonomy Menu advanced config options.
*
* @group hierarchical_taxonomy_menu
*/
class HierarchicalTaxonomyMenuAdvancedTest extends WebDriverTestBase {
use BlockCreationTrait;
use TaxonomyTestTrait;
use NodeCreationTrait;
use EntityReferenceTestTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'block',
'image',
'hierarchical_taxonomy_menu',
'taxonomy',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* The vocabulary.
*
* @var \Drupal\taxonomy\VocabularyInterface
*/
protected $vocabulary;
/**
* The parent term ID.
*
* @var int
*/
protected $childParent;
/**
* The placed Hierarchical Taxonomy Menu block.
*
* @var \Drupal\block\Entity\Block
*/
protected $block;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$admin_user = $this->drupalCreateUser([
'administer blocks',
'administer site configuration',
'access administration pages',
]);
$this->drupalLogin($admin_user);
$this->vocabulary = $this->createVocabulary();
// Generate taxonomy tree with 3 parents. Each parent has 11 descendants.
// @codingStandardsIgnoreStart
// Parent term 1 (Term ID: 1)
// Child term 1-1 (Term ID: 2)
// Child term 1-2 (Term ID: 3)
// Child term 1-3 (Term ID: 4)
// Child term 1-4 (Term ID: 5)
// Child term 1-5 (Term ID: 6)
// Child term 1-6 (Term ID: 7)
// Child term 1-7 (Term ID: 8)
// Child term 1-8 (Term ID: 9)
// Child term 1-9 (Term ID: 10)
// Child term 1-10 (Term ID: 11)
// Child term 1-11 (Term ID: 12)
// Parent term 2 (Term ID: 13)
// Child term 2-1 (Term ID: 14)
// Child term 2-2 (Term ID: 15)
// Child term 2-3 (Term ID: 16)
// Child term 2-4 (Term ID: 17)
// Child term 2-5 (Term ID: 18)
// Child term 2-6 (Term ID: 19)
// Child term 2-7 (Term ID: 20)
// Child term 2-8 (Term ID: 21)
// Child term 2-9 (Term ID: 22)
// Child term 2-10 (Term ID: 23)
// Child term 2-11 (Term ID: 24)
// Parent term 3 (Term ID: 25)
// Child term 3-1 (Term ID: 26)
// Child term 3-2 (Term ID: 27)
// Child term 3-3 (Term ID: 28)
// Child term 3-4 (Term ID: 29)
// Child term 3-5 (Term ID: 30)
// Child term 3-6 (Term ID: 31)
// Child term 3-7 (Term ID: 32)
// Child term 3-8 (Term ID: 33)
// Child term 3-9 (Term ID: 34)
// Child term 3-10 (Term ID: 35)
// Child term 3-11 (Term ID: 36)
// @codingStandardsIgnoreEnd
for ($i = 1; $i < 4; $i++) {
$parent = Term::create([
'vid' => $this->vocabulary->id(),
'name' => 'Parent term ' . $i,
]);
$parent->save();
for ($n = 1; $n < 12; $n++) {
$child = Term::create([
'vid' => $this->vocabulary->id(),
'name' => 'Child term ' . $i . '-' . $n,
]);
if ($n == 1) {
$child->parent = $parent->id();
}
else {
$child->parent = $this->childParent;
}
$child->save();
$this->childParent = $child->id();
}
}
$this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
// Create a term reference field on node.
$this->createEntityReferenceField(
'node',
'article',
'field_tags',
'Term reference',
'taxonomy_term',
'default',
['target_bundles' => [$this->vocabulary->id()]],
FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED
);
$this->block = $this->drupalPlaceBlock('hierarchical_taxonomy_menu', [
'region' => 'content',
'label' => 'Hierarchical Taxonomy Menu',
'id' => 'hierarchicaltaxonomymenu',
]);
}
/**
* Test base term.
*/
public function testBaseTerm() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|',
'base_term' => 3,
]);
$this->block->save();
$this->drupalGet('<front>');
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextNotContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
if ($i == 1 && $n > 2) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n);
}
else {
// We need that empty space at the end because Child term 1-10 and
// Child term 1-11 contain substring Child term 1-1.
$this->assertSession()->pageTextNotContains('Child term ' . $i . '-' . $n . ' ');
}
}
}
}
/**
* Test dynamic base term.
*/
public function testDynamicBaseTerm() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|',
'dynamic_base_term' => TRUE,
]);
$this->block->save();
$this->drupalGet('<front>');
// In this case we should see all terms.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n);
}
}
$this->drupalGet('taxonomy/term/1');
// In this case we should see just Term #1 children.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextNotContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
if ($i == 1) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n);
}
else {
$this->assertSession()->pageTextNotContains('Child term ' . $i . '-' . $n);
}
}
}
$this->drupalGet('taxonomy/term/13');
// In this case we should see just Term #13 children.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextNotContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
if ($i == 2) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n);
}
else {
$this->assertSession()->pageTextNotContains('Child term ' . $i . '-' . $n);
}
}
}
$this->drupalGet('taxonomy/term/25');
// In this case we should see just Term #25 children.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextNotContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
if ($i == 3) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n);
}
else {
$this->assertSession()->pageTextNotContains('Child term ' . $i . '-' . $n);
}
}
}
$this->drupalGet('taxonomy/term/33');
// In this case we should see just Term #33 children.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextNotContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
if ($i == 3 && $n > 8) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n);
}
else {
// We need that empty space at the end because Child term 3-10 and
// Child term 3-11 contain substring Child term 3-1.
$this->assertSession()->pageTextNotContains('Child term ' . $i . '-' . $n . ' ');
}
}
}
}
/**
* Test count of referencing nodes.
*/
public function testCountOfReferencingNodes() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|',
'show_count' => TRUE,
]);
$this->block->save();
$this->drupalGet('<front>');
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextContains('Parent term ' . $i . ' [0]');
for ($n = 1; $n < 12; $n++) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n . ' [0]');
}
}
$term = Term::load(1);
$this->drupalCreateNode([
'type' => 'article',
'title' => 'Article 1',
'field_tags' => $term,
]);
$term = Term::load(2);
$this->drupalCreateNode([
'type' => 'article',
'title' => 'Article 2',
'field_tags' => $term,
]);
$term = Term::load(34);
$this->drupalCreateNode([
'type' => 'article',
'title' => 'Article 3',
'field_tags' => $term,
]);
$this->drupalCreateNode([
'type' => 'article',
'title' => 'Article 4',
'field_tags' => $term,
]);
$this->drupalGet('<front>');
for ($i = 1; $i < 4; $i++) {
if ($i == 1) {
$this->assertSession()->pageTextContains('Parent term ' . $i . ' [1]');
}
else {
$this->assertSession()->pageTextContains('Parent term ' . $i . ' [0]');
}
for ($n = 1; $n < 12; $n++) {
if ($i == 1 && $n == 1) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n . ' [1]');
}
elseif ($i == 3 && $n == 9) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n . ' [2]');
}
else {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n . ' [0]');
}
}
}
}
/**
* Test recursively count of referencing nodes.
*/
public function testRecursivelyCountOfReferencingNodes() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|',
'show_count' => TRUE,
'calculate_count_recursively' => TRUE,
]);
$this->block->save();
$this->drupalGet('<front>');
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextContains('Parent term ' . $i . ' [0]');
for ($n = 1; $n < 12; $n++) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n . ' [0]');
}
}
$term = Term::load(1);
$this->drupalCreateNode([
'type' => 'article',
'title' => 'Article 1',
'field_tags' => $term,
]);
$term = Term::load(2);
$this->drupalCreateNode([
'type' => 'article',
'title' => 'Article 2',
'field_tags' => $term,
]);
$term = Term::load(3);
$this->drupalCreateNode([
'type' => 'article',
'title' => 'Article 3',
'field_tags' => $term,
]);
$this->drupalCreateNode([
'type' => 'article',
'title' => 'Article 4',
'field_tags' => $term,
]);
$term = Term::load(4);
$this->drupalCreateNode([
'type' => 'article',
'title' => 'Article 5',
'field_tags' => $term,
]);
$this->drupalCreateNode([
'type' => 'article',
'title' => 'Article 6',
'field_tags' => $term,
]);
$this->drupalGet('<front>');
for ($i = 1; $i < 4; $i++) {
if ($i == 1) {
$this->assertSession()->pageTextContains('Parent term ' . $i . ' [6]');
}
else {
$this->assertSession()->pageTextContains('Parent term ' . $i . ' [0]');
}
for ($n = 1; $n < 12; $n++) {
if ($i == 1 && $n == 1) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n . ' [5]');
}
elseif ($i == 1 && $n == 2) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n . ' [4]');
}
elseif ($i == 1 && $n == 3) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n . ' [2]');
}
else {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n . ' [0]');
}
}
}
}
}
<?php
namespace Drupal\Tests\hierarchical_taxonomy_menu\FunctionalJavascript;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
use Drupal\taxonomy\Entity\Term;
use Drupal\Tests\block\Traits\BlockCreationTrait;
use Drupal\Tests\taxonomy\Traits\TaxonomyTestTrait;
/**
* Tests the Hierarchical Taxonomy Menu basic config options.
*
* @group hierarchical_taxonomy_menu
*/
class HierarchicalTaxonomyMenuBasicTest extends WebDriverTestBase {
use BlockCreationTrait;
use TaxonomyTestTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'block',
'image',
'hierarchical_taxonomy_menu',
'taxonomy',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* The vocabulary.
*
* @var \Drupal\taxonomy\VocabularyInterface
*/
protected $vocabulary;
/**
* The parent term ID.
*
* @var int
*/
protected $childParent;
/**
* The placed Hierarchical Taxonomy Menu block.
*
* @var \Drupal\block\Entity\Block
*/
protected $block;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$admin_user = $this->drupalCreateUser([
'administer blocks',
'administer site configuration',
'access administration pages',
]);
$this->drupalLogin($admin_user);
$this->vocabulary = $this->createVocabulary();
// Generate taxonomy tree with 3 parents. Each parent has 11 descendants.
// @codingStandardsIgnoreStart
// Parent term 1 (Term ID: 1)
// Child term 1-1 (Term ID: 2)
// Child term 1-2 (Term ID: 3)
// Child term 1-3 (Term ID: 4)
// Child term 1-4 (Term ID: 5)
// Child term 1-5 (Term ID: 6)
// Child term 1-6 (Term ID: 7)
// Child term 1-7 (Term ID: 8)
// Child term 1-8 (Term ID: 9)
// Child term 1-9 (Term ID: 10)
// Child term 1-10 (Term ID: 11)
// Child term 1-11 (Term ID: 12)
// Parent term 2 (Term ID: 13)
// Child term 2-1 (Term ID: 14)
// Child term 2-2 (Term ID: 15)
// Child term 2-3 (Term ID: 16)
// Child term 2-4 (Term ID: 17)
// Child term 2-5 (Term ID: 18)
// Child term 2-6 (Term ID: 19)
// Child term 2-7 (Term ID: 20)
// Child term 2-8 (Term ID: 21)
// Child term 2-9 (Term ID: 22)
// Child term 2-10 (Term ID: 23)
// Child term 2-11 (Term ID: 24)
// Parent term 3 (Term ID: 25)
// Child term 3-1 (Term ID: 26)
// Child term 3-2 (Term ID: 27)
// Child term 3-3 (Term ID: 28)
// Child term 3-4 (Term ID: 29)
// Child term 3-5 (Term ID: 30)
// Child term 3-6 (Term ID: 31)
// Child term 3-7 (Term ID: 32)
// Child term 3-8 (Term ID: 33)
// Child term 3-9 (Term ID: 34)
// Child term 3-10 (Term ID: 35)
// Child term 3-11 (Term ID: 36)
// @codingStandardsIgnoreEnd
for ($i = 1; $i < 4; $i++) {
$parent = Term::create([
'vid' => $this->vocabulary->id(),
'name' => 'Parent term ' . $i,
]);
$parent->save();
for ($n = 1; $n < 12; $n++) {
$child = Term::create([
'vid' => $this->vocabulary->id(),
'name' => 'Child term ' . $i . '-' . $n,
]);
if ($n == 1) {
$child->parent = $parent->id();
}
else {
$child->parent = $this->childParent;
}
$child->save();
$this->childParent = $child->id();
}
}
$this->block = $this->drupalPlaceBlock('hierarchical_taxonomy_menu', [
'region' => 'content',
'label' => 'Hierarchical Taxonomy Menu',
'id' => 'hierarchicaltaxonomymenu',
]);
}
/**
* Test zero depth.
*/
public function testZeroDepth() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|',
'max_depth' => 0,
]);
$this->block->save();
$this->drupalGet('<front>');
// We should see just parents. All descendants must be hidden.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
$this->assertSession()->pageTextNotContains('Child term ' . $i . '-' . $n);
}
}
}
/**
* Test unlimited depth.
*/
public function testUnlimitedDepth() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|',
'max_depth' => 100,
]);
$this->block->save();
$this->drupalGet('<front>');
// We should see parents and all descendants.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n);
}
}
}
/**
* Test dynamic block title enabled.
*/
public function testDynamicBlockTitleEnabled() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|',
'dynamic_block_title' => TRUE,
]);
$this->block->save();
$this->drupalGet('taxonomy/term/1');
$block_title_element = $this->getSession()->getPage()->find('css', '#block-hierarchicaltaxonomymenu h2');
$this->assertEqual($block_title_element->getText(), 'Parent term 1');
}
/**
* Test dynamic block title disabled.
*/
public function testDynamicBlockTitleDisabled() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|',
'dynamic_block_title' => FALSE,
]);
$this->block->save();
$this->drupalGet('taxonomy/term/1');
$block_title_element = $this->getSession()->getPage()->find('css', '#block-hierarchicaltaxonomymenu h2');
$this->assertEqual($block_title_element->getText(), 'Hierarchical Taxonomy Menu');
}
/**
* Test the block with collapsed content.
*/
public function testCollapsed() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|',
'collapsible' => TRUE,
]);
$this->block->save();
$this->drupalGet('<front>');
// We should see just parents. All descendants must be hidden.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
$this->assertSession()->pageTextNotContains('Child term ' . $i . '-' . $n);
}
}
}
/**
* Test the block with not collapsed content.
*/
public function testNotCollapsed() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|',
'collapsible' => FALSE,
]);
$this->block->save();
$this->drupalGet('<front>');
// We should see parents and all descendants.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n);
}
}
}
/**
* Test the block with collapsed and stay open content.
*/
public function testCollapsedAndStayOpen() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|',
'collapsible' => TRUE,
'stay_open' => TRUE,
]);
$this->block->save();
$this->drupalGet('taxonomy/term/12');
// We should see all parents and all descendants of the first parent.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
if ($i == 1) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n);
}
else {
$this->assertSession()->pageTextNotContains('Child term ' . $i . '-' . $n);
}
}
}
}
/**
* Test the block with collapsed and stay closed content.
*/
public function testCollapsedAndStayClosed() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|',
'collapsible' => TRUE,
'stay_open' => FALSE,
]);
$this->block->save();
$this->drupalGet('taxonomy/term/6');
// We should see just parents. All descendants must be hidden.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
$this->assertSession()->pageTextNotContains('Child term ' . $i . '-' . $n);
}
}
}
/**
* Test the block with collapsed and selectable content.
*/
public function testCollapsedAndSelectable() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|',
'collapsible' => TRUE,
'interactive_parent' => TRUE,
]);
$this->block->save();
$this->drupalGet('<front>');
// We should see 33 toggle arrows.
$toggle_elements = $this->getSession()->getPage()->findAll('css', '#block-hierarchicaltaxonomymenu i.arrow-right.parent-toggle');
$this->assertCount(33, $toggle_elements);
}
/**
* Test the block with no content.
*/
public function testEmptyBlock() {
$vocabulary = $this->createVocabulary();
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $vocabulary->id() . '|',
'hide_block' => FALSE,
]);
$this->block->save();
$this->drupalGet('<front>');
$this->assertSession()->pageTextContains('Hierarchical Taxonomy Menu');
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $vocabulary->id() . '|',
'hide_block' => TRUE,
]);
$this->block->save();
// Empty block should be hidden if 'Hide block if the output is empty' is
// checked.
$this->drupalGet('<front>');
$this->assertSession()->pageTextNotContains('Hierarchical Taxonomy Menu');
}
}
<?php
namespace Drupal\Tests\hierarchical_taxonomy_menu\FunctionalJavascript;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
use Drupal\taxonomy\Entity\Term;
use Drupal\Tests\block\Traits\BlockCreationTrait;
use Drupal\Tests\taxonomy\Traits\TaxonomyTestTrait;
/**
* Tests the Hierarchical Taxonomy Menu dynamic behaviour.
*
* @group hierarchical_taxonomy_menu
*/
class HierarchicalTaxonomyMenuDynamicTest extends WebDriverTestBase {
use BlockCreationTrait;
use TaxonomyTestTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'block',
'image',
'hierarchical_taxonomy_menu',
'taxonomy',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* The vocabulary.
*
* @var \Drupal\taxonomy\VocabularyInterface
*/
protected $vocabulary;
/**
* The parent term ID.
*
* @var int
*/
protected $childParent;
/**
* The placed Hierarchical Taxonomy Menu block.
*
* @var \Drupal\block\Entity\Block
*/
protected $block;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$admin_user = $this->drupalCreateUser([
'administer blocks',
'administer site configuration',
'access administration pages',
]);
$this->drupalLogin($admin_user);
$this->vocabulary = $this->createVocabulary();
// Generate taxonomy tree with 3 parents. Each parent has 11 descendants.
// @codingStandardsIgnoreStart
// Parent term 1 (Term ID: 1)
// Child term 1-1 (Term ID: 2)
// Child term 1-2 (Term ID: 3)
// Child term 1-3 (Term ID: 4)
// Child term 1-4 (Term ID: 5)
// Child term 1-5 (Term ID: 6)
// Child term 1-6 (Term ID: 7)
// Child term 1-7 (Term ID: 8)
// Child term 1-8 (Term ID: 9)
// Child term 1-9 (Term ID: 10)
// Child term 1-10 (Term ID: 11)
// Child term 1-11 (Term ID: 12)
// Parent term 2 (Term ID: 13)
// Child term 2-1 (Term ID: 14)
// Child term 2-2 (Term ID: 15)
// Child term 2-3 (Term ID: 16)
// Child term 2-4 (Term ID: 17)
// Child term 2-5 (Term ID: 18)
// Child term 2-6 (Term ID: 19)
// Child term 2-7 (Term ID: 20)
// Child term 2-8 (Term ID: 21)
// Child term 2-9 (Term ID: 22)
// Child term 2-10 (Term ID: 23)
// Child term 2-11 (Term ID: 24)
// Parent term 3 (Term ID: 25)
// Child term 3-1 (Term ID: 26)
// Child term 3-2 (Term ID: 27)
// Child term 3-3 (Term ID: 28)
// Child term 3-4 (Term ID: 29)
// Child term 3-5 (Term ID: 30)
// Child term 3-6 (Term ID: 31)
// Child term 3-7 (Term ID: 32)
// Child term 3-8 (Term ID: 33)
// Child term 3-9 (Term ID: 34)
// Child term 3-10 (Term ID: 35)
// Child term 3-11 (Term ID: 36)
// @codingStandardsIgnoreEnd
for ($i = 1; $i < 4; $i++) {
$parent = Term::create([
'vid' => $this->vocabulary->id(),
'name' => 'Parent term ' . $i,
]);
$parent->save();
for ($n = 1; $n < 12; $n++) {
$child = Term::create([
'vid' => $this->vocabulary->id(),
'name' => 'Child term ' . $i . '-' . $n,
]);
if ($n == 1) {
$child->parent = $parent->id();
}
else {
$child->parent = $this->childParent;
}
$child->save();
$this->childParent = $child->id();
}
}
$this->block = $this->drupalPlaceBlock('hierarchical_taxonomy_menu', [
'region' => 'content',
'label' => 'Hierarchical Taxonomy Menu',
'id' => 'hierarchicaltaxonomymenu',
]);
}
/**
* Tests dynamic behaviour when menu items are collapsed.
*/
public function testDynamicBehaviourWhenCollapsed() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|',
'collapsible' => TRUE,
]);
$this->block->save();
$this->drupalGet('<front>');
// We should see just parents. All descendants must be hidden.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
$this->assertSession()->pageTextNotContains('Child term ' . $i . '-' . $n);
}
}
$this->clickLink('Parent term 1');
// We should see just parents and first descendant of Parent term 1.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
if ($i == 1 && $n == 1) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n);
}
else {
$this->assertSession()->pageTextNotContains('Child term ' . $i . '-' . $n);
}
}
}
$this->clickLink('Child term 1-1');
// We should see just parents and first descendant of Child term 1-1.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
if ($i == 1 && ($n == 1 || $n == 2)) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n);
}
else {
$this->assertSession()->pageTextNotContains('Child term ' . $i . '-' . $n);
}
}
}
}
/**
* Tests dynamic behaviour when menu items are not collapsed.
*/
public function testDynamicBehaviourWhenNotCollapsed() {
$this->block->set('settings', [
'label' => 'Hierarchical Taxonomy Menu',
'label_display' => 'visible',
'vocabulary' => $this->vocabulary->id() . '|',
'collapsible' => FALSE,
]);
$this->block->save();
$this->drupalGet('<front>');
// We should see all items.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n);
}
}
$this->clickLink('Parent term 1');
// We should see parents and Parent term 2 and 3 descendants.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextContains('Parent term ' . $i);
if ($i == 1) {
for ($n = 1; $n < 12; $n++) {
$this->assertSession()->pageTextNotContains('Child term ' . $i . '-' . $n);
}
}
else {
for ($n = 1; $n < 12; $n++) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n);
}
}
}
$this->clickLink('Parent term 2');
// We should see parents and Parent term 3 descendants.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextContains('Parent term ' . $i);
if ($i == 1 || $i == 2) {
for ($n = 1; $n < 12; $n++) {
$this->assertSession()->pageTextNotContains('Child term ' . $i . '-' . $n);
}
}
else {
for ($n = 1; $n < 12; $n++) {
$this->assertSession()->pageTextContains('Child term ' . $i . '-' . $n);
}
}
}
$this->clickLink('Parent term 3');
// We should see just parents. All descendants must be hidden.
for ($i = 1; $i < 4; $i++) {
$this->assertSession()->pageTextContains('Parent term ' . $i);
for ($n = 1; $n < 12; $n++) {
$this->assertSession()->pageTextNotContains('Child term ' . $i . '-' . $n);
}
}
}
}
language: php
php:
- 5.5
- 5.6
sudo: false
env:
global:
- PATH="$PATH:$HOME/.composer/vendor/bin"
- TESTDIR=$(pwd)
- DRUPAL_TI_MODULE_NAME="taxonomy_menu"
- DRUPAL_TI_SIMPLETEST_GROUP="taxonomy_menu"
- DRUPAL_TI_DB="drupal_travis_$$"
- DRUPAL_TI_DB_URL="mysql://root@127.0.0.1/$DRUPAL_TI_DB"
- DRUPAL_TI_WEBSERVER_URL="http://127.0.0.1"
- DRUPAL_TI_WEBSERVER_PORT="8080"
- DRUPAL_TI_SIMPLETEST_ARGS="--verbose --color --url $DRUPAL_TI_WEBSERVER_URL:$DRUPAL_TI_WEBSERVER_PORT"
# - DRUPAL_TI_PHPUNIT_CORE_SRC_DIRECTORY="./tests/src"
- DRUPAL_TI_ENVIRONMENT="drupal-8"
matrix:
# - DRUPAL_TI_RUNNERS="simpletest phpunit-core"
- DRUPAL_TI_RUNNERS="simpletest"
before_install:
- composer self-update
- composer global require "lionsad/drupal_ti:1.*"
- drupal-ti before_install
install:
- drupal-ti install
before_script:
- drupal-ti before_script
# - DRUPAL_TI_PHPUNIT_ARGS="-c $DRUPAL_TI_DRUPAL_DIR/modules/key/phpunit.xml --coverage-text"
script:
- drupal-ti script
after_script:
- drupal-ti after_script
notifications:
email: false
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
CONTENTS OF THIS FILE
---------------------
* Introduction
* Requirements
* Installation
* Configuration
* Maintainers
INTRODUCTION
------------
The Taxonomy Menu transforms your taxonomy vocabularies into menus.
* For a full description of the module visit:
https://www.drupal.org/project/taxonomy_menu
* To submit bug reports and feature suggestions, or to track changes visit:
https://www.drupal.org/project/issues/taxonomy_menu
* If you prefer GitHub or GitLab, feel free to send a pull/merge request:
https://github.com/unn/taxonomy_menu https://gitlab.com/dstol/taxonomy_menu
REQUIREMENTS
------------
This module requires no modules outside of Drupal core.
INSTALLATION
------------
* Install the Taxonomy Menu module as you would normally install a contributed
Drupal module. Visit https://www.drupal.org/node/1897420 for further
information.
CONFIGURATION
-------------
1. Navigate to Administration > Extend and enable the module.
2. Navigate to Administration > Structure > Taxonomy menu to add a new
taxonomy menu.
3. From the appropriate dropdown, assign a vocabulary.
4. From the appropriate dropdown, assign a menu.
5. Save.
6. Clear caches.
Modify the menu:
Please note - once the taxonomy menu is created, the menu items are decoupled
from the taxonomy.
You can adjust the weight/order of the menu items, the ability to expand, and if
the item is enabled or disabled.
We have built some constraints to ensure the menu items resemble it's associated
taxonomy. First, you cannot adjust the parents. This ensures the original
taxonomy tree stays somewhat in tact. Second, you cannot change the title or
description for taxonomy-generated menu items. This is rendered dynamically from
the original taxonomy.
Caching:
Menu items are heavily cached. Upon making changes to menus and/or taxonomy,
please clear the cache before submitting an issue.
MAINTAINERS
-----------
* Adam Bergstein (nerdstein) - https://www.drupal.org/u/nerdstein
* Andrey Troeglazov (andrey.troeglazov) -
https://www.drupal.org/u/andreytroeglazov
* David Stoline (dstol) - https://www.drupal.org/u/dstol
* Nick Wilde (NickWilde) - https://www.drupal.org/u/nickwilde
Supporting organization
* Hook 42 - https://www.drupal.org/hook-42
Development proudly supported through a PhpStorm license from JetBrains.
<?php
namespace Drupal\taxonomy_menu\Tests;
use Drupal\simpletest\WebTestBase;
/**
* Provides automated tests for the taxonomy_menu module.
*/
class TaxonomyMenuTest extends WebTestBase {
/**
* {@inheritdoc}
*/
public static function getInfo() {
return [
'name' => "taxonomy_menu TaxonomyMenu's controller functionality",
'description' => 'Test Unit for module taxonomy_menu and controller TaxonomyMenu.',
'group' => 'Other',
];
}
/**
* {@inheritdoc}
*/
public function setUp() {
parent::setUp();
}
/**
* Tests taxonomy_menu functionality.
*/
public function testTaxonomyMenu() {
// Check that the basic functions of module taxonomy_menu.
$this->assertEqual(TRUE, TRUE, 'Test Unit Generated via App Console.');
}
}
{
"name": "drupal/taxonomy_menu",
"type": "drupal-module",
"description": "Creates menu items based on associations to taxonomy vocabularies",
"keywords": ["Drupal"],
"license": "GPL-2.0+",
"homepage": "http://drupal.org/project/taxonomy_menu",
"minimum-stability": "dev",
"support": {
"issues": "http://drupal.org/project/taxonomy_menu",
"source": "http://cgit.drupalcode.org/taxonomy_menu"
},
"require": { }
}
taxonomy_menu.taxonomy_menu.*:
type: config_entity
label: 'Taxonomy Menu config'
mapping:
id:
type: string
label: 'ID'
label:
type: label
label: 'Label'
vocabulary:
type: string
label: 'Vocabulary'
menu:
type: string
label: 'Menu'
expanded:
type: boolean
label: 'Expanded'
depth:
type: integer
label: 'Depth'
menu_parent:
type: string
label: 'Menu parent'
description_field_name:
type: string
label: 'Description field name'
use_term_weight_order:
type: boolean
label: 'Use term weight order'
<?php
namespace Drupal\taxonomy_menu\Controller;
use Drupal\Core\Controller\ControllerBase;
/**
* Class TaxonomyMenu.
*
* @package Drupal\taxonomy_menu\Controller
*/
class TaxonomyMenu extends ControllerBase {
/**
* Render taxonomy links.
*
* @return string
* Return Hello string.
*/
public function renderTaxonomyLinks() {
$markup = '';
// Load taxonomy menus.
$storage = \Drupal::entityTypeManager()->getStorage('taxonomy_menu');
$taxonomy_menus = $storage->loadMultiple();
$links = [];
// Get taxonomy and create menu links from vocabularies.
foreach ($taxonomy_menus as $taxonomy_menu) {
$links += $taxonomy_menu->generateTaxonomyLinks([]);
}
return [
'#type' => 'markup',
'#markup' => $this->t($markup),
];
}
}
<?php
namespace Drupal\taxonomy_menu\Controller;
use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Drupal\Core\Entity\EntityInterface;
/**
* Provides a listing of TaxonomyMenu.
*/
class TaxonomyMenuListBuilder extends ConfigEntityListBuilder {
/**
* {@inheritdoc}
*/
public function buildHeader() {
$header['label'] = $this->t('Taxonomy Menu');
$header['id'] = $this->t('Machine name');
$header['expanded'] = $this->t('Expanded');
return $header + parent::buildHeader();
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
$row['label'] = $entity->label();
$row['id'] = $entity->id();
$row['expanded'] = ($entity->expanded) ? $this->t('Yes') : $this->t('No');
// You probably want a few more properties here...
return $row + parent::buildRow($entity);
}
}
<?php
namespace Drupal\taxonomy_menu\Entity;
use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy\TermInterface;
use Drupal\taxonomy_menu\TaxonomyMenuInterface;
/**
* Defines the TaxonomyMenu entity.
*
* @ConfigEntityType(
* id = "taxonomy_menu",
* label = @Translation("Taxonomy menu"),
* handlers = {
* "list_builder" = "Drupal\taxonomy_menu\Controller\TaxonomyMenuListBuilder",
* "form" = {
* "add" = "Drupal\taxonomy_menu\Form\TaxonomyMenuForm",
* "edit" = "Drupal\taxonomy_menu\Form\TaxonomyMenuForm",
* "delete" = "Drupal\Core\Entity\EntityDeleteForm"
* }
* },
* config_prefix = "taxonomy_menu",
* admin_permission = "administer site configuration",
* entity_keys = {
* "id" = "id",
* "label" = "label",
* "uuid" = "uuid"
* },
* links = {
* "edit-form" = "/admin/structure/taxonomy_menu/{taxonomy_menu}",
* "delete-form" = "/admin/structure/taxonomy_menu/{taxonomy_menu}/delete",
* "collection" = "/admin/structure/taxonomy_menu"
* }
* )
*/
class TaxonomyMenu extends ConfigEntityBase implements TaxonomyMenuInterface {
/**
* The TaxonomyMenu ID.
*
* @var string
*/
protected $id;
/**
* The TaxonomyMenu label.
*
* @var string
*/
protected $label;
/**
* The taxonomy vocabulary.
*
* @var string
* The machine name of the vocabulary this entity represents.
*/
protected $vocabulary;
/**
* The depth to generate menu items.
*
* @var int
*/
protected $depth;
/**
* The menu to embed the vocabulary.
*
* @var string
* The machine name of the menu entity.
*/
protected $menu;
/**
* The expanded mode.
*
* @var bool
*/
public $expanded;
/**
* The menu parent.
*
* @var string
*/
protected $menu_parent;
/**
* The name of the description field.
*
* @var string
* The machine name of the field to be used as the description.
*/
protected $description_field_name;
/**
* {@inheritdoc}
*/
public function getVocabulary() {
return $this->vocabulary;
}
/**
* {@inheritdoc}
*/
public function getDepth() {
return $this->depth;
}
/**
* {@inheritdoc}
*/
public function getMenu() {
return $this->menu;
}
/**
* {@inheritdoc}
*/
public function getMenuParent() {
return $this->menu_parent;
}
/**
* Return if menu items should be ordered by the terms weight.
*
* Default value is TRUE.
*
* @return bool
* True or false.
*/
public function useTermWeightOrder() {
return isset($this->use_term_weight_order) ? $this->use_term_weight_order : TRUE;
}
/**
* {@inheritdoc}
*/
public function getDescriptionFieldName() {
return $this->description_field_name;
}
/**
* {@inheritdoc}
*/
public function preSave(EntityStorageInterface $storage) {
parent::preSave($storage);
if (!$this->isNew()) {
foreach (array_keys($this->getLinks([], TRUE)) as $link_key) {
$this->getMenuLinkManager()->removeDefinition($link_key, FALSE);
}
}
$this->addDependency('config', 'system.menu.' . $this->getMenu());
$this->addDependency('config', 'taxonomy.vocabulary.' . $this->getVocabulary());
}
/**
* {@inheritdoc}
*/
public function save() {
// Make sure we don't have any save exceptions before building menu
// definitions.
$return = parent::save();
foreach ($this->getLinks([], TRUE) as $link_key => $link_def) {
$this->getMenuLinkManager()->addDefinition($link_key, $link_def);
}
return $return;
}
/**
* {@inheritdoc}
*/
public function delete() {
foreach (array_keys($this->getLinks([], TRUE)) as $link_key) {
$this->getMenuLinkManager()->removeDefinition($link_key, FALSE);
}
parent::delete();
}
/**
* {@inheritdoc}
*/
public function getLinks($base_plugin_definition = [], $include_base_plugin_id = FALSE) {
/** @var $termStorage \Drupal\taxonomy\TermStorageInterface */
$termStorage = $this->entityTypeManager()->getStorage('taxonomy_term');
// Load taxonomy terms for tax menu vocab.
$terms = $termStorage->loadTree($this->getVocabulary(), 0, $this->getDepth() + 1);
$links = [];
// Create menu links for each term in the vocabulary.
foreach ($terms as $term) {
if (!$term instanceof TermInterface) {
$term = Term::load($term->tid);
}
$mlid = $this->buildMenuPluginId($term, $include_base_plugin_id);
$links[$mlid] = $this->buildMenuDefinition($term, $base_plugin_definition);
}
return $links;
}
/**
* Get the Menu Link Manager
*
* @return \Drupal\Core\Menu\MenuLinkManagerInterface
* The Menu Link Manager Service
*/
protected function getMenuLinkManager() {
return \Drupal::service('plugin.manager.menu.link');
}
/**
* {@inheritdoc}
*/
public function buildMenuPluginId(TermInterface $term, $include_base_plugin_id = TRUE) {
$plugin_id = '';
if ($include_base_plugin_id) {
$plugin_id .= 'taxonomy_menu.menu_link:';
}
$plugin_id .= 'taxonomy_menu.menu_link.' . $this->id() . '.' . $term->id();
return $plugin_id;
}
/**
* Generate a menu link plugin definition for a taxonomy term.
*
* @param \Drupal\taxonomy\TermInterface $term
* The taxonomy term for which to build a menu link render array.
* @param array $base_plugin_definition
* The base plugin definition to merge the link with.
*
* @return array
* The menu link plugin definition.
*/
protected function buildMenuDefinition(TermInterface $term, array $base_plugin_definition) {
$term_id = $term->id();
$term_url = $term->toUrl();
$taxonomy_menu_id = $this->id();
$menu_id = $this->getMenu();
// Determine parent link.
// TODO: Evaluate use case of multiple parents (should we make many menu items?)
$menu_parent_id = NULL;
/* @var $termStorage \Drupal\taxonomy\TermStorageInterface */
$termStorage = $this->entityTypeManager()->getStorage('taxonomy_term');
$parents = $termStorage->loadParents($term_id);
$parents = array_values($parents);
if (is_array($parents) && count($parents) && !is_null($parents[0]) && $parents[0] != '0') {
$menu_parent_id = $this->buildMenuPluginId($parents[0]);
}
// Note: if menu_parent_id is NULL, it will not update the hierarchy properly.
if (empty($menu_parent_id)) {
$menu_parent_id = str_replace($this->getMenu() . ':', '', $this->getMenuParent());
}
// TODO: Consider implementing a forced weight based on taxonomy tree.
// Generate link.
$arguments = ['taxonomy_term' => $term_id];
$link = $base_plugin_definition;
$link += [
'id' => $this->buildMenuPluginId($term),
'title' => $term->label(),
'description' => $term->getDescription(),
'menu_name' => $menu_id,
'expanded' => $this->expanded,
'metadata' => [
'taxonomy_menu_id' => $taxonomy_menu_id,
'taxonomy_term_id' => $term_id,
],
'route_name' => $term_url->getRouteName(),
'route_parameters' => $term_url->getRouteParameters(),
'load arguments' => $arguments,
'parent' => $menu_parent_id,
'provider' => 'taxonomy_menu',
'class' => 'Drupal\taxonomy_menu\Plugin\Menu\TaxonomyMenuMenuLink',
];
// Order by terms weight if configured for this taxonomy_menu.
if ($this->useTermWeightOrder()) {
$link['weight'] = $term->getWeight();
}
\Drupal::moduleHandler()->alter('taxonomy_menu_link', $link, $term);
return $link;
}
}
<?php
namespace Drupal\taxonomy_menu\Form;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\system\Entity\Menu;
/**
* Class TaxonomyMenuForm.
*
* @package Drupal\taxonomy_menu\Form
*/
class TaxonomyMenuForm extends EntityForm {
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
/* @var $taxonomy_menu \Drupal\taxonomy_menu\Entity\TaxonomyMenu */
$taxonomy_menu = $this->entity;
$form['label'] = [
'#type' => 'textfield',
'#title' => $this->t('Label'),
'#maxlength' => 255,
'#default_value' => $taxonomy_menu->label(),
'#description' => $this->t("Label for the Taxonomy Menu."),
'#required' => TRUE,
];
$form['id'] = [
'#type' => 'machine_name',
'#default_value' => $taxonomy_menu->id(),
'#machine_name' => [
'exists' => '\Drupal\taxonomy_menu\Entity\TaxonomyMenu::load',
],
'#disabled' => !$taxonomy_menu->isNew(),
];
// Vocabulary selection.
$options = [];
$vocabulary_storage = \Drupal::entityTypeManager()->getStorage('taxonomy_vocabulary');
foreach ($vocabulary_storage->loadMultiple() as $vocabulary) {
$options[$vocabulary->id()] = $vocabulary->label();
}
$form['vocabulary'] = [
'#type' => 'select',
'#title' => $this->t('Vocabulary'),
'#options' => $options,
'#default_value' => $taxonomy_menu->getVocabulary(),
'#ajax' => [
'callback' => '::ajaxReplaceDescriptionFieldForm',
'wrapper' => 'description-field-container',
'method' => 'replace',
],
];
// Description field selection.
$form['description_container'] = [
'#type' => 'container',
'#prefix' => '<div id="description-field-container">',
'#suffix' => '</div>',
];
$selected_vocabulary = $taxonomy_menu->getVocabulary();
if ($selected_vocabulary) {
$field_definitions = $this->entityManager->getFieldDefinitions('taxonomy_term', $selected_vocabulary);
// Build a field options array.
$field_options = ['' => $this->t('none')];
if (count($field_definitions)) {
foreach ($field_definitions as $field_name => $field_definition) {
$field_options[$field_name] = $field_definition->getName();
}
}
if (count($field_options)) {
$form['description_container']['description_field_name'] = [
'#type' => 'select',
'#title' => $this->t('Description field'),
'#description' => $this->t('Select the field to be used for the menu item description.'),
'#options' => $field_options,
'#default_value' => $taxonomy_menu->getDescriptionFieldName(),
];
}
}
// Menu selection.
$options = [];
$menu_storage = \Drupal::entityTypeManager()->getStorage('menu');
foreach ($menu_storage->loadMultiple() as $menu) {
$options[$menu->id()] = $menu->label();
}
$form['menu'] = [
'#type' => 'select',
'#title' => $this->t('Menu'),
'#options' => $options,
'#default_value' => $taxonomy_menu->getMenu(),
];
$form['expanded'] = [
'#type' => 'checkbox',
'#title' => $this->t('All menus entries expanded'),
'#default_value' => $taxonomy_menu->expanded,
];
$form['depth'] = [
'#type' => 'select',
'#title' => $this->t('Depth'),
'#default_value' => $taxonomy_menu->getDepth(),
'#options' => range(1, 9),
];
// Menu selection.
$custom_menus = Menu::loadMultiple();
foreach ($custom_menus as $menu_name => $menu) {
$custom_menus[$menu_name] = $menu->label();
}
asort($custom_menus);
$menu_parent_selector = \Drupal::service('menu.parent_form_selector');
$available_menus = $custom_menus;
$menu_options = $menu_parent_selector->getParentSelectOptions(NULL, $available_menus);
$form['menu_parent'] = [
'#type' => 'select',
'#title' => $this->t('Parent menu link'),
'#options' => $menu_options,
'#default_value' => $taxonomy_menu->getMenuParent(),
];
// If this checkbox is active, use the term weight for the menu item order.
// Otherwise the menu items will be sorted alphabetically.
// The default is order by weight.
$form['use_term_weight_order'] = [
'#type' => 'checkbox',
'#title' => $this->t('Use term weight order'),
'#default_value' => isset($taxonomy_menu->use_term_weight_order) ? $taxonomy_menu->use_term_weight_order : TRUE,
];
return $form;
}
/**
* AJAX callback; Builds the description field selector.
*/
public static function ajaxReplaceDescriptionFieldForm(array &$form, FormStateInterface $form_state) {
return $form['description_container'];
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$taxonomy_menu = $this->entity;
$status = $taxonomy_menu->save();
if ($status) {
drupal_set_message($this->t('Saved the %label Taxonomy Menu.', [
'%label' => $taxonomy_menu->label(),
]));
}
else {
drupal_set_message($this->t('The %label Taxonomy Menu was not saved.', [
'%label' => $taxonomy_menu->label(),
]));
}
$form_state->setRedirectUrl($taxonomy_menu->toUrl('collection'));
}
}
<?php
namespace Drupal\taxonomy_menu\Plugin\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides menu links for Taxonomy Menus.
*
* @see \Drupal\taxonomy_menu\Plugin\Menu\TaxonomyMenuMenuLink
*/
class TaxonomyMenuMenuLink extends DeriverBase implements ContainerDeriverInterface {
/**
* The taxonomy menu storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $taxonomyMenuStorage;
/**
* Sets up the storage handler.
*
* @param \Drupal\Core\Entity\EntityStorageInterface $taxonomy_menu_storage
* The taxonomy menu storage.
*/
public function __construct(EntityStorageInterface $taxonomy_menu_storage) {
$this->taxonomyMenuStorage = $taxonomy_menu_storage;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id) {
return new static(
$container->get('entity.manager')->getStorage('taxonomy_menu')
);
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
$links = [];
/* @var $taxonomy_menus \Drupal\taxonomy_menu\TaxonomyMenuInterface[] */
$taxonomy_menus = $this->taxonomyMenuStorage->loadMultiple();
//MenuLinkContent entity, menulinkcontent table, look for data
foreach ($taxonomy_menus as $taxonomy_menu) {
/* @var $taxonomy_menu \Drupal\taxonomy_menu\TaxonomyMenuInterface */
$taxonomy_menu->getMenu();
$links = array_merge($links, $taxonomy_menu->getLinks($base_plugin_definition));
}
return $links;
}
}
<?php
namespace Drupal\taxonomy_menu\Plugin\Menu;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Menu\MenuLinkBase;
use Drupal\Core\Menu\StaticMenuLinkOverridesInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines menu links provided by taxonomy menu.
*
* @see \Drupal\taxonony_menu\Plugin\Derivative\TaxonomyMenuMenuLink
*/
class TaxonomyMenuMenuLink extends MenuLinkBase implements ContainerFactoryPluginInterface {
/**
* {@inheritdoc}
*
* Other possible overrides:
* - 'menu_name' => 1,
* - 'parent' => 1,
* - 'title' => 1,
* - 'description' => 1,
* - 'metadata' => 1,
*/
protected $overrideAllowed = [
'weight' => 1,
'expanded' => 1,
'enabled' => 1,
'parent' => 1,
];
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The static menu link service used to store updates to weight/parent etc.
*
* @var \Drupal\Core\Menu\StaticMenuLinkOverridesInterface
*/
protected $staticOverride;
/**
* Constructs a new TaxonomyMenuMenuLink.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Menu\StaticMenuLinkOverridesInterface $static_override
* The static menu override.
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
EntityTypeManagerInterface $entity_type_manager,
StaticMenuLinkOverridesInterface $static_override
) {
$this->configuration = $configuration;
$this->pluginId = $plugin_id;
$this->pluginDefinition = $plugin_definition;
$this->entityTypeManager = $entity_type_manager;
$this->staticOverride = $static_override;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
$container->get('menu_link.static.overrides')
);
}
/**
* {@inheritdoc}
*/
public function getTitle() {
/* @var $link \Drupal\taxonomy\Entity\Term. */
$link = $this->entityTypeManager->getStorage('taxonomy_term')
->load($this->pluginDefinition['metadata']['taxonomy_term_id']);
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
if ($link->hasTranslation($language)) {
$translation = $link->getTranslation($language);
return $translation->label();
}
else {
return $link->label();
}
return NULL;
}
/**
* {@inheritdoc}
*/
public function getDescription() {
/* @var $link \Drupal\taxonomy\Entity\Term. */
$link = $this->entityTypeManager->getStorage('taxonomy_term')
->load($this->pluginDefinition['metadata']['taxonomy_term_id']);
// Get the description field name.
$taxonomy_menu = $this->entityTypeManager->getStorage('taxonomy_menu')->load($this->pluginDefinition['metadata']['taxonomy_menu_id']);
$description_field_name = $taxonomy_menu->getDescriptionFieldName();
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
if ($link->hasTranslation($language)) {
$translation = $link->getTranslation($language);
if (!empty($translation) && $translation->hasField($description_field_name)) {
return $translation->{$description_field_name}->value;
}
}
elseif (!empty($link) && $link->hasField($description_field_name)) {
return $link->{$description_field_name}->value;
}
return NULL;
}
/**
* {@inheritdoc}
*/
public function updateLink(array $new_definition_values, $persist) {
$overrides = array_intersect_key($new_definition_values, $this->overrideAllowed);
// Update the definition.
$this->pluginDefinition = $overrides + $this->pluginDefinition;
if ($persist) {
// TODO - consider any "persistence" back to TaxonomyMenu and/or Taxonomy
// upon menu link update.
// Always save the menu name as an override to avoid defaulting to tools.
$overrides['menu_name'] = $this->pluginDefinition['menu_name'];
$this->staticOverride->saveOverride($this->getPluginId(), $this->pluginDefinition);
}
return $this->pluginDefinition;
}
/**
* {@inheritdoc}
*/
public function isDeletable() {
return TRUE;
}
/**
* {@inheritdoc}
*/
public function deleteLink() {
}
}
<?php
namespace Drupal\taxonomy_menu;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Menu\MenuLinkManagerInterface;
use Drupal\taxonomy\TermInterface;
/**
* Class TaxonomyMenu.
*
* @package Drupal\taxonomy_menu
*/
class TaxonomyMenuHelper {
/**
* Taxonomy Menu storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $menuStorage;
/**
* Menu Link Manager.
*
* @var \Drupal\Core\Menu\MenuLinkManagerInterface
*/
protected $manager;
/**
* Constructor.
*
* @param EntityTypeManagerInterface $entity_type_manager
* @param \Drupal\Core\Menu\MenuLinkManagerInterface $manager
* The menu link manager.
* @internal param EntityTypeManagerInterface $entity_manager The storage interface.* The storage interface.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, MenuLinkManagerInterface $manager) {
$this->menuStorage = $entity_type_manager->getStorage('taxonomy_menu');
$this->manager = $manager;
}
/**
* A reverse lookup of a taxonomy term menus by vocabulary.
*
* @param string $vid
* The vocabulary id.
*
* @return \Drupal\taxonomy_menu\TaxonomyMenuInterface[]
* The Taxonomy Menu
*/
public function getTermMenusByVocabulary($vid) {
return $this->menuStorage->loadByProperties(['vocabulary'=>$vid]);
}
/**
* Create menu entries associate with the vocabulary of this term.
*
* @param \Drupal\taxonomy\TermInterface $term
* Term
*/
public function generateTaxonomyMenuEntries(TermInterface $term, $rebuild_all = TRUE) {
// Load relevant taxonomy menus.
$tax_menus = $this->getTermMenusByVocabulary($term->getVocabularyId());
foreach ($tax_menus as $menu) {
foreach ($menu->getLinks([], TRUE) as $plugin_id => $plugin_def) {
if (!$rebuild_all) {
$plugin_id_parts = explode('.', $plugin_id);
$term_id = array_pop($plugin_id_parts);
if ($term->id() != $term_id) {
continue;
}
}
if ($this->manager->hasDefinition($plugin_id)) {
$this->manager->updateDefinition($plugin_id, $plugin_def);
}
else {
$this->manager->addDefinition($plugin_id, $plugin_def);
}
}
}
}
/**
* Update menu entries associate with the vocabulary of this term.
*
* @param \Drupal\taxonomy\TermInterface $term
* Term
*/
public function updateTaxonomyMenuEntries(TermInterface $term, $rebuild_all = TRUE) {
// Load relevant taxonomy menus.
$tax_menus = $this->getTermMenusByVocabulary($term->getVocabularyId());
/** @var $menu \Drupal\taxonomy_menu\TaxonomyMenuInterface */
foreach ($tax_menus as $menu) {
$links = $menu->getLinks([], TRUE);
foreach ($links as $plugin_id => $plugin_def) {
if (!$rebuild_all) {
$plugin_id_explode = explode('.', $plugin_id);
$term_id = array_pop($plugin_id_explode);
if ($term->id() != $term_id) {
continue;
}
}
if ($this->manager->hasDefinition($plugin_id)) {
$this->manager->updateDefinition($plugin_id, $plugin_def, FALSE);
}
else {
// Remove specific menu link if vid term is different to this old vid.
if ($term->original->getVocabularyId() != $term->getVocabularyId()) {
$this->removeTaxonomyMenuEntries($term->original);
}
$this->manager->addDefinition($plugin_id, $plugin_def);
}
}
}
}
/**
* Remove menu entries associate with the vocabulary of this term.
*
* @param \Drupal\taxonomy\TermInterface $term
* Term.
* @param bool $rebuild_all
* Whether to rebuild all links or not.
*/
public function removeTaxonomyMenuEntries(TermInterface $term, $rebuild_all = TRUE) {
// Load relevant taxonomy menus.
$tax_menus = $this->getTermMenusByVocabulary($term->getVocabularyId());
/** @var $menu \Drupal\taxonomy_menu\TaxonomyMenuInterface */
foreach ($tax_menus as $menu) {
// Remove all links.
if ($rebuild_all) {
$links = array_keys($menu->getLinks([], TRUE));
foreach ($links as $plugin_id) {
$this->manager->removeDefinition($plugin_id, FALSE);
}
// Remove specific term link. Note - this link does not exist in the taxonomy menu and is not in $links.
} else if (!empty($term)) {
$this->manager->removeDefinition($menu->buildMenuPluginId($term), FALSE);
}
}
}
}
<?php
namespace Drupal\taxonomy_menu;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\taxonomy\TermInterface;
/**
* Provides an interface defining a TaxonomyMenu entity.
*/
interface TaxonomyMenuInterface extends ConfigEntityInterface {
/**
* Get the menu that the menu items are being created in.
*
* @return string
* The machine name of the menu entity holding the vocabulary's menu items.
*/
public function getMenu();
/**
* Get the vocabulary being used.
*
* @return string
* The vocabulary whose terms will be used to generate a menu.
*/
public function getVocabulary();
/**
* Get the depth of terms to generate menu items for.
*
* @return int
* The depth.
*/
public function getDepth();
/**
* Get the menu item to use as the parent for the taxonomy menu.
*
* @return string
* The menu item id string.
*/
public function getMenuParent();
/**
* @return string
* The machine name of the field to be used as the description.
*/
public function getDescriptionFieldName();
/**
* Get menu link plugin definitions
*
* @param array $base_plugin_definition
*
* @param bool $include_base_plugin_id
* If true, 'taxonomy_menu.menu_link:' will be prepended to the returned
* plugin ids.
*
* @return array
* Associative array of menu links ids and definitions.
*/
public function getLinks($base_plugin_definition = [], $include_base_plugin_id = FALSE);
/**
* Generates a menu link id for the taxonomy term.
*
* @param \Drupal\taxonomy\TermInterface $term
* Term to build menu item for.
* @param bool $include_base_plugin_id
* Include base plugin id in menu item id.
* @return string
* A unique string id for the menu item.
*/
public function buildMenuPluginId(TermInterface $term, $include_base_plugin_id = TRUE);
}
<?php
namespace Drupal\taxonomy_menu\Tests;
use Drupal\simpletest\WebTestBase;
/**
* Tests the operations of Taxonomy Menu.
*
* @group taxonomy_menu
*/
class TaxonomyMenuOperations extends WebTestBase {
public static $modules = ['taxonomy_menu', 'system', 'menu_ui', 'taxonomy', 'dblog'];
/**
* Set up for all tests.
*/
function setUp() {
parent::setUp();
// Create user with permission to create policy.
$user1 = $this->drupalCreateUser(['administer site configuration', 'administer taxonomy']);
$this->drupalLogin($user1);
// Create a testing taxonomy vocabulary.
$this->drupalGet('admin/structure/taxonomy/add');
$edit = [
'vid' => 'test_tax_vocab',
'name' => 'Test',
];
$this->drupalPostForm(NULL, $edit, t('Save'));
// Create logged in user.
$perms = [
'administer site configuration',
'administer taxonomy',
'administer menu'
//'delete terms in test',
//'edit terms in test'
];
$admin_user = $this->drupalCreateUser($perms);
$this->drupalLogin($admin_user);
// Add sample terms to the vocabulary.
$this->drupalGet('admin/structure/taxonomy/manage/test_tax_vocab/add');
$edit = [
'name[0][value]' => 'test term 1',
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->drupalGet('admin/structure/taxonomy/manage/test_tax_vocab/add');
$edit = [
'name[0][value]' => 'test term 1-A',
'parent[]' => '1',
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->drupalGet('admin/structure/taxonomy/manage/test_tax_vocab/add');
$edit = [
'name[0][value]' => 'test term 2',
];
$this->drupalPostForm(NULL, $edit, t('Save'));
// Create a testing menu.
$this->drupalGet('admin/structure/menu/add');
$edit = [
'id' => 'test-menu',
'label' => 'Test',
];
$this->drupalPostForm(NULL, $edit, t('Save'));
// Create new taxonomy menu.
$this->drupalGet('admin/structure/taxonomy_menu/add');
$edit = [
'id' => 'test_tax_menu',
'label' => 'test tax menu',
'vocabulary' => 'test_tax_vocab',
'menu' => 'test-menu',
'expanded' => 1,
'depth' => '1',
'menu_parent' => 'test-menu:',
];
$this->drupalPostForm(NULL, $edit, t('Save'));
}
/**
* Test creation of taxonomy menu functions.
*/
function testTaxMenuCreate() {
// Check menu for taxonomy-based menu items keyed 1, 2, and 3.
$this->drupalGet('admin/structure/menu/manage/test-menu');
$this->assertFieldByName(
'links[menu_plugin_id:taxonomy_menu.menu_link:taxonomy_menu.menu_link.test_tax_menu.1][enabled]',
NULL,
'I should expect to see enabled field for taxonomy term 1'
);
$this->assertFieldByName(
'links[menu_plugin_id:taxonomy_menu.menu_link:taxonomy_menu.menu_link.test_tax_menu.2][enabled]',
NULL,
'I should expect to see enabled field for taxonomy term 2'
);
$this->assertFieldByName(
'links[menu_plugin_id:taxonomy_menu.menu_link:taxonomy_menu.menu_link.test_tax_menu.3][enabled]',
NULL,
'I should expect to see enabled field for taxonomy term 3'
);
// Check 2 is a parent of 1.
$this->assertFieldByName(
'links[menu_plugin_id:taxonomy_menu.menu_link:taxonomy_menu.menu_link.test_tax_menu.2][parent]',
'taxonomy_menu.menu_link:taxonomy_menu.menu_link.test_tax_menu.1',
'I should expect to see taxonomy term 2 have a parent of taxonomy term 1'
);
}
/**
* Test creation of taxonomy term.
*/
function testTaxTermCreate() {
// Create a new term.
$this->drupalGet('admin/structure/taxonomy/manage/test_tax_vocab/add');
$edit = [
'name[0][value]' => 'test term 3',
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->drupalGet('admin/structure/menu/manage/test-menu');
// Check for it within the menu.
$this->assertFieldByName(
'links[menu_plugin_id:taxonomy_menu.menu_link:taxonomy_menu.menu_link.test_tax_menu.4][enabled]',
NULL,
'I should expect to see enabled field for taxonomy term 4'
);
}
/**
* Test deletion of taxonomy term.
*/
function testTaxTermDelete() {
// Delete a term.
$this->drupalGet('taxonomy/term/3/delete');
$edit = [
];
$this->drupalPostForm(NULL, $edit, t('Delete'));
// Check for it within the menu.
$this->assertNoFieldByName(
'links[menu_plugin_id:taxonomy_menu.menu_link.test.3][enabled]',
NULL,
'I should not expect to see enabled field for taxonomy term 3'
);
}
/**
* Tests if of menu links from taxonony_menu is expanded.
*/
function testTaxMenuLinkExpanded() {
$this->drupalGet('admin/structure/menu/link/taxonomy_menu.menu_link:taxonomy_menu.menu_link.test_tax_menu.1/edit');
$this->assertFieldByName(
'expanded',
1,
'I should expect to see expanded value for menu based on taxonomy term 1'
);
}
}
name: Taxonomy Menu
type: module
description: Embed a taxonomy tree into a menu
# core: 8.x
package: Menu
configure: entity.taxonomy_menu.collection
# Information added by Drupal.org packaging script on 2018-12-22
version: '8.x-3.4'
core: '8.x'
project: 'taxonomy_menu'
datestamp: 1545492795
entity.taxonomy_menu.add_form:
route_name: 'entity.taxonomy_menu.add_form'
title: 'Add Taxonomy menu'
appears_on:
- entity.taxonomy_menu.collection
# Taxonomy Menu menu items definition
entity.taxonomy_menu.collection:
title: 'Taxonomy Menu'
route_name: entity.taxonomy_menu.collection
description: 'List Taxonomy Menus'
parent: system.admin_structure
taxonomy_menu.menu_link:
class: Drupal\taxonomy_menu\Plugin\Menu\TaxonomyMenuMenuLink
deriver: Drupal\taxonomy_menu\Plugin\Derivative\TaxonomyMenuMenuLink
<?php
/**
* @file
* Contains taxonomy_menu.module.
*/
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implements taxonomy_menu_help().
*/
function taxonomy_menu_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.taxonomy_menu':
return t('<p>The Taxonomy Menu module transforms your taxonomy vocabularies into menus.</p>
<p>See the <a href=":project_page">project page on Drupal.org</a> for more details.</p>',
[
':project_page' => 'https://www.drupal.org/project/taxonomy_menu',
]);
}
}
/**
* Implements hook_entity_insert().
*
* Check for taxonomy term insert.
*/
function taxonomy_menu_taxonomy_term_insert(EntityInterface $entity) {
\Drupal::service('taxonomy_menu.helper')->generateTaxonomyMenuEntries($entity, FALSE);
}
/**
* Implements hook_entity_delete().
*
* Check for taxonomy term deletion.
*/
function taxonomy_menu_taxonomy_term_delete(EntityInterface $entity) {
\Drupal::service('taxonomy_menu.helper')->removeTaxonomyMenuEntries($entity, FALSE);
}
/**
* Implements hook_entity_update().
*
* Check for taxonomy term updates.
*/
function taxonomy_menu_taxonomy_term_update(EntityInterface $entity) {
\Drupal::service('taxonomy_menu.helper')->updateTaxonomyMenuEntries($entity, FALSE);
}
# Taxonomy Menu Entity routing definition
entity.taxonomy_menu.collection:
path: '/admin/structure/taxonomy_menu'
defaults:
_entity_list: 'taxonomy_menu'
_title: 'Taxonomy menu Configuration'
requirements:
_permission: 'administer site configuration'
entity.taxonomy_menu.add_form:
path: '/admin/structure/taxonomy_menu/add'
defaults:
_entity_form: 'taxonomy_menu.add'
_title: 'Add Taxonomy menu'
requirements:
_permission: 'administer site configuration'
entity.taxonomy_menu.edit_form:
path: '/admin/structure/taxonomy_menu/{taxonomy_menu}'
defaults:
_entity_form: 'taxonomy_menu.edit'
_title: 'Edit Taxonomy menu'
requirements:
_permission: 'administer site configuration'
entity.taxonomy_menu.delete_form:
path: '/admin/structure/taxonomy_menu/{taxonomy_menu}/delete'
defaults:
_entity_form: 'taxonomy_menu.delete'
_title: 'Delete Taxonomy menu'
requirements:
_permission: 'administer site configuration'
taxonomy_menu.test:
path: '/taxonomy-menu/render-taxonomy-links'
defaults:
_controller: '\Drupal\taxonomy_menu\Controller\TaxonomyMenu::renderTaxonomyLinks'
_title: 'Debugging'
requirements:
_permission: 'administer site configuration'
services:
taxonomy_menu.helper:
class: Drupal\taxonomy_menu\TaxonomyMenuHelper
arguments: ['@entity.manager', '@plugin.manager.menu.link']
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
----------------------
-- Taxonomy Menu UI --
----------------------
This module provides to create menu items on a Taxonomy term page in Drupal 8.
This functionality similar like you create menu items for node. This module
enables the "Available Menus" options on the Taxonomy vocabulary page.
Then on the Taxonomy term add/edit form you can set the menu item for that
term, just as you can do on the node add/edit form.
-----------
-- Usage --
-----------
Configurable per Taxonomy vocabulary on the "Menu Settings" tab, editing your
available menus and default parent item.
Configurable per Taxonomy term on the "Menu Settings" tab, editing your menu
link title, parent item and weight.
Functionality similar with "Menu Settings" tab for node.
# Schema for configuration files of the Taxonomy Menu UI module.
taxonomy.vocabulary.*.third_party.menu_ui:
type: mapping
label: 'Per-content type menu settings'
mapping:
available_menus:
type: sequence
label: 'Available menus'
sequence:
type: string
label: 'Menu machine name'
parent:
type: string
label: 'Parent'
name: Taxonomy Menu UI
type: module
description: 'Add ability to create menu links for taxonomy terms.'
core: 8.x
core_version_requirement: ^8 || ^9
package: Taxonomy
dependencies:
- drupal:taxonomy
- drupal:menu_ui
# Information added by Drupal.org packaging script on 2020-07-17
version: '8.x-1.4'
project: 'taxonomy_menu_ui'
datestamp: 1594974827
<?php
/**
* @file
* Taxonomy Menu UI installation file.
*/
use Drupal\taxonomy\Entity\Vocabulary;
/**
* Implements hook_uninstall().
*/
function taxonomy_menu_ui_uninstall() {
$logger = \Drupal::logger('taxonomy_menu_ui');
/** @var \Drupal\Core\Entity\EntityInterface $bundle */
foreach (Vocabulary::loadMultiple() as $bundle) {
$config_name = 'core.entity_form_display.taxonomy_term.' . $bundle->id() . '.default';
try {
\Drupal::service('config.factory')
->getEditable($config_name)
->clear('content.menu')
->save();
}
catch (\Exception $e) {
$logger->warning(sprintf('Unable to uninstall config: %s.', $config_name));
}
}
}
<?php
/**
* @file
* Add ability to create menu links for taxonomy terms.
*/
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Drupal\taxonomy\VocabularyInterface;
use Drupal\taxonomy\TermInterface;
use Drupal\taxonomy\Entity\Vocabulary;
/**
* Helper function to create or update a menu link for a taxonomy term.
*
* @param \Drupal\taxonomy\TermInterface $term
* Term entity.
* @param array $values
* Values for the menu link.
*/
function _menu_ui_taxonomy_term_save(TermInterface $term, array $values) {
/** @var \Drupal\menu_link_content\MenuLinkContentInterface $entity */
if (!empty($values['entity_id'])) {
$entity = MenuLinkContent::load($values['entity_id']);
if ($entity->isTranslatable()) {
if (!$entity->hasTranslation($term->language()->getId())) {
$entity = $entity->addTranslation($term->language()->getId(), $entity->toArray());
}
else {
$entity = $entity->getTranslation($term->language()->getId());
}
}
}
else {
// Create a new menu_link_content entity.
$entity = MenuLinkContent::create([
'link' => ['uri' => 'internal:/taxonomy/term/' . $term->id()],
'langcode' => $term->language()->getId(),
]);
$entity->enabled->value = 1;
}
$entity->title->value = trim($values['title']);
$entity->description->value = trim($values['description']);
$entity->menu_name->value = $values['menu_name'];
$entity->parent->value = $values['parent'];
$entity->weight->value = isset($values['weight']) ? $values['weight'] : 0;
$entity->save();
}
/**
* Returns the definition for a menu link for the given term.
*
* @param \Drupal\taxonomy\TermInterface $term
* The term entity.
*
* @return array
* An array that contains default values for the menu link form.
*/
function taxonomy_menu_ui_get_menu_link_defaults(TermInterface $term) {
// Prepare the definition for the edit form.
/** @var \Drupal\taxonomy\VocabularyInterface $vocabulary */
$vid = $term->bundle();;
$vocabulary = Vocabulary::load($vid);
$menu_name = strtok($vocabulary->getThirdPartySetting('menu_ui', 'parent', 'main:'), ':');
$defaults = FALSE;
if ($term->id()) {
$id = FALSE;
// Give priority to the default menu.
$vocabulary_menus = $vocabulary->getThirdPartySetting('menu_ui', 'available_menus', ['main']);
if (in_array($menu_name, $vocabulary_menus)) {
$query = \Drupal::entityQuery('menu_link_content')
->condition('link.uri', 'taxonomy/term/' . $term->id())
->condition('menu_name', $menu_name)
->sort('id', 'ASC')
->range(0, 1);
$result = $query->execute();
$id = (!empty($result)) ? reset($result) : FALSE;
}
// Check all allowed menus if a link does not exist in the default menu.
if (!$id && !empty($vocabulary_menus)) {
$query = \Drupal::entityQuery('menu_link_content')
->condition('link.uri', 'internal:/taxonomy/term/' . $term->id())
->condition('menu_name', array_values($vocabulary_menus), 'IN')
->sort('id', 'ASC')
->range(0, 1);
$result = $query->execute();
$id = (!empty($result)) ? reset($result) : FALSE;
}
if ($id) {
$menu_link = MenuLinkContent::load($id);
$menu_link = \Drupal::service('entity.repository')->getTranslationFromContext($menu_link);
$defaults = [
'entity_id' => $menu_link->id(),
'id' => $menu_link->getPluginId(),
'title' => $menu_link->getTitle(),
'title_max_length' => $menu_link->getFieldDefinitions()['title']->getSetting('max_length'),
'description' => $menu_link->getDescription(),
'menu_name' => $menu_link->getMenuName(),
'parent' => $menu_link->getParentId(),
'weight' => $menu_link->getWeight(),
];
}
}
if (!$defaults) {
// Get the default max_length of a menu link title from the base field
// definition.
$field_definitions = \Drupal::service('entity_field.manager')->getBaseFieldDefinitions('menu_link_content');
$max_length = $field_definitions['title']->getSetting('max_length');
$defaults = [
'entity_id' => 0,
'id' => '',
'title' => '',
'title_max_length' => $max_length,
'description' => '',
'menu_name' => $menu_name,
'parent' => '',
'weight' => 0,
];
}
return $defaults;
}
/**
* Implements hook_form_BASE_FORM_ID_alter() for \Drupal\taxonomy\TermForm.
*
* Adds menu item fields to the taxonomy term form.
*
* @see taxonomy_menu_ui_form_taxonomy_term_form_submit()
*/
function taxonomy_menu_ui_form_taxonomy_term_form_alter(&$form, FormStateInterface $form_state) {
// Generate a list of possible parents
// (not including this link or descendants).
// @todo This must be handled in a #process handler.
$term = $form_state->getFormObject()->getEntity();
$defaults = taxonomy_menu_ui_get_menu_link_defaults($term);
/** @var \Drupal\taxonomy\VocabularyInterface $vocabulary */
$vid = $term->bundle();
$vocabulary = Vocabulary::load($vid);
/** @var \Drupal\Core\Menu\MenuParentFormSelectorInterface $menu_parent_selector */
$menu_parent_selector = \Drupal::service('menu.parent_form_selector');
$menu_names = menu_ui_get_menus();
$vocabulary_menus = $vocabulary->getThirdPartySetting('menu_ui', 'available_menus', ['main']);
$available_menus = [];
foreach ($vocabulary_menus as $menu) {
$available_menus[$menu] = $menu_names[$menu];
}
if ($defaults['id']) {
$default = $defaults['menu_name'] . ':' . $defaults['parent'];
}
else {
$default = $vocabulary->getThirdPartySetting('menu_ui', 'parent', 'main:');
}
$parent_element = $menu_parent_selector->parentSelectElement($default, $defaults['id'], $available_menus);
// If no possible parent menu items were found, there is nothing to display.
if (empty($parent_element)) {
return;
}
$current_user = \Drupal::currentUser();
$access = $current_user->hasPermission('administer menu');
// Menu admin per menu integration.
if (!$access && \Drupal::moduleHandler()->moduleExists('menu_admin_per_menu')) {
foreach (array_keys($available_menus) as $available_menu_id) {
if ($access = $current_user->hasPermission('administer ' . $available_menu_id . ' menu items')) {
break;
}
}
}
$form['menu'] = [
'#type' => 'details',
'#title' => t('Menu settings'),
'#access' => $access,
'#open' => (bool) $defaults['id'],
'#group' => 'advanced',
'#attached' => [
'library' => ['menu_ui/drupal.menu_ui'],
],
'#tree' => TRUE,
'#weight' => 10,
'#attributes' => ['class' => ['menu-link-form']],
];
$form['menu']['enabled'] = [
'#type' => 'checkbox',
'#title' => t('Provide a menu link'),
'#default_value' => (int) (bool) $defaults['id'],
];
$form['menu']['link'] = [
'#type' => 'container',
'#parents' => ['menu'],
'#states' => [
'invisible' => [
'input[name="menu[enabled]"]' => ['checked' => FALSE],
],
],
];
// Populate the element with the link data.
foreach (['id', 'entity_id'] as $key) {
$form['menu']['link'][$key] = ['#type' => 'value', '#value' => $defaults[$key]];
}
$form['menu']['link']['title'] = [
'#type' => 'textfield',
'#title' => t('Menu link title'),
'#default_value' => $defaults['title'],
'#maxlength' => $defaults['title_max_length'],
];
$form['menu']['link']['description'] = [
'#type' => 'textarea',
'#title' => t('Description'),
'#default_value' => $defaults['description'],
'#rows' => 1,
'#description' => t('Shown when hovering over the menu link.'),
];
$form['menu']['link']['menu_parent'] = $parent_element;
$form['menu']['link']['menu_parent']['#title'] = t('Parent item');
$form['menu']['link']['menu_parent']['#attributes']['class'][] = 'menu-parent-select';
$form['menu']['link']['weight'] = [
'#type' => 'number',
'#title' => t('Weight'),
'#default_value' => $defaults['weight'],
'#description' => t('Menu links with lower weights are displayed before links with higher weights.'),
];
foreach (array_keys($form['actions']) as $action) {
if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
$form['actions'][$action]['#submit'][] = 'taxonomy_menu_ui_form_taxonomy_term_form_submit';
}
}
$form['#entity_builders'][] = 'taxonomy_menu_ui_taxonomy_term_builder';
}
/**
* Entity form builder to add the menu information to the taxonomy term.
*/
function taxonomy_menu_ui_taxonomy_term_builder($entity_type, TermInterface $entity, &$form, FormStateInterface $form_state) {
$entity->menu = $form_state->getValue('menu');
}
/**
* Form submission handler for menu item field on the texonomy term form.
*
* @see taxonomy_menu_ui_form_taxonomy_term_form_alter()
*/
function taxonomy_menu_ui_form_taxonomy_term_form_submit($form, FormStateInterface $form_state) {
$term = $form_state->getFormObject()->getEntity();
if (!$form_state->isValueEmpty('menu')) {
$values = $form_state->getValue('menu');
if (empty($values['enabled'])) {
if ($values['entity_id']) {
$entity = MenuLinkContent::load($values['entity_id']);
$entity->delete();
}
}
elseif (trim($values['title'])) {
// Decompose the selected menu parent option into 'menu_name' and
// 'parent', if the form used the default parent selection widget.
if (!empty($values['menu_parent'])) {
list($menu_name, $parent) = explode(':', $values['menu_parent'], 2);
$values['menu_name'] = $menu_name;
$values['parent'] = $parent;
}
_menu_ui_taxonomy_term_save($term, $values);
}
}
}
/**
* Implements hook_form_FORM_ID_alter() for \Drupal\taxonomy\VocabularyForm.
*
* Adds menu options to the taxonomy vocabulary form.
*
* @see VocabularyForm::form()
* @see taxonomy_menu_ui_form_taxonomy_vocabulary_form_submit()
*/
function taxonomy_menu_ui_form_taxonomy_vocabulary_form_alter(&$form, FormStateInterface $form_state) {
/** @var \Drupal\Core\Menu\MenuParentFormSelectorInterface $menu_parent_selector */
$menu_parent_selector = \Drupal::service('menu.parent_form_selector');
$menu_options = menu_ui_get_menus();
/** @var \Drupal\taxonomy\VocabularyInterface $vocabulary */
$vocabulary = $form_state->getFormObject()->getEntity();
$form['menu'] = [
'#type' => 'details',
'#title' => t('Menu settings'),
'#attached' => [
'library' => ['menu_ui/drupal.menu_ui.admin'],
],
'#group' => 'additional_settings',
];
$form['menu']['menu_options'] = [
'#type' => 'checkboxes',
'#title' => t('Available menus'),
'#default_value' => $vocabulary->getThirdPartySetting('menu_ui', 'available_menus', ['main']),
'#options' => $menu_options,
'#description' => t('The menus available to place links in for this content type.'),
];
// @todo See if we can avoid pre-loading all options by changing the form or
// using a #process callback. https://www.drupal.org/node/2310319
// To avoid an 'illegal option' error after saving the form we have to load
// all available menu parents. Otherwise, it is not possible to dynamically
// add options to the list using ajax.
$options_cacheability = new CacheableMetadata();
$options = $menu_parent_selector->getParentSelectOptions('', NULL, $options_cacheability);
$form['menu']['menu_parent'] = [
'#type' => 'select',
'#title' => t('Default parent item'),
'#default_value' => $vocabulary->getThirdPartySetting('menu_ui', 'parent', 'main:'),
'#options' => $options,
'#description' => t('Choose the menu item to be the default parent for a new link in the content authoring form.'),
'#attributes' => ['class' => ['menu-title-select']],
];
$options_cacheability->applyTo($form['menu']['menu_parent']);
$form['#validate'][] = 'taxonomy_menu_ui_form_taxonomy_vocabulary_form_validate';
$form['#entity_builders'][] = 'taxonomy_menu_ui_form_taxonomy_vocabulary_form_builder';
}
/**
* Validate handler for forms with menu options.
*
* @see taxonomy_menu_ui_form_taxonomy_vocabulary_form_alter()
*/
function taxonomy_menu_ui_form_taxonomy_vocabulary_form_validate(&$form, FormStateInterface $form_state) {
$available_menus = array_filter($form_state->getValue('menu_options'));
// If there is at least one menu allowed, the selected item should be in
// one of them.
if (count($available_menus)) {
$menu_item_id_parts = explode(':', $form_state->getValue('menu_parent'));
if (!in_array($menu_item_id_parts[0], $available_menus)) {
$form_state->setErrorByName('menu_parent', t('The selected menu item is not under one of the selected menus.'));
}
}
else {
$form_state->setValue('menu_parent', '');
}
}
/**
* Entity builder for the taxonomy vocabulary form with menu options.
*
* @see taxonomy_menu_ui_form_taxonomy_vocabulary_form_alter()
*/
function taxonomy_menu_ui_form_taxonomy_vocabulary_form_builder($entity_type, VocabularyInterface $vocabulary, &$form, FormStateInterface $form_state) {
$vocabulary->setThirdPartySetting('menu_ui', 'available_menus', array_values(array_filter($form_state->getValue('menu_options'))));
$vocabulary->setThirdPartySetting('menu_ui', 'parent', $form_state->getValue('menu_parent'));
}
/**
* Implements hook_entity_extra_field_info().
*
* Add extra fields for each taxonomy vocabulary to show Menu settings.
*/
function taxonomy_menu_ui_entity_extra_field_info() {
$extra = [];
/** @var \Drupal\Core\Entity\EntityInterface $bundle */
foreach (Vocabulary::loadMultiple() as $bundle) {
$extra['taxonomy_term'][$bundle->id()]['form']['menu'] = [
'label' => t('Menu settings'),
'description' => t('Field for menu settings'),
'weight' => 10,
];
}
return $extra;
}
/**
* Implements hook_ENTITY_TYPE_translation_delete().
*
* Remove translation from the menu.
*/
function taxonomy_menu_ui_taxonomy_term_translation_delete(EntityInterface $entity) {
$language_id = $entity->language()->getId();
$menus = \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(['link__uri' => 'internal:/taxonomy/term/' . $entity->id()]);
foreach ($menus as $menu) {
if ($menu->hasTranslation($language_id)) {
$menu->removeTranslation($language_id);
$menu->save();
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment