added term_reference_tree contrib module

This commit is contained in:
Bachir Soussi Chiadmi 2019-06-24 10:06:27 +02:00
parent d9e494e6db
commit 9ac8f44cf3
21 changed files with 1735 additions and 5 deletions

View File

@ -26,12 +26,12 @@ dependencies:
- node.type.materiau - node.type.materiau
module: module:
- computed_field - computed_field
- cshs
- field_group - field_group
- file - file
- image - image
- materio_samples - materio_samples
- path - path
- term_reference_tree
- text - text
- video_embed_field - video_embed_field
- workflow - workflow
@ -295,11 +295,13 @@ content:
field_thesaurus: field_thesaurus:
weight: 11 weight: 11
settings: settings:
parent: 0 start_minimized: true
level_labels: '' select_parents: true
force_deepest: false cascading_selection: 0
max_depth: 0
leaves_only: false
third_party_settings: { } third_party_settings: { }
type: cshs type: term_reference_tree
region: content region: content
field_video: field_video:
weight: 14 weight: 14

View File

@ -139,6 +139,7 @@ module:
telephone: 0 telephone: 0
telephone_formatter: 0 telephone_formatter: 0
telephone_validation: 0 telephone_validation: 0
term_reference_tree: 0
text: 0 text: 0
token: 0 token: 0
toolbar: 0 toolbar: 0

View File

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

@ -0,0 +1,19 @@
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'
max_depth:
type: integer
label: 'Maximum Depth'

View File

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

After

Width:  |  Height:  |  Size: 765 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 469 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 518 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 224 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 213 B

View File

@ -0,0 +1,99 @@
<?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[] = _term_reference_tree_build_level($element, $tree, $form_state, $value, $element['#max_choices'], [], 1);
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

@ -0,0 +1,24 @@
<?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

@ -0,0 +1,24 @@
<?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

@ -0,0 +1,24 @@
<?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

@ -0,0 +1,55 @@
<?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

@ -0,0 +1,209 @@
<?php
namespace Drupal\term_reference_tree\Plugin\Field\FieldWidget;
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,
'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['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('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['#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']]);
}
}
}
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

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

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

@ -0,0 +1,298 @@
(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 track list. If so, add the
//currently selected items to it.
if($(this).hasClass('term-reference-tree-track-list-shown')) {
var track_list_container = $(this).find('.term-reference-tree-track-list');
//Var to track whether using checkboxes or radio buttons.
var input_type =
( $(this).has('input[type=checkbox]').length > 0 ) ? 'checkbox' : 'radio';
//Find all the checked controls.
var checked_controls = $(this).find('input[type=' + input_type + ']:checked');
//Get their labels.
var labels = checked_controls.next();
var label_element;
//For each label of the checked boxes, add item to the track list.
labels.each(function(index) {
label_element = $(labels[index]);
addItemToTrackList(
track_list_container, //Where to add new item.
label_element.html(), //Text of new item.
$(label_element).attr('for'), //Id of control new item is for.
input_type //checkbox or radio
);
}); //End labels.each
//Show "nothing selected" message, if needed.
showNothingSelectedMessage(track_list_container);
//Event - when an element on the track list is clicked on:
// 1. Delete it.
// 2. Uncheck the associated checkbox.
//The event is bound to the track list container, not each element.
$(track_list_container).click(function(event){
//Remove the "nothing selected" message if showing - add it later if needed.
//removeNothingSelectedMessage(track_list_container);
var event_target = $(event.target);
var control_id = event_target.data('control_id');
if(control_id) {
event_target.remove();
var checkbox = $('#' + control_id);
checkbox.removeAttr('checked');
checkMaxChoices(tree, checkbox);
//Show "nothing selected" message, if needed.
showNothingSelectedMessage(track_list_container);
}
});
//Change track list when controls are clicked.
$(this).find('.form-' + input_type).change(function(event){
//Remove the "nothing selected" message if showing - add it later if needed.
removeNothingSelectedMessage(track_list_container);
var event_target = $(event.target);
var control_id = event_target.attr('id');
if ( event_target.attr('checked') ) {
//Control checked - add item to the track list.
label_element = event_target.next();
addItemToTrackList(
track_list_container, //Where to add new item.
label_element.html(), //Text of new item.
$(label_element).attr('for'), //Id of control new item is for.
input_type //checkbox or radio
);
}
else {
//Checkbox unchecked. Remove from the track list.
$('#' + control_id + '_list').remove();
}
//Show "nothing selected" message, if needed.
showNothingSelectedMessage(track_list_container);
}); //End process checkbox changes.
} //End Want a track list.
//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.
});
}
};
/**
* Add a new item to the track list.
* If more than one item can be selected, the new item is positioned to
* match the order of the terms in the checkbox tree.
*
* @param track_list_container Container where the new item will be added.
*
* @param item_text Text of the item to add.
*
* @param control_id Id of the checkbox/radio control the item matches.
*
* @param control_type Control type - 'checkbox' or 'radio'.
*/
function addItemToTrackList(track_list_container, item_text, control_id, control_type) {
var new_item = $('<li class="track-item">' + item_text + '</li>');
new_item.data('control_id', control_id);
//Add an id for easy finding of the item.
new_item.attr('id', control_id + '_list');
//Process radio controls - only one item can be selected.
if ( control_type == 'radio') {
//Find the existing element on the track list, if there is one.
var current_items = track_list_container.find('li');
//If there are no items on the track list, add the new item.
if ( current_items.length == 0 ) {
track_list_container.append(new_item);
}
else {
//There is an item on the list.
var current_item = $(current_items.get(0));
//Is the item we want to add different from what is there?
if ( current_item.data('control_id') != control_id ) {
//Remove exiting element from track list, and add the new one.
current_item.remove();
track_list_container.append(new_item);
}
}
return;
}
//Using checkboxes, so there can be more than one selected item.
//Find the right place to put the new item, to match the order of the
//checkboxes.
var list_items = track_list_container.find('li');
var item_comparing_to;
//Flag to tell whether the item was inserted.
var inserted_flag = false;
list_items.each(function(index){
item_comparing_to = $(list_items[index]);
//If item is already on the track list, do nothing.
if ( control_id == item_comparing_to.data('control_id') ) {
inserted_flag = true;
return false; //Returning false stops the loop.
}
else if ( control_id < item_comparing_to.data('control_id') ) {
//Add it here.
item_comparing_to.before(new_item);
inserted_flag = true;
return false; //Returning false stops the loop.
}
});
//If not inserted yet, add new item at the end of the track list.
if ( ! inserted_flag ) {
track_list_container.append(new_item);
}
}
/**
* Show the 'nothing selected' message if it applies.
*
* @param track_list_container Where the message is to be shown.
*/
function showNothingSelectedMessage(track_list_container) {
//Is the message there already?
var message_showing =
(track_list_container.find('.term_ref_tree_nothing_message').length != 0);
//Number of real items showing.
var num_real_items_showing =
message_showing
? track_list_container.find('li').length - 1
: track_list_container.find('li').length;
if ( num_real_items_showing == 0 ) {
//No items showing, so show the message.
if ( ! message_showing ) {
track_list_container.append(
'<li class="term_ref_tree_nothing_message">' + termReferenceTreeNothingSelectedText + '</li>'
);
}
}
else { // !(num_real_items_showing == 0)
//There are real items.
if ( message_showing ) {
track_list_container.find('.term_ref_tree_nothing_message').remove();
}
}
}
/**
* Remove the 'nothing selected' message. Makes processing easier.
*
* @param track_list_container Where the message is shown.
*/
function removeNothingSelectedMessage(track_list_container) {
track_list_container.find('.term_ref_tree_nothing_message').remove();
}
// 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')) {
var track_list_container = item.find('.term-reference-tree-track-list');
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);
if(track_list_container) {
var label_element = $(this).next();
addItemToTrackList(
track_list_container, //Where to add new item.
label_element.html(), //Text of new item.
$(label_element).attr('for'), //Id of control new item is for.
(item.has('input[type=checkbox]').length > 0) ? 'checkbox' : 'radio'
);
}
});
}
}
}
}
})(jQuery);

View File

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

@ -0,0 +1,498 @@
<?php
use \Drupal\Core\Render\Element;
/**
* 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' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
);
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;
}