term_taxonomy_term_tree patche

This commit is contained in:
Bachir Soussi Chiadmi 2021-07-28 09:27:00 +02:00
parent fc85755ad1
commit d06cf6702a
22 changed files with 81 additions and 1690 deletions

View File

@ -91,6 +91,7 @@
"drupal/synonyms": "2.0.0-beta2", "drupal/synonyms": "2.0.0-beta2",
"drupal/telephone_formatter": "^1.0@beta", "drupal/telephone_formatter": "^1.0@beta",
"drupal/telephone_validation": "^2.1", "drupal/telephone_validation": "^2.1",
"drupal/term_reference_tree": "1.x-dev@dev",
"drupal/translate_side_by_side": "^1.x-dev", "drupal/translate_side_by_side": "^1.x-dev",
"drupal/translation_views": "^1.x-dev", "drupal/translation_views": "^1.x-dev",
"drupal/ultimate_cron": "^2.x-dev", "drupal/ultimate_cron": "^2.x-dev",
@ -197,6 +198,9 @@
}, },
"drupal/pwa": { "drupal/pwa": {
"Manifest doesn't have a maskable icon https://www.drupal.org/project/pwa/issues/3165433": "https://www.drupal.org/files/issues/2020-08-26/pwa_icon_purpose-3165433-9.patch" "Manifest doesn't have a maskable icon https://www.drupal.org/project/pwa/issues/3165433": "https://www.drupal.org/files/issues/2020-08-26/pwa_icon_purpose-3165433-9.patch"
},
"drupal/term_reference_tree": {
"Term Reference Tree: Re-implement Track List https://www.drupal.org/project/term_reference_tree/issues/3064280": "https://www.drupal.org/files/issues/2021-07-16/3064280_bring_back_tracklist-15.patch"
} }
}, },
"drupal-scaffold": { "drupal-scaffold": {

78
composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "5f6a4267f5f2366f8b0c1e069383160d", "content-hash": "b16797b72316e983c9d3ffdc0c169447",
"packages": [ "packages": [
{ {
"name": "alchemy/zippy", "name": "alchemy/zippy",
@ -12462,6 +12462,81 @@
"issues": "http://drupal.org/project/issues/telephone_validation" "issues": "http://drupal.org/project/issues/telephone_validation"
} }
}, },
{
"name": "drupal/term_reference_tree",
"version": "dev-1.x",
"source": {
"type": "git",
"url": "https://git.drupalcode.org/project/term_reference_tree.git",
"reference": "198f1a2c02dc32946cf1c74f7130b32ba4d45841"
},
"require": {
"drupal/core": "^8.9 || ^9.1"
},
"type": "drupal-module",
"extra": {
"branch-alias": {
"dev-1.x": "1.x-dev"
},
"drupal": {
"version": "8.x-1.0-alpha3+8-dev",
"datestamp": "1611896754",
"security-coverage": {
"status": "not-covered",
"message": "Dev releases are not covered by Drupal security advisories."
}
}
},
"notification-url": "https://packages.drupal.org/8/downloads",
"license": [
"GPL-2.0+"
],
"authors": [
{
"name": "See other contributors",
"homepage": "https://www.drupal.org/node/1088348/committers",
"role": "contributor"
},
{
"name": "Dave Reid",
"homepage": "https://www.drupal.org/user/53892"
},
{
"name": "MoustafaEid",
"homepage": "https://www.drupal.org/user/1126928"
},
{
"name": "VladimirAus",
"homepage": "https://www.drupal.org/user/673120"
},
{
"name": "alex_optim",
"homepage": "https://www.drupal.org/user/3317601"
},
{
"name": "carpenter.490",
"homepage": "https://www.drupal.org/user/804142"
},
{
"name": "dgtlmoon",
"homepage": "https://www.drupal.org/user/25027"
},
{
"name": "sdrycroft",
"homepage": "https://www.drupal.org/user/151544"
},
{
"name": "sumitmadan",
"homepage": "https://www.drupal.org/user/1538790"
}
],
"description": "An expanding/collapsing tree widget for selecting terms in a taxonomy term reference field.",
"homepage": "https://drupal.org/project/term_reference_tree",
"support": {
"source": "https://git.drupalcode.org/project/term_reference_tree",
"issues": "https://drupal.org/project/issues/term_reference_tree"
}
},
{ {
"name": "drupal/token", "name": "drupal/token",
"version": "1.9.0", "version": "1.9.0",
@ -20641,6 +20716,7 @@
"drupal/simplenews": 10, "drupal/simplenews": 10,
"drupal/strings_i18n_json_export": 20, "drupal/strings_i18n_json_export": 20,
"drupal/telephone_formatter": 10, "drupal/telephone_formatter": 10,
"drupal/term_reference_tree": 20,
"drupal/translate_side_by_side": 20, "drupal/translate_side_by_side": 20,
"drupal/translation_views": 20, "drupal/translation_views": 20,
"drupal/ultimate_cron": 20, "drupal/ultimate_cron": 20,

View File

@ -305,7 +305,6 @@ content:
select_parents: true select_parents: true
cascading_selection: 0 cascading_selection: 0
track_list: true track_list: true
track_list_order: true
max_depth: 0 max_depth: 0
leaves_only: false leaves_only: false
third_party_settings: { } third_party_settings: { }

View File

@ -1,339 +0,0 @@
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.

View File

@ -1,22 +0,0 @@
field.widget.settings.term_reference_tree:
type: mapping
label: 'Term reference tree widget settings'
mapping:
start_minimized:
type: boolean
label: 'Start minimized'
leaves_only:
type: boolean
label: 'Leaves only'
select_parents:
type: boolean
label: 'Select parents automatically'
cascading_selection:
type: integer
label: 'Cascading selection'
track_list:
type: boolean
label: 'Track list'
max_depth:
type: integer
label: 'Maximum Depth'

View File

@ -1,5 +0,0 @@
The icons contained in this directory are from the FatCow "Farm-Fresh Web Icons"
collection, available under the Creative Commons Attribution 3.0 license. They
can be downloaded here:
http://www.fatcow.com/free-icons

Binary file not shown.

Before

Width:  |  Height:  |  Size: 765 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 469 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 518 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 224 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 213 B

View File

@ -1,135 +0,0 @@
<?php
namespace Drupal\term_reference_tree\Element;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\CompositeFormElementTrait;
use Drupal\Core\Render\Element\FormElement;
/**
* Provides a form element for term reference tree.
*
* @FormElement("checkbox_tree")
*/
class CheckboxTree extends FormElement {
use CompositeFormElementTrait;
/**
* {@inheritdoc}
*/
public function getInfo() {
$class = get_class($this);
return [
'#input' => TRUE,
'#tree' => TRUE,
'#process' => [
[$class, 'processCheckboxTree'],
],
'#pre_render' => [
[$class, 'preRenderCompositeFormElement'],
],
'#default_value' => [],
'#attached' => [
'library' => [
'term_reference_tree/term_reference_tree_js',
'term_reference_tree/term_reference_tree_css',
],
],
'#theme' => 'checkbox_tree',
];
}
/**
* Processes a checkboxes form element.
*/
public static function processCheckboxTree(&$element, FormStateInterface $form_state, &$complete_form) {
$value = is_array($element['#value']) ? $element['#value'] : [];
$allowed = [];
$filter = FALSE;
if (!empty($element['#max_choices']) && $element['#max_choices'] != '-1') {
$element['#attached']['drupalSettings'] = [
'term_reference_tree' => [
'trees' => [
$element['#id'] => [
'max_choices' => $element['#max_choices'],
],
],
],
];
}
if (!empty($element['#allowed'])) {
$allowed = $element['#allowed'];
$filter = TRUE;
}
if (empty($element['#options'])) {
$options_tree = [];
foreach ($element['#vocabularies'] as $vocabulary) {
$options = _term_reference_tree_get_term_hierarchy(0, $vocabulary->id(), $allowed, $filter, '', $value);
$options_tree = array_merge($options_tree, $options);
}
$element['#options_tree'] = $options_tree;
$element['#options'] = _term_reference_tree_get_options($element['#options_tree'], $allowed, $filter);
}
$terms = !empty($element['#options_tree']) ? $element['#options_tree'] : [];
$tree = new \stdClass();
$tree->children = $terms;
unset($element['#needs_validation']);
$element['checkbox_tree'] = _term_reference_tree_build_level($element, $tree, $form_state, $value, $element['#max_choices'], [], 1);
// track list
if ($element['#track_list']) {
if($form_state->getTriggeringElement()){
// we are on ajax
// $value is not updated on ajax callback
// we need an other way to get wich options are checked
// and give an accurate track list
$parent = $element['#parents'][0]; // get the element's parent field
$input = $form_state->getUserInput(); // get all inputs from form state
$checkbox_tree_input = $input[$parent]['checkbox_tree']; // get the chekbox_tree input
$selected = _term_reference_tree_get_flatten_selected_values($checkbox_tree_input); // get selected flattenized
$track_list_input = $input[$parent]['track_list']; // get the current track_list input with correct order
$old_list = array_keys($track_list_input); // flattenize
// remove all chebox_tree input unselected from the list
$list = [];
foreach ($old_list as $id) {
if(in_array($id, $selected)){
$list[] = $id;
}
}
// append newly selected
$diff = array_diff($selected, $list);
foreach ($diff as $id) {
$list[] = $id;
}
}else{
// if not ajax just get the default value
$list = $value;
}
// build the track_list form element
$element['track_list'] = _term_reference_tree_build_track_list_order($list, $element['#options']);
}
return $element;
}
/**
* {@inheritdoc}
*/
public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
$value = [];
$element += ['#default_value' => []];
foreach ($element['#default_value'] as $key) {
if (isset($key['target_id'])) {
$value[$key['target_id']] = $key['target_id'];
}
}
return $value;
}
}

View File

@ -1,24 +0,0 @@
<?php
namespace Drupal\term_reference_tree\Element;
use Drupal\Core\Render\Element\FormElement;
/**
* Provides a form element for term reference tree.
*
* @FormElement("checkbox_tree_item")
*/
class CheckboxTreeItem extends FormElement {
/**
* {@inheritdoc}
*/
public function getInfo() {
return array(
'#input' => FALSE,
'#theme' => 'checkbox_tree_item',
);
}
}

View File

@ -1,24 +0,0 @@
<?php
namespace Drupal\term_reference_tree\Element;
use Drupal\Core\Render\Element\FormElement;
/**
* Provides a form element for term reference tree.
*
* @FormElement("checkbox_tree_label")
*/
class CheckboxTreeLabel extends FormElement {
/**
* {@inheritdoc}
*/
public function getInfo() {
return array(
'#input' => FALSE,
'#theme' => 'checkbox_tree_label',
);
}
}

View File

@ -1,24 +0,0 @@
<?php
namespace Drupal\term_reference_tree\Element;
use Drupal\Core\Render\Element\FormElement;
/**
* Provides a form element for term reference tree.
*
* @FormElement("checkbox_tree_level")
*/
class CheckboxTreeLevel extends FormElement {
/**
* {@inheritdoc}
*/
public function getInfo() {
return array(
'#input' => FALSE,
'#theme' => 'checkbox_tree_level',
);
}
}

View File

@ -1,55 +0,0 @@
<?php
namespace Drupal\term_reference_tree\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the thumbnail field formatter.
*
* @FieldFormatter(
* id = "term_reference_tree",
* label = @Translation("Term Reference Tree"),
* field_types = {
* "entity_reference"
* }
* )
*/
class TermReferenceTree extends FormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$element[] = array(
'#theme' => 'term_tree_list',
'#data' => $items->getValue(),
'#attached' => ['library' => ['term_reference_tree/term_reference_tree_css']],
);
return $element;
}
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
return parent::settingsForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
return [];
}
}

View File

@ -1,238 +0,0 @@
<?php
namespace Drupal\term_reference_tree\Plugin\Field\FieldWidget;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\taxonomy\Entity\Vocabulary;
/**
* Plugin implementation of the 'term_reference_tree' widget.
*
* @FieldWidget(
* id = "term_reference_tree",
* label = @Translation("Term reference tree"),
* field_types = {"entity_reference"},
* multiple_values = TRUE
* )
*/
class TermReferenceTree extends WidgetBase {
const CASCADING_SELECTION_NONE = '0';
const CASCADING_SELECTION_BOTH = '1';
const CASCADING_SELECTION_SELECT = '2';
const CASCADING_SELECTION_DESELECT = '3';
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'start_minimized' => TRUE,
'leaves_only' => FALSE,
'select_parents' => FALSE,
'cascading_selection' => self::CASCADING_SELECTION_NONE,
'track_list' => FALSE,
'max_depth' => 0,
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$form = parent::settingsForm($form, $form_state);
$form['start_minimized'] = [
'#type' => 'checkbox',
'#title' => $this->t('Start minimized'),
'#description' => $this->t('Make the tree appear minimized on the form by default'),
'#default_value' => $this->getSetting('start_minimized'),
];
$form['leaves_only'] = [
'#type' => 'checkbox',
'#title' => $this->t('Leaves only'),
'#description' => $this->t("Don't allow the user to select items that have children"),
'#default_value' => $this->getSetting('leaves_only'),
'#return_value' => 1,
];
$form['select_parents'] = [
'#type' => 'checkbox',
'#title' => $this->t('Select parents automatically'),
'#description' => $this->t("When turned on, this option causes the widget to automatically select the ancestors of all selected items. In Leaves Only mode, the parents will be added invisibly to the selected value. <em>This option is only valid if an unlimited number of values can be selected.</em>"),
'#default_value' => $this->getSetting('select_parents'),
'#return_value' => 1,
];
$form['cascading_selection'] = [
'#type' => 'select',
'#title' => $this->t('Cascading selection'),
'#description' => $this->t('On parent selection, automatically select children if none were selected. Some may then be manually unselected. In the same way, on parent unselection, unselect children if all were selected. <em>This option is only valid if an unlimited number of values can be selected.</em>'),
'#default_value' => $this->getSetting('cascading_selection'),
'#options' => [
self::CASCADING_SELECTION_NONE => $this->t('None'),
self::CASCADING_SELECTION_BOTH => $this->t('Select / deselect'),
self::CASCADING_SELECTION_SELECT => $this->t('Only select'),
self::CASCADING_SELECTION_DESELECT => $this->t('Only deselect'),
],
];
if ($this->fieldDefinition->getFieldStorageDefinition()
->getCardinality() !== FieldStorageConfig::CARDINALITY_UNLIMITED) {
$form['select_parents']['#disabled'] = TRUE;
$form['select_parents']['#default_value'] = FALSE;
$form['select_parents']['#description'] .= ' <em>' . $this->t("This option is only valid if an unlimited number of values can be selected.") . '</em>';
$form['cascading_selection']['#disabled'] = TRUE;
$form['cascading_selection']['#default_value'] = self::CASCADING_SELECTION_NONE;
$form['cascading_selection']['#description'] .= ' <em>' . $this->t("This option is only valid if an unlimited number of values can be selected.") . '</em>';
}
$form['track_list'] = [
'#type' => 'checkbox',
'#title' => $this->t('Track list'),
'#description' => $this->t('Track what the user has chosen in a list below the tree.
Useful when the tree is large, with many levels.'),
'#default_value' => $this->getSetting('track_list'),
'#return_value' => 1,
];
$form['max_depth'] = [
'#type' => 'number',
'#title' => $this->t('Maximum Depth'),
'#description' => $this->t("Only show items up to this many levels deep."),
'#default_value' => $this->getSetting('max_depth'),
'#min' => 0,
];
return $form;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
if ($this->getSetting('start_minimized')) {
$summary[] = $this->t('Start minimized');
}
if ($this->getSetting('leaves_only')) {
$summary[] = $this->t('Leaves only');
}
if ($this->getSetting('select_parents')) {
$summary[] = $this->t('Select parents automatically');
}
$cascadingSelection = $this->getSetting('cascading_selection');
if ($cascadingSelection == self::CASCADING_SELECTION_BOTH) {
$summary[] = $this->t('Cascading selection');
}
elseif ($cascadingSelection == self::CASCADING_SELECTION_SELECT) {
$summary[] = sprintf('%s (%s)', $this->t('Cascading selection'), $this->t('Only select'));
}
elseif ($cascadingSelection == self::CASCADING_SELECTION_DESELECT) {
$summary[] = sprintf('%s (%s)', $this->t('Cascading selection'), $this->t('Only deselect'));
}
if ($this->getSetting('track_list')) {
$summary[] = $this->t('Track list');
}
if ($this->getSetting('max_depth')) {
$summary[] = $this->formatPlural($this->getSetting('max_depth'), 'Maximum Depth: @count level', 'Maximum Depth: @count levels');
}
return $summary;
}
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$handler_settings = $this->getFieldSetting('handler_settings');
$vocabularies = Vocabulary::loadMultiple($handler_settings['target_bundles']);
$element['#type'] = 'checkbox_tree';
$element['#default_value'] = $items->getValue();
$element['#vocabularies'] = $vocabularies;
$element['#max_choices'] = $this->fieldDefinition->getFieldStorageDefinition()
->getCardinality();
$element['#leaves_only'] = $this->getSetting('leaves_only');
$element['#select_parents'] = $this->getSetting('select_parents');
$element['#cascading_selection'] = $this->getSetting('cascading_selection');
$element['#track_list'] = $this->getSetting('track_list');
$element['#value_key'] = 'target_id';
$element['#max_depth'] = $this->getSetting('max_depth');
$element['#start_minimized'] = $this->getSetting('start_minimized');
$element['#element_validate'] = [
[
get_class($this),
'validateTermReferenceTreeElement',
],
];
return $element;
}
/**
* Form element validation handler for term reference form widget.
*/
public static function validateTermReferenceTreeElement(&$element, FormStateInterface $form_state) {
$items = _term_reference_tree_flatten($element, $form_state);
$value = [];
if ($element['#max_choices'] != 1) {
foreach ($items as $child) {
if (!empty($child['#value'])) {
// If the element is leaves only and select parents is on,
// then automatically add all the parents of each selected value.
if (!empty($element['#select_parents']) && !empty($element['#leaves_only'])) {
foreach ($child['#parent_values'] as $parent_tid) {
if (!in_array([$element['#value_key'] => $parent_tid], $value)) {
array_push($value, [$element['#value_key'] => $parent_tid]);
}
}
}
array_push($value, [$element['#value_key'] => $child['#value']]);
}
}
// if track_list enabled, reorder the value array regarding the tablegrag input
if (!empty($value) && $element['#track_list']) {
$input = &$form_state->getUserInput();
$nested_input = NestedArray::getValue($form_state->getValues(), $element['#parents']);
if (is_array($nested_input['track_list'])) {
$track_list = array_keys($nested_input['track_list']);
$sorted_value = [];
foreach ($track_list as $id) {
$sorted_value[] = $value[array_search($id, array_column($value, 'target_id'))];
}
$value = $sorted_value;
}
}
}
else {
// If it's a tree of radio buttons, they all have the same value,
// so we can just grab the value of the first one.
if (count($items) > 0) {
$child = reset($items);
if (!empty($child['#value'])) {
array_push($value, [$element['#value_key'] => $child['#value']]);
}
}
}
if ($element['#required'] && empty($value)) {
$form_state->setError($element, t('%name field is required.', ['%name' => $element['#title']]));
}
$form_state->setValueForElement($element, $value);
}
}

View File

@ -1,107 +0,0 @@
.item-list .field--widget-term-reference-tree ul,
.block .field--widget-term-reference-tree ul,
.field--widget-term-reference-tree ul {
list-style-type: none;
margin-top: 0;
margin-bottom: 0;
margin-left: 0;
}
.item-list .field--widget-term-reference-tree ul ul,
.block .field--widget-term-reference-tree ul ul,
.field--widget-term-reference-tree ul ul {
margin-left: 1.5em;
}
.item-list .field--widget-term-reference-tree ul .form-item,
.block .field--widget-term-reference-tree ul .form-item,
.field--widget-term-reference-tree ul .form-item {
margin: 0;
padding: 0;
}
.term-reference-tree-button,
.no-term-reference-tree-button {
width: 16px;
height: 16px;
display: inline-block;
*display: inline;
zoom: 1;
vertical-align: middle;
margin-right: 4px;
}
.term-reference-tree-button {
background-image: url('images/bullet_toggle_minus.png');
}
.no-term-reference-tree-button {
background-color: #ddd;
}
.term-reference-tree-button.term-reference-tree-collapsed {
background-image: url('images/bullet_toggle_plus.png');
}
.field--widget-term-reference-tree .form-item {
display: inline-block;
*display: inline;
zoom: 1;
}
.field--widget-term-reference-tree .disabled {
opacity: .5;
}
.field--widget-term-reference-tree .parent-term {
display: inline-block;
*display: inline;
zoom: 1;
font-weight: bold;
}
.form-type-checkbox-tree .error {
background-image: none;
border: 2px solid red;
padding: 3px;
}
.region-content ul.term-reference-tree-level,
.term-reference-tree-level {
padding: 0;
}
/*
* Styles for track list of selected options.
*/
.term-reference-tree-track-list li {
list-style-type: none;
list-style-image: none;
margin-left: 10px;
padding-left: 20px;
min-height: 16px;
cursor: pointer;
}
.term-reference-tree-track-list li.track-item:hover {
color: red;
background-image: url("images/bullet_delete.png");
background-repeat: no-repeat;
background-position: middle left;
}
.term-reference-tree-track-list li.term_ref_tree_nothing_message {
list-style-type: none;
list-style-image: none;
font-style: italic;
cursor: default;
}
.term-reference-track-list-container {
padding: 5px;
}
.term-reference-track-list-label {
font-weight: bold;
}
/*
* Styles for display element
*/
.term-tree-list .selected {
font-weight: bold;
}
.term-tree-list .unselected {
font-weight: normal;
}
.term-tree-list ul {
margin-top: 0;
}
.field--type-entity-reference ul.links .term-tree-list ul.term li {
float: none;
}

View File

@ -1,14 +0,0 @@
name: 'Term Reference Tree'
description: 'An expanding/collapsing tree widget for selecting terms in a taxonomy term reference field.'
package: Fields
# core: 8.x
dependencies:
- drupal:taxonomy
- drupal:system (>= 8.6.x)
type: module
# Information added by Drupal.org packaging script on 2019-06-21
version: '8.x-1.0-alpha2+15-dev'
core: '8.x'
project: 'term_reference_tree'
datestamp: 1561103289

View File

@ -1,109 +0,0 @@
(function($) {
/**
* Attaches the tree behavior to the term widget form.
*/
Drupal.behaviors.termReferenceTree = {
attach: function(context, settings) {
// Bind the term expand/contract button to slide toggle the list underneath.
$('.term-reference-tree-button', context).once('term-reference-tree-button').click(function() {
$(this).toggleClass('term-reference-tree-collapsed');
$(this).siblings('ul').slideToggle('fast');
});
// An expand all button (unimplemented)
/*
$('.expandbutton').click(function() {
$(this).siblings('.term-reference-tree-button').trigger('click');
});
*/
$('.term-reference-tree', context).once('term-reference-tree').each(function() {
// On page load, check whether the maximum number of choices is already selected.
// If so, disable the other options.
var tree = $(this);
checkMaxChoices(tree, false);
$(this).find('input[type=checkbox]').change(function() {
checkMaxChoices(tree, $(this));
});
//On page load, check if the user wants a cascading selection.
if($(this).hasClass('term-reference-tree-select-parents')) {
$(this).find('.form-checkbox').parent().addClass('select-parents');
}
//On page load, check if the user wants a cascading selection.
if($(this).hasClass('term-reference-tree-cascading-selection')) {
var mode_select = $(this).hasClass('term-reference-tree-cascading-selection-mode-select');
var mode_deselect = $(this).hasClass('term-reference-tree-cascading-selection-mode-deselect');
//Check children when checkboxes are clicked.
$(this).find('.form-checkbox').change(function(event) {
var event_target = $(event.target);
var event_target_checked = event_target.is(':checked');
var control_id = event_target.attr('id');
var children = event_target.parent().next().children().find('> :not(ul) > input[id^="' + control_id + '-children"]');
if (!mode_select && !mode_deselect) {
if(event_target_checked) {
$(children).filter(':not(:checked)').click().trigger('change');
}
else {
$(children).filter(':checked').click().trigger('change');
}
} else if (mode_select && event_target_checked) {
$(children).filter(':not(:checked)').click().trigger('change');
} else if (mode_deselect && !event_target_checked) {
$(children).filter(':checked').click().trigger('change');
}
});
//End process checkbox changes.
} //End Want a cascading checking.
});
// track_list
// just unselect items in tree on track_list button remove click
// let builtin ajax form do the heavy work
$('.term-reference-tree-track-list input[type="submit"][value="remove"]', context).click(function(e){
e.preventDefault();
var key = $(this).attr('term-reference-tree-key');
$('input[type="checkbox"][value="'+key+'"]', $(this).parents('.term-reference-tree'))
.prop('checked', false)
.trigger('change');
return false;
});
}
};
// This helper function checks if the maximum number of choices is already selected.
// If so, it disables all the other options. If not, it enables them.
function checkMaxChoices(item, checkbox) {
var maxChoices = -1;
try {
maxChoices = parseInt(Drupal.settings.term_reference_tree.trees[item.attr('id')]['max_choices']);
}
catch (e){}
var count = item.find(':checked').length;
if(maxChoices > 0 && count >= maxChoices) {
item.find('input[type=checkbox]:not(:checked)').attr('disabled', 'disabled').parent().addClass('disabled');
} else {
item.find('input[type=checkbox]').removeAttr('disabled').parent().removeClass('disabled');
}
if(checkbox) {
if(item.hasClass('term-reference-tree-select-parents')) {
if(checkbox.prop('checked')) {
checkbox.parents('ul.term-reference-tree-level li').children('div.form-item').find('input[type=checkbox]').each(function() {
$(this).prop('checked', true);
});
}
}
}
}
})(jQuery);

View File

@ -1,12 +0,0 @@
term_reference_tree_js:
js:
term_reference_tree.js: {}
dependencies:
- core/jquery
- core/drupal
- core/jquery.once
term_reference_tree_css:
css:
theme:
term_reference_tree.css: {}

View File

@ -1,580 +0,0 @@
<?php
use \Drupal\Core\Render\Element;
use Drupal\Core\Form\FormState;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
/**
* Implements hook_theme().
*/
function term_reference_tree_theme() {
return [
'checkbox_tree' => [
'render element' => 'element',
'function' => 'theme_checkbox_tree',
],
'checkbox_tree_level' => [
'render element' => 'element',
'function' => 'theme_checkbox_tree_level',
],
'checkbox_tree_item' => [
'render element' => 'element',
'function' => 'theme_checkbox_tree_item',
],
'checkbox_tree_label' => [
'render element' => 'element',
'function' => 'theme_checkbox_tree_label',
],
'term_tree_list' => [
'render element' => 'element',
'function' => 'theme_term_tree_list',
],
];
}
/**
* Returns HTML for a checkbox_tree form element.
*/
function theme_checkbox_tree($variables) {
$element = $variables['element'];
$element['#children'] = drupal_render_children($element);
$attributes = isset($element['#attributes']) ? $element['#attributes'] : [];
if (isset($element['#id'])) {
$attributes['id'] = $element['#id'];
}
$attributes['class'][] = 'term-reference-tree';
if (!empty($element['#required'])) {
$attributes['class'][] = 'required';
}
if (array_key_exists('#start_minimized', $element) && $element['#start_minimized']) {
$attributes['class'][] = 'term-reference-tree-collapsed';
}
if (array_key_exists('#track_list', $element) && $element['#track_list']) {
$attributes['class'][] = 'term-reference-tree-track-list-shown';
}
if (!empty($variables['element']['#select_parents'])) {
$attributes['class'][] = 'term-reference-tree-select-parents';
}
if ($variables['element']['#cascading_selection'] != \Drupal\term_reference_tree\Plugin\Field\FieldWidget\TermReferenceTree::CASCADING_SELECTION_NONE) {
$attributes['class'][] = 'term-reference-tree-cascading-selection';
}
if ($variables['element']['#cascading_selection'] == \Drupal\term_reference_tree\Plugin\Field\FieldWidget\TermReferenceTree::CASCADING_SELECTION_SELECT) {
$attributes['class'][] = 'term-reference-tree-cascading-selection-mode-select';
}
else {
if ($variables['element']['#cascading_selection'] == \Drupal\term_reference_tree\Plugin\Field\FieldWidget\TermReferenceTree::CASCADING_SELECTION_DESELECT) {
$attributes['class'][] = 'term-reference-tree-cascading-selection-mode-deselect';
}
}
if (!empty($element['#attributes']['class'])) {
$attributes['class'] = array_merge($attributes['class'], $element['#attributes']['class']);
}
return
'<div' . new \Drupal\Core\Template\Attribute($attributes) . '>'
. (!empty($element['#children']) ? $element['#children'] : '')
. '</div>';
}
/**
* This function prints a list item with a checkbox and an unordered list
* of all the elements inside it.
*/
function theme_checkbox_tree_level($variables) {
$element = $variables['element'];
$sm = '';
if (array_key_exists('#level_start_minimized', $element) && $element['#level_start_minimized']) {
$sm = ' style="display: none;"';
}
$output = '<ul class="term-reference-tree-level "' . $sm . '>';
$children = Element::children($element);
foreach ($children as $child) {
$output .= '<li>';
$output .= \Drupal::service('renderer')->render($element[$child]);
$output .= '</li>';
}
$output .= '</ul>';
return $output;
}
/**
* This function prints a single item in the tree, followed by that item's
* children (which may be another checkbox_tree_level).
*/
function theme_checkbox_tree_item($variables) {
$element = $variables['element'];
$children = Element::children($element);
$output = '';
$sm = $element['#level_start_minimized'] ? ' term-reference-tree-collapsed' : '';
if (is_array($children) && count($children) > 1) {
$output .= '<div class="term-reference-tree-button' . $sm . '"></div>';
}
elseif (!$element['#leaves_only']) {
$output .= '<div class="no-term-reference-tree-button"></div>';
}
foreach ($children as $child) {
$output .= drupal_render($element[$child]);
}
return $output;
}
/**
* This function prints a label that cannot be selected.
*/
function theme_checkbox_tree_label($variables) {
$element = $variables['element'];
$output = '<div class="parent-term">' . $element['#value'] . '</div>';
return $output;
}
/**
* This function returns a taxonomy term hierarchy in a nested array.
*
* @param $tid
* The ID of the root term.
* @param $vid
* The vocabulary ID to restrict the child search.
*
* @return
* A nested array of the term's child objects.
*/
function _term_reference_tree_get_term_hierarchy($tid, $vid, &$allowed, $filter, $label, $default = array()) {
$terms = _term_reference_tree_get_children($tid, $vid);
$result = [];
if ($filter != '') {
foreach ($allowed as $k => $v) {
if (array_key_exists($k, $terms)) {
$term =& $terms[$k];
$children = _term_reference_tree_get_term_hierarchy($term->tid, $vid, $allowed, $filter, $label, $default);
if (is_array($children)) {
$term->children = $children;
$term->children_selected = _term_reference_tree_children_selected($term, $default);
}
else {
$term->children_selected = FALSE;
}
$term->TEST = $label;
array_push($result, $term);
}
}
}
else {
foreach ($terms as &$term) {
if ($filter == '' || array_key_exists($term->tid, $allowed)) {
$children = _term_reference_tree_get_term_hierarchy($term->tid, $vid, $allowed, $filter, $label, $default);
if (is_array($children)) {
$term->children = $children;
$term->children_selected = _term_reference_tree_children_selected($term, $default);
}
else {
$term->children_selected = FALSE;
}
$term->TEST = $label;
array_push($result, $term);
}
}
}
return $result;
}
/**
* This function is like taxonomy_get_children, except it doesn't load the
* entire term.
*
* @param int $tid
* The ID of the term whose children you want to get.
* @param int $vid
* The vocabulary ID.
*
* @return array
* Taxonomy terms, each in the form ['tid' => $tid, 'name' => $name].
*/
function _term_reference_tree_get_children($tid, $vid) {
// DO NOT LOAD TAXONOMY TERMS HERE.
// Taxonomy terms take a lot of time and memory to load, and this can be
// very bad on large vocabularies. Instead, we load the term as necessary
// in cases where it's needed (such as using tokens or when the locale
// module is enabled).
$table = 'taxonomy_term_field_data';
$alias = 't';
$query = \Drupal::database()
->select($table, $alias);
$query->join('taxonomy_term__parent', 'p', 't.tid = p.entity_id');
$query->fields('t', ['tid', 'name']);
$query->addField('t', 'vid', 'vocabulary_machine_name');
$query
->condition('t.vid', $vid)
->condition('p.parent_target_id', $tid)
->addTag('term_access')
->addTag('translatable')
->orderBy('t.weight')
->orderBy('t.name');
$result = $query->execute();
$terms = [];
while ($term = $result->fetchObject()) {
$terms[$term->tid] = $term;
}
return $terms;
}
function _term_reference_tree_children_selected($terms, $default) {
foreach ($terms->children as $term) {
if (isset($default[$term->tid]) || $term->children_selected) {
return TRUE;
}
}
return FALSE;
}
/**
* Recursively go through the option tree and return a flat array of options.
*/
function _term_reference_tree_flatten($element, &$form_state) {
$output = array();
$children = \Drupal\Core\Render\Element::children($element);
foreach ($children as $c) {
$child = $element[$c];
if (array_key_exists('#type', $child) && ($child['#type'] == 'radio' || $child['#type'] == 'checkbox')) {
$output[] = $child;
}
else {
$output = array_merge($output, _term_reference_tree_flatten($child, $form_state));
}
}
return $output;
}
/**
* Return an array of options.
*
* This function converts a list of taxonomy terms to a key/value list of
* options.
*/
function _term_reference_tree_get_options(&$terms, &$allowed, $filter) {
$options = array();
if (is_array($terms) && count($terms) > 0) {
foreach ($terms as $term) {
if (!$filter || (is_array($allowed) && $allowed[$term->tid])) {
$options[$term->tid] = $term->name;
$options += _term_reference_tree_get_options($term->children, $allowed, $filter);
}
}
}
return $options;
}
/**
* Builds a level in the term reference tree widget.
*
* This function returns an element that has a number of checkbox_tree_item
* elements as children. It is meant to be called recursively when the widget
* is built.
*/
function _term_reference_tree_build_level($element, $term, $form_state, $value, $max_choices, $parent_tids, $depth) {
$start_minimized = TRUE;
$leaves_only = FALSE;
$container = array(
'#type' => 'checkbox_tree_level',
'#max_choices' => $max_choices,
'#leaves_only' => $leaves_only,
'#start_minimized' => $start_minimized,
'#depth' => $depth,
);
$container['#level_start_minimized'] = $depth > 1 && $element['#start_minimized'] && !($term->children_selected);
foreach ($term->children as $child) {
$container[$child->tid] = _term_reference_tree_build_item($element, $child, $form_state, $value, $max_choices, $parent_tids, $container, $depth);
}
return $container;
}
/**
* Builds a single item in the term reference tree widget.
*
* This function returns an element with a checkbox for a single taxonomy term.
* If that term has children, it appends checkbox_tree_level element that
* contains the children. It is meant to be called recursively when the widget
* is built.
*/
function _term_reference_tree_build_item($element, $term, $form_state, $value, $max_choices, $parent_tids, $parent, $depth) {
$leaves_only = FALSE;
$langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
$t = NULL;
if (\Drupal::moduleHandler()->moduleExists('locale') && !empty($term->tid)) {
$t = \Drupal::entityManager()
->getStorage('taxonomy_term')
->load($term->tid);
if ($t && $t->hasTranslation($langcode)) {
$term_name = $t->getTranslation($langcode)->label();
}
}
if (empty($term_name)) {
$term_name = $term->name;
}
$container = array(
'#type' => 'checkbox_tree_item',
'#max_choices' => $max_choices,
'#leaves_only' => $leaves_only,
'#term_name' => $term_name,
'#level_start_minimized' => FALSE,
'#select_parents' => $element['#select_parents'],
'#depth' => $depth,
);
if (!$element['#leaves_only'] || count($term->children) == 0) {
$e = array(
'#type' => ($max_choices == 1) ? 'radio' : 'checkbox',
'#title' => $term_name,
'#on_value' => $term->tid,
'#off_value' => 0,
'#return_value' => $term->tid,
'#parent_values' => $parent_tids,
'#default_value' => isset($value[$term->tid]) ? $term->tid : NULL,
'#attributes' => isset($element['#attributes']) ? $element['#attributes'] : NULL,
'#ajax' => array(
'callback' => '_term_reference_tree_item_changed_ajax_callback',
'event' => 'change',
'message' => '',
)
);
if ($e['#type'] == 'radio') {
$parents_for_id = array_merge($element['#parents'], array($term->tid));
$e['#id'] = \Drupal\Component\Utility\Html::getId('edit-' . implode('-', $parents_for_id));
$e['#parents'] = $element['#parents'];
}
}
else {
$e = array(
'#type' => 'checkbox_tree_label',
'#value' => $term_name,
);
}
$container[$term->tid] = $e;
if (($depth + 1 <= $element['#max_depth'] || !$element['#max_depth']) && property_exists($term, 'children') && count($term->children) > 0) {
$parents = $parent_tids;
$parents[] = $term->tid;
$container[$term->tid . '-children'] = _term_reference_tree_build_level($element, $term, $form_state, $value, $max_choices, $parents, $depth + 1);
$container['#level_start_minimized'] = $container[$term->tid . '-children']['#level_start_minimized'];
}
return $container;
}
/**
* Themes the term tree display (as opposed to the select widget).
*/
function theme_term_tree_list($variables) {
$element = &$variables['element'];
$data = &$element['#data'];
$tree = [];
// For each selected term.
foreach ($data as $item) {
// Loop if the term ID is not zero.
$values = [];
$tid = $item['target_id'];
$original_tid = $tid;
while ($tid != 0) {
// Unshift the term onto an array.
array_unshift($values, $tid);
// Repeat with parent term.
$tid = _term_reference_tree_get_parent($tid);
}
$current = &$tree;
// For each term in the above array.
foreach ($values as $tid) {
// current[children][term_id] = new array.
if (!isset($current['children'][$tid])) {
$current['children'][$tid] = ['selected' => FALSE];
}
// If this is the last value in the array,
// tree[children][term_id][selected] = true.
if ($tid == $original_tid) {
$current['children'][$tid]['selected'] = TRUE;
}
$current['children'][$tid]['tid'] = $tid;
$current = &$current['children'][$tid];
}
}
$output = '<div class="term-tree-list">';
$output .= _term_reference_tree_output_list_level($element, $tree);
$output .= '</div>';
return $output;
}
/**
* Helper function to get the parent of tid.
*
* @param int $tid
* The term id.
*
* @return int
* Parent term id or 0.
*/
function _term_reference_tree_get_parent($tid) {
$query = "SELECT p.parent_target_id FROM {taxonomy_term__parent} p WHERE p.entity_id = :tid";
$from = 0;
$count = 1;
$args = [':tid' => $tid];
$database = \Drupal::database();
$result = $database->queryRange($query, $from, $count, $args);
$parent_tid = 0;
foreach ($result as $term) {
$parent_tid = $term->parent_target_id;
}
return $parent_tid;
}
/**
* Helper function to output a single level of the term reference tree display.
*/
function _term_reference_tree_output_list_level(&$element, &$tree) {
$output = '';
$langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
if (isset($tree['children']) && is_array($tree['children']) && count($tree['children']) > 0) {
$output = '<ul class="term">';
foreach ($tree['children'] as &$item) {
if (isset($item['tid'])) {
$term = \Drupal\taxonomy\Entity\Term::load($item['tid']);
$url = $term->toUrl();
$uri['options']['html'] = TRUE;
$class = $item['selected'] ? 'selected' : 'unselected';
$output .= '<li class="' . $class . '">';
$t = NULL;
$term_name = '';
if (\Drupal::moduleHandler()
->moduleExists('locale') && !empty($term->tid)) {
$t = $term;
if ($t && $t->hasTranslation($langcode)) {
$term_name = $t->getTranslation($langcode)->label();
}
}
if (empty($term_name)) {
$term_name = $term->label();
}
$output .= \Drupal::service('link_generator')
->generate($term_name, $url);
if (isset($item['children'])) {
$output .= _term_reference_tree_output_list_level($element, $item);
}
$output .= '</li>';
}
}
$output .= '</ul>';
}
return $output;
}
/**
* Helper function to output a dragtable as track_list.
*/
function _term_reference_tree_build_track_list_order($value, $options){
// define the tabledrag container
$table = array(
'#type' => 'table',
'#prefix' => '<aside class="term-reference-tree-track-list">',
'#suffix' => '</aside>',
'#header' => array('Label', 'weight', 'remove'),
'#tabledrag' => array(
array(
'action' => 'order',
'relationship' => 'sibling',
'group' => 'tracklist-order-weight',
),
),
);
// define the table rows
$index = 0;
foreach ($value as $key) {
$table[$key] = [
'#attributes' => array(
'class' => ['draggable']
),
'#weight' => $index,
'label' => array(
'#plain_text' => $options[$key],
),
'weight' => array(
'#type' => 'weight',
'#title' => t('Weight for @title', array('@title' => $options[$key])),
'#title_display' => 'invisible',
'#default_value' => $index,
// Classify the weight element for #tabledrag.
'#attributes' => array('class' => array('tracklist-order-weight')),
),
'remove' => array(
'#type' => 'button',
'#value' => 'remove',
'#attributes' => array(
'term-reference-tree-key' => $key,
)
)
];
$index ++;
}
return $table;
}
function _term_reference_tree_item_changed_ajax_callback(array &$form, FormState $form_state){
$trigger = $form_state->getTriggeringElement(); // get the trigger element (a term_ref_tree checkbox)
$parent = $trigger['#parents'][0]; // get the element's parent field name
$track_list_form = $form[$parent]['widget']['track_list']; // extract the track_list form part
// ajax response
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('.term-reference-tree-track-list', $track_list_form));
return $response;
}
function _term_reference_tree_get_flatten_selected_values($tree){
$selected = [];
foreach ($tree as $key => $value) {
if ( array_key_exists($key, $value) ) {
if( $value[$key] == $key ){
$selected[] = $key;
}
}
if( array_key_exists($key.'-children', $value) ){
$selected += _term_reference_tree_get_flatten_selected_values($value[$key.'-children']);
}
}
return $selected;
}