Commit e63c0449 by Manzar Hussain

add product detail template

parent 5621084e
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
CONTENTS OF THIS FILE
--------------------
* Introduction
* Requirements
* Installation
* Configuration
* Maintainers
INTRODUCTION
------------
The Views Tree module provides a Views style plugin to display a tree of
elements using the adjacency model.
* For a full description of the module visit
https://www.drupal.org/project/views_tree
* To submit bug reports and feature suggestions, or to track changes visit
https://www.drupal.org/project/issues/views_tree
REQUIREMENTS
------------
This module requires no modules outside of Drupal core.
INSTALLATION
------------
* Install the Views Tree module as you would normally install a contributed
Drupal module. Visit https://www.drupal.org/node/1897420 for further
information.
CONFIGURATION
-------------
1. Navigate to Administration > Extend and enable the module.
2. Navigate to Administration > Structure > Views and select "Add new view"
to create a new view.
3. Select what information will be displayed and how it will be sorted by
using the appropriate dropdown.
4. Select the display format "unformatted list" of "fields". Save and
edit.
5. Add the appropriate fields.
6. Using the Advanced settings create a relationship of the information to
be displayed in the hierarchy.
7. Edit the format of the view to "TreeHelper (Adjacency model)".
8. Select unordered or ordered list type. Most use cases will prefer
Unordered. Select the field with the unique identifier for each record
from the "Main field" dropdown menu. Select the field that contains the
unique identifier of the record's parent from the "Parent field"
dropdown. Apply changes.
MAINTAINERS
-----------
* Daniel Wehner (dawehner) - https://www.drupal.org/u/dawehner
* Jeff Geerling (geerlingguy) - https://www.drupal.org/u/geerlingguy
* Larry Garfield (Crell) - https://www.drupal.org/u/crell
# Schema for the Views Tree module.
views.style.tree:
type: views_style
label: 'Views Tree'
mapping:
type:
type: string
label: 'List type'
main_field:
type: string
label: 'Main field'
parent_field:
type: string
label: 'Parent field'
collapsible_tree:
type: string
label: 'Collapsible list'
views.style.tree_table:
type: views_style
label: 'Views Tree (table)'
mapping:
main_field:
type: string
label: 'Main field'
parent_field:
type: string
label: 'Parent field'
display_hierarchy_column:
type: string
label: 'Column in which to represent the hierarchy'
.views_tree_collapsed,
.views_tree_expanded,
.views_tree_collapsed ul li,
.views_tree_expanded ul li {
list-style-type: none;
}
.views_tree_link {
width: 15px;
height: 100%;
clear: both;
float: left;
}
.views_tree_link a {
margin: 0 5px 0 0;
text-indent: -9999px;
display: block;
}
.views_tree_link_collapsed a {
background: #ffffff url(../images/menu-collapsed.png) no-repeat center center;
}
.views_tree_link_expanded a {
background: #ffffff url(../images/menu-expanded.png) no-repeat center center;
}
/**
* CSS for laying out a hierarchy within an HTML table.
*
* While this could be done more elegantly with JS, this allows for non-JS browsers to properly layout the hierarchy.
*
* The starting point is 20px, as Bartik pads cells with 9px.
*/
tr[data-hierarchy-level='2'] .views-tree-hierarchy-cell {
padding-left: 20px;
}
tr[data-hierarchy-level='3'] .views-tree-hierarchy-cell {
padding-left: 30px;
}
tr[data-hierarchy-level='4'] .views-tree-hierarchy-cell {
padding-left: 40px;
}
tr[data-hierarchy-level='5'] .views-tree-hierarchy-cell {
padding-left: 50px;
}
tr[data-hierarchy-level='6'] .views-tree-hierarchy-cell {
padding-left: 60px;
}
tr[data-hierarchy-level='7'] .views-tree-hierarchy-cell {
padding-left: 70px;
}
tr[data-hierarchy-level='8'] .views-tree-hierarchy-cell {
padding-left: 80px;
}
/**
* @file
*/
(function ($, Drupal) {
'use strict';
Drupal.behaviors.views_tree = {
attach: function (context, settings) {
var views_tree_settings = settings.views_tree_settings;
for (var views_tree_settings_id in views_tree_settings) {
var views_tree_name = views_tree_settings[views_tree_settings_id][0];
$.each($(".view-id-" + views_tree_name + " .view-content li"), function () {
var count = $(this).find("li").length;
if (count > 0) {
$(this).addClass('views_tree_parent');
$(this).children('ul').addClass("item-list");
if (views_tree_settings[views_tree_settings_id][1] != "collapsed") {
$(this).addClass('views_tree_expanded');
// @todo Use Drupal.theme()
$(this).prepend('<div class="views_tree_link views_tree_link_expanded"><a href="#">' + Drupal.t('Operation') + '</a></div>');
}
else {
$(this).addClass('views_tree_collapsed');
$(this).prepend('<div class="views_tree_link views_tree_link_collapsed"><a href="#">' + Drupal.t('Operation') + '</a></div>');
$(this).children(".item-list").hide();
}
}
});
}
$('.views_tree_link a', context).on('click', function (e) {
e.preventDefault();
if ($(this).parent().hasClass('views_tree_link_expanded')) {
$(this).parent().parent().children(".item-list").slideUp();
$(this).parent().addClass('views_tree_link_collapsed');
$(this).parent().removeClass('views_tree_link_expanded');
}
else {
$(this).parent().parent().children(".item-list").slideDown();
$(this).parent().addClass('views_tree_link_expanded');
$(this).parent().removeClass('views_tree_link_collapsed');
}
});
}
};
})(jQuery, Drupal);
<?php
namespace Drupal\views_tree\Plugin\EntityReferenceSelection;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;
use Drupal\views_tree\TreeHelper;
use Drupal\views_tree\ViewsResultTreeValues;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Plugin implementation of the 'selection' entity_reference.
*
* @EntityReferenceSelection(
* id = "views_tree",
* label = @Translation("TreeHelper (Adjacency model)"),
* group = "views_tree",
* weight = 0
* )
*/
class TreeViewsSelection extends ViewsSelection {
/**
* The tree helper.
*
* @var \Drupal\views_tree\TreeHelper
*/
protected $tree;
/**
* The views result tree values.
*
* @var \Drupal\views_tree\ViewsResultTreeValues
*/
protected $viewsResultTreeValues;
/**
* Constructs the ER views selection plugin.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager service.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler service.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
* @param \Drupal\views_tree\TreeHelper $tree
* The tree helper.
* @param \Drupal\views_tree\ViewsResultTreeValues $views_result_tree_values
* The views result tree values service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, AccountInterface $current_user, TreeHelper $tree, ViewsResultTreeValues $views_result_tree_values) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_manager, $module_handler, $current_user);
$this->tree = $tree;
$this->viewsResultTreeValues = $views_result_tree_values;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity.manager'),
$container->get('module_handler'),
$container->get('current_user'),
$container->get('views_tree.tree'),
$container->get('views_tree.views_tree_values')
);
}
/**
* {@inheritdoc}
*/
public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
$handler_settings = $this->configuration['handler_settings'];
$display_name = $handler_settings['view']['display_name'];
$arguments = $handler_settings['view']['arguments'];
$result = [];
if ($this->initializeView($match, $match_operator, $limit)) {
// Get the results.
$result = $this->view->executeDisplay($display_name, $arguments);
}
$this->applyTreeOnResult($this->view, $this->view->result);
$tree = $this->tree->getTreeFromResult($this->view->result);
$return = [];
if ($result) {
$this->tree->applyFunctionToTree($tree, function (ResultRow $row) use (&$return) {
$entity = $row->_entity;
$return[$entity->bundle()][$entity->id()] = str_repeat('-', $row->views_tree_depth) . $entity->label();
return NULL;
});
}
return $return;
}
/**
* Applies a tree to a result set.
*
* @param \Drupal\views\ViewExecutable $view
* The view.
* @param \Drupal\views\ResultRow[] $result
* The result set.
*/
protected function applyTreeOnResult(ViewExecutable $view, array $result) {
$this->viewsResultTreeValues->setTreeValues($view, $result);
}
}
<?php
namespace Drupal\views_tree\Plugin\views\style;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\style\HtmlList;
use Drupal\views_tree\TreeStyleTrait;
/**
* Style plugin to render each item as hierarchy.
*
* @ingroup views_style_plugins
*
* @ViewsStyle(
* id = "tree",
* title = @Translation("Tree (list)"),
* help = @Translation("Display the results as a nested tree"),
* theme = "views_tree",
* display_types = {"normal"}
* )
*/
class Tree extends HtmlList {
use TreeStyleTrait;
/**
* {@inheritdoc}
*/
protected $usesRowPlugin = TRUE;
/**
* {@inheritdoc}
*/
protected $usesFields = TRUE;
/**
* {@inheritdoc}
*/
protected $usesGrouping = FALSE;
/**
* {@inheritdoc}
*/
protected function defineOptions() {
$options = parent::defineOptions();
$this->defineCommonOptions($options);
$options['class'] = ['default' => ''];
$options['wrapper_class'] = ['default' => 'item-list'];
$options['collapsible_tree'] = ['default' => 0];
return $options;
}
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$this->getCommonOptionsForm($form, $form_state);
$events = ['click' => $this->t('On Click'), 'mouseover' => $this->t('On Mouseover')];
$form['type']['#description'] = $this->t('Whether to use an ordered or unordered list for the retrieved items. Most use cases will prefer Unordered.');
// Unused by the views tree list style at this time.
unset($form['wrapper_class']);
unset($form['class']);
$form['collapsible_tree'] = [
'#type' => 'radios',
'#title' => $this->t('Collapsible view'),
'#default_value' => $this->options['collapsible_tree'],
'#options' => [
0 => $this->t('Off'),
'expanded' => $this->t('Expanded'),
'collapsed' => $this->t('Collapsed'),
],
];
}
}
<?php
namespace Drupal\views_tree\Plugin\views\style;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Form\FormStateInterface;
/**
* Style plugin to render each item as hierarchy.
*
* @ingroup views_style_plugins
*
* @ViewsStyle(
* id = "tree_entity_reference_selection",
* title = @Translation("TreeHelper (Adjacency model)"),
* help = @Translation("Display the results as a nested tree"),
* theme = "views_tree",
* display_types = {"entity_reference"},
* )
*/
class TreeERSelection extends Tree {
/**
* {@inheritdoc}
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['search_fields'] = ['default' => NULL];
return $options;
}
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$options = $this->displayHandler->getFieldLabels(TRUE);
$form['search_fields'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Search fields'),
'#options' => $options,
'#required' => TRUE,
'#default_value' => $this->options['search_fields'],
'#description' => $this->t('Select the field(s) that will be searched when using the autocomplete widget.'),
'#weight' => -3,
];
}
/**
* {@inheritdoc}
*/
public function render() {
if (!empty($this->view->live_preview)) {
return parent::render();
}
// Group the rows according to the grouping field, if specified.
$sets = $this->renderGrouping($this->view->result, $this->options['grouping']);
// Grab the alias of the 'id' field added by
// entity_reference_plugin_display.
$id_field_alias = $this->view->storage->get('base_field');
// @todo We don't display grouping info for now. Could be useful for select
// widget, though.
$results = [];
foreach ($sets as $records) {
foreach ($records as $values) {
$results[$values->{$id_field_alias}] = $this->view->rowPlugin->render($values);
// Sanitize HTML, remove line breaks and extra whitespace.
$results[$values->{$id_field_alias}]['#post_render'][] = function ($html, array $elements) {
return Xss::filterAdmin(preg_replace('/\s\s+/', ' ', str_replace("\n", '', $html)));
};
}
}
return $results;
}
/**
* {@inheritdoc}
*/
public function evenEmpty() {
return TRUE;
}
}
<?php
namespace Drupal\views_tree\Plugin\views\style;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\style\Table;
use Drupal\views_tree\TreeStyleTrait;
/**
* Defines a tree-based table display.
*
* @ingroup views_style_plugins
*
* @ViewsStyle(
* id = "tree_table",
* title = @Translation("Tree (table)"),
* help = @Translation("Displays the results as a nested tree in a table"),
* theme = "views_tree_table",
* display_types = {"normal"}
* )
*/
class TreeTable extends Table {
use TreeStyleTrait;
/**
* {@inheritdoc}
*/
protected function defineOptions() {
$options = parent::defineOptions();
$this->defineCommonOptions($options);
$options['display_hierarchy_column'] = ['default' => ''];
return $options;
}
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$this->getCommonOptionsForm($form, $form_state);
// This is the column the hierarchy will actually be displayed in.
$form['display_hierarchy_column'] = [
'#type' => 'select',
'#title' => $this->t('Hierarchy display column'),
'#description' => $this->t('The table column in which to represent the hierarchy. This is typically a title/label field.'),
'#required' => TRUE,
'#options' => $this->displayHandler->getFieldLabels(),
'#default_value' => $this->options['display_hierarchy_column'],
];
}
}
<?php
namespace Drupal\views_tree;
use Drupal\Core\Template\Attribute;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;
/**
* The tree helper service.
*/
class TreeHelper {
/**
* The tree values service.
*
* @var \Drupal\views_tree\ViewsResultTreeValues
*/
protected $treeValues;
/**
* Constructs the tree helper.
*
* @param \Drupal\views_tree\ViewsResultTreeValues $tree_values
* The tree values service.
*/
public function __construct(ViewsResultTreeValues $tree_values) {
$this->treeValues = $tree_values;
}
/**
* Builds a render tree from an executed view.
*/
public function buildRenderTree(ViewExecutable $view, array $rows) {
$result = $view->result;
$this->treeValues->setTreeValues($view, $result);
$result_tree = $this->getTreeFromResult($result);
return $this->applyFunctionToTree($result_tree, function (ResultRow $row) use ($rows) {
return $rows[$row->index];
});
}
/**
* Adds hierarchical data attributes to the tree data.
*/
public function addDataAttributes(TreeItem $tree, $nesting = 0) {
$node = $tree->getNode();
if (isset($node['attributes']) && $node['attributes'] instanceof Attribute) {
$node['attributes']->setAttribute('data-hierarchy-level', $nesting);
}
$nesting++;
foreach ($tree->getLeaves() as $leaf) {
$this->addDataAttributes($leaf, $nesting);
}
}
/**
* Builds a tree from a views result.
*
* @param array $result
* The views results with views_tree_main and views_tree_parent set.
*
* @return \Drupal\views_tree\TreeItem
* A tree representation.
*/
public function getTreeFromResult(array $result) {
$groups = $this->groupResultByParent($result);
return $this->getTreeFromGroups($groups);
}
/**
* Get a tree from given groups.
*
* @param array $groups
* The groups.
* @param string $current_group
* The current group.
*
* @return \Drupal\views_tree\TreeItem
* The tree for the given groups.
*/
protected function getTreeFromGroups(array $groups, $current_group = '0') {
$return = new TreeItem(NULL);
if (empty($groups[$current_group])) {
return $return;
}
foreach ($groups[$current_group] as $item) {
$tree_item = new TreeItem($item);
$return->addLeave($tree_item);
$tree_item->setLeaves($this->getTreeFromGroups($groups, $item->views_tree_main)->getLeaves());
}
return $return;
}
/**
* Groups results by parent.
*
* @param array $result
* The result set.
*
* @return array
* Result grouped by parent.
*/
protected function groupResultByParent(array $result) {
$return = [];
foreach ($result as $row) {
$return[$row->views_tree_parent][] = $row;
}
return $return;
}
/**
* Applies a given callable to each row and leaf.
*
* @param \Drupal\views_tree\TreeItem $tree
* The tree item.
* @param callable $callable
* The callable.
*
* @return \Drupal\views_tree\TreeItem
* The new tree item.
*/
public function applyFunctionToTree(TreeItem $tree, callable $callable) {
if (($node = $tree->getNode()) && $node !== NULL) {
$new_node = $callable($tree->getNode());
}
else {
$new_node = NULL;
}
$new_tree = new TreeItem($new_node);
foreach ($tree->getLeaves() as $leave) {
$new_tree->addLeave($this->applyFunctionToTree($leave, $callable));
}
return $new_tree;
}
}
<?php
namespace Drupal\views_tree;
/**
* Defines a tree item class.
*/
class TreeItem implements \IteratorAggregate {
/**
* The main node in the tree.
*
* @var mixed
*/
protected $node;
/**
* Leaves of the main node.
*
* @var \Drupal\views_tree\TreeItem[]
*/
protected $leaves = [];
/**
* Creates a new TreeItem instance.
*
* @param mixed $node
* The main tree node to set.
* @param array $leaves
* An optional array of leaves to set.
*/
public function __construct($node, array $leaves = []) {
$this->setNode($node);
$this->setLeaves($leaves);
}
/**
* Get the tree node.
*
* @return mixed
* The tree node.
*/
public function getNode() {
return $this->node;
}
/**
* Sets the node.
*
* @param mixed $node
* The node to set.
*/
public function setNode($node) {
$this->node = $node;
}
/**
* Get the leaves.
*
* @return \Drupal\views_tree\TreeItem[]
* An array of tree item leaves.
*/
public function getLeaves() {
return $this->leaves;
}
/**
* {@inheritdoc}
*/
public function getIterator() {
return new \ArrayIterator($this->leaves);
}
/**
* Sets the leaves.
*
* @param array $leaves
* An array of leaves. If they are not already an instance of
* \Drupal\views_tree\TreeItem, each one will be converted.
*
* @return $this
* The instance of the TreeItem.
*/
public function setLeaves(array $leaves) {
foreach ($leaves as &$leave) {
if (!$leave instanceof static) {
$leave = new TreeItem($leave);
}
}
$this->leaves = $leaves;
return $this;
}
/**
* Adds a leaf.
*
* @param mixed $item
* An item to add. If not an instance of \Drupal\views_tree\TreeItem it will
* be converted.
*
* @return $this
*/
public function addLeave($item) {
if (!$item instanceof static) {
$item = new TreeItem($item);
}
$this->leaves[] = $item;
return $this;
}
}
<?php
namespace Drupal\views_tree;
use Drupal\Core\Form\FormStateInterface;
/**
* Contains common code for list and table tree style displays.
*
* @property \Drupal\views\Plugin\views\display\DisplayPluginBase $displayHandler
* @property array $options
*/
trait TreeStyleTrait {
/**
* Gather common options.
*/
protected function defineCommonOptions(array &$options) {
$options['main_field'] = ['default' => ''];
$options['parent_field'] = ['default' => ''];
}
/**
* Builds common form elements for the options form.
*
* @param array $form
* The form definition.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*/
protected function getCommonOptionsForm(array &$form, FormStateInterface $form_state) {
$fields = ['' => $this->t('<None>')];
foreach ($this->displayHandler->getHandlers('field') as $field => $handler) {
$fields[$field] = $handler->adminLabel();
}
$form['main_field'] = [
'#type' => 'select',
'#title' => $this->t('Main field'),
'#options' => $fields,
'#default_value' => $this->options['main_field'],
'#description' => $this->t('Select the field with the unique identifier for each record.'),
'#required' => TRUE,
];
$form['parent_field'] = [
'#type' => 'select',
'#title' => $this->t('Parent field'),
'#options' => $fields,
'#default_value' => $this->options['parent_field'],
'#description' => $this->t("Select the field that contains the unique identifier of the record's parent."),
];
}
}
<?php
namespace Drupal\views_tree;
use Drupal\Core\Messenger\MessengerTrait;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ViewExecutable;
/**
* Methods to get result tree based on views results.
*/
class ViewsResultTreeValues {
use MessengerTrait;
use StringTranslationTrait;
/**
* Sets tree values given a view and result set.
*
* @param \Drupal\views\ViewExecutable $view
* The view object.
* @param \Drupal\views\ResultRow[] $result
* The result set.
*
* @return array
* The result.
*/
public function setTreeValues(ViewExecutable $view, array $result) {
$fields = $view->field;
$options = $view->getStyle()->options;
$parents = [];
if (!$fields[$options['main_field']] instanceof FieldPluginBase) {
$this->messenger()->addError($this->t('Main field is invalid: %field', ['%field' => $options['main_field']]), 'error');
return [];
}
if (!$fields[$options['parent_field']] instanceof FieldPluginBase) {
$this->messenger()->addError($this->t('Parent field is invalid: %field', ['%field' => $options['parent_field']]), 'error');
return [];
}
// The field structure of Field API fields in a views result object is...
// ridiculous. To avoid having to deal with it, we'll first iterate over all
// records and normalize out the main and parent IDs to new properties. That
// vastly simplifies the code that follows. This particular magic
// incantation extracts the value from each record for the appropriate field
// specified by the user. It then normalizes that value down to just an int,
// even though in some cases it is an array. See views_tree_normalize_key().
// Finally, we build up a list of all main keys in the result set so that we
// can normalize top-level records below.
foreach ($result as $i => $record) {
$result[$i]->views_tree_main = $this->normalizeKey($fields[$options['main_field']]->getValue($record), $fields[$options['main_field']]);
$result[$i]->views_tree_parent = $this->normalizeKey($fields[$options['parent_field']]->getValue($record), $fields[$options['parent_field']]);
$parents[] = $record->views_tree_main;
}
// Normalize the top level of records to all point to 0 as their parent
// We only have to do this once, so we do it here in the wrapping function.
foreach ($result as $i => $record) {
if (!in_array($record->views_tree_parent, $parents)) {
$result[$i]->views_tree_parent = 0;
}
}
// Add the depth onto the result.
foreach ($result as $row) {
$current_row = $row;
$depth = 0;
while ($current_row->views_tree_parent != '0') {
$depth++;
if ($parent_row = $this->findRowByParent($result, $current_row->views_tree_parent)) {
$current_row = $parent_row;
}
else {
break;
}
}
$row->views_tree_depth = $depth;
}
return $result;
}
/**
* Finds a row given a parent.
*
* @param \Drupal\views\ResultRow[] $result
* The view result array.
* @param mixed $parent_id
* The parent ID.
*
* @return \Drupal\views\ResultRow|null
* The corresponding row if foundm, NULL otherwise.
*/
protected function findRowByParent(array $result, $parent_id) {
foreach ($result as $row) {
if ($parent_id == $row->views_tree_main) {
return $row;
}
}
}
/**
* Normalize a value out of the record to an int.
*
* If the field in question comes from Field API, then it will be an array,
* not an int. We need to detect that and extract the int value we want from
* it. Note that because Field API structures are so free-form, we have to
* specifically support each field type. For now we support entityreference
* (target_id), nodereference (nid), userreference (uid), organic groups
* (gid), and taxonomyreference (tid).
*
* @param mixed $value
* The value to normalize. It should be either an int or an array. If an
* int, it is returned unaltered. If it's an array, we extract the int we
* want and return that.
* @param \Drupal\views\Plugin\views\field\FieldPluginBase $field
* Metadata about the field we are extracting information from.
*
* @return int
* The value of this key, normalized to an int.
*/
protected function normalizeKey($value, FieldPluginBase $field) {
if (is_array($value) && count($value)) {
return reset($value);
}
else {
return $value ? $value : 0;
}
}
}
{#
/**
* @file
* Default theme implementation for displaying a view as a table.
*
* Available variables (from core views_view_table):
* - attributes: Remaining HTML attributes for the element.
* - class: HTML classes that can be used to style contextually through CSS.
* - title : The title of this group of rows.
* - header: The table header columns.
* - attributes: Remaining HTML attributes for the element.
* - content: HTML classes to apply to each header cell, indexed by
* the header's key.
* - default_classes: A flag indicating whether default classes should be
* used.
* - caption_needed: Is the caption tag needed.
* - caption: The caption for this table.
* - accessibility_description: Extended description for the table details.
* - accessibility_summary: Summary for the table details.
* - rows: Table row items. Rows are keyed by row number.
* - attributes: HTML classes to apply to each row.
* - columns: Row column items. Columns are keyed by column number.
* - attributes: HTML classes to apply to each column.
* - content: The column content.
* - default_classes: A flag indicating whether default classes should be
* used.
* - responsive: A flag indicating whether table is responsive.
* - sticky: A flag indicating whether table header is sticky.
*
* Available variables from views tree:
* - items: A list of items. Each item contains:
* - attributes: HTML attributes to be applied to each list item.
* - value: The content of the list element.
*
* @see template_preprocess_views_tree_table()
*
* @ingroup themeable
*/
#}
{%
set classes = [
'cols-' ~ header|length,
responsive ? 'responsive-enabled',
sticky ? 'sticky-enabled',
]
%}
{% import _self as views_tree %}
<table{{ attributes.addClass(classes) }}>
{% if caption_needed %}
<caption>
{% if caption %}
{{ caption }}
{% else %}
{{ title }}
{% endif %}
{% if (summary is not empty) or (description is not empty) %}
<details>
{% if summary is not empty %}
<summary>{{ summary }}</summary>
{% endif %}
{% if description is not empty %}
{{ description }}
{% endif %}
</details>
{% endif %}
</caption>
{% endif %}
{% if header %}
<thead>
<tr>
{% for key, column in header %}
{% if column.default_classes %}
{%
set column_classes = [
'views-field',
'views-field-' ~ fields[key],
]
%}
{% endif %}
<th{{ column.attributes.addClass(column_classes).setAttribute('scope', 'col') }}>
{%- if column.wrapper_element -%}
<{{ column.wrapper_element }}>
{%- if column.url -%}
<a href="{{ column.url }}" title="{{ column.title }}">{{ column.content }}{{ column.sort_indicator }}</a>
{%- else -%}
{{ column.content }}{{ column.sort_indicator }}
{%- endif -%}
</{{ column.wrapper_element }}>
{%- else -%}
{%- if column.url -%}
<a href="{{ column.url }}" title="{{ column.title }}">{{ column.content }}{{ column.sort_indicator }}</a>
{%- else -%}
{{- column.content }}{{ column.sort_indicator }}
{%- endif -%}
{%- endif -%}
</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tbody>
{{ views_tree.tree(items) }}
</tbody>
</table>
{% macro tree(items) %}
{% import _self as views_tree %}
{% if items %}
{%- if items -%}
{%- for item in items -%}
{{ views_tree.row(item.node) }}
{{ views_tree.tree(item.leaves) }}
{% endfor %}
{% endif %}
{% endif %}
{% endmacro %}
{% macro row(item) %}
<tr{{ item.attributes }}>
{% for key, column in item.columns %}
{% if column.default_classes %}
{%
set column_classes = [
'views-field'
]
%}
{% for field in column.fields %}
{% set column_classes = column_classes|merge(['views-field-' ~ field]) %}
{% endfor %}
{% endif %}
<td{{ column.attributes.addClass(column_classes) }}>
{%- if column.wrapper_element -%}
<{{ column.wrapper_element }}>
{% for content in column.content %}
{{ content.separator }}{{ content.field_output }}
{% endfor %}
</{{ column.wrapper_element }}>
{%- else -%}
{% for content in column.content %}
{{- content.separator }}{{ content.field_output -}}
{% endfor %}
{%- endif %}
</td>
{% endfor %}
</tr>
{% endmacro %}
{#
/**
* @file
* Default theme implementation for an item list.
*
* Available variables:
* - items: A list of items. Each item contains:
* - attributes: HTML attributes to be applied to each list item.
* - value: The content of the list element.
* - title: The title of the list.
* - list_type: The tag for list element ("ul" or "ol").
* - wrapper_attributes: HTML attributes to be applied to the list wrapper.
* - attributes: HTML attributes to be applied to the list.
* - empty: A message to display when there are no items. Allowed value is a
* string or render array.
* - context: A list of contextual data associated with the list. May contain:
* - list_style: The custom list style.
*
* @see template_preprocess_item_list()
*
* @ingroup themeable
*/
#}
{% import _self as views_tree %}
{{ views_tree.tree(items.leaves, attributes, list_type) }}
{% macro tree(items, attributes, list_type) %}
{% import _self as views_tree %}
{% if context.list_style %}
{%- set attributes = attributes.addClass('item-list__' ~ context.list_style) %}
{% endif %}
{% if items or empty %}
{%- if title is not empty -%}
<h3>{{ title }}</h3>
{%- endif -%}
{%- if items -%}
<{{ list_type }}{{ attributes }}>
{%- for item in items -%}
<li{{ item.attributes }}>{{ item.node }} {{ views_tree.tree(item.leaves, attributes, list_type) }}</li>
{%- endfor -%}
</{{ list_type }}>
{%- else -%}
{{- empty -}}
{%- endif -%}
{%- endif %}
{% endmacro %}
langcode: en
status: true
dependencies:
module:
- entity_test
- views_tree
id: views_tree_test
label: views_tree_test
module: views
description: ''
tag: ''
base_table: entity_test
base_field: id
core: 8.x
display:
default:
display_plugin: default
id: default
display_title: Master
position: 0
display_options:
access:
type: none
options: { }
cache:
type: tag
options: { }
query:
type: views_query
options:
disable_sql_rewrite: false
distinct: false
replica: false
query_comment: ''
query_tags: { }
exposed_form:
type: basic
options:
submit_button: Apply
reset_button: false
reset_button_label: Reset
exposed_sorts_label: 'Sort by'
expose_sort_order: true
sort_asc_label: Asc
sort_desc_label: Desc
pager:
type: none
options:
items_per_page: null
offset: 0
style:
type: tree
options:
row_class: ''
default_row_class: true
type: ul
main_field: id
parent_field: field_test_parent
collapsible_tree: '0'
row:
type: fields
options:
inline: { }
separator: ''
hide_empty: false
default_field_elements: true
fields:
name:
table: entity_test
field: name
id: name
entity_type: null
entity_field: name
plugin_id: field
relationship: none
group_type: group
admin_label: ''
label: ''
exclude: false
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: value
type: string
settings: { }
group_column: value
group_columns: { }
group_rows: true
delta_limit: 0
delta_offset: 0
delta_reversed: false
delta_first_last: false
multi_type: separator
separator: ', '
field_api_classes: false
id:
id: id
table: entity_test
field: id
relationship: none
group_type: group
admin_label: ''
label: ''
exclude: true
alter:
alter_text: false
text: ''
make_link: false
path: ''
absolute: false
external: false
replace_spaces: false
path_case: none
trim_whitespace: false
alt: ''
rel: ''
link_class: ''
prefix: ''
suffix: ''
target: ''
nl2br: false
max_length: 0
word_boundary: true
ellipsis: true
more_link: false
more_link_text: ''
more_link_path: ''
strip_tags: false
trim: false
preserve_tags: ''
html: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: false
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_empty: false
empty_zero: false
hide_alter_empty: true
click_sort_column: value
type: number_integer
settings:
thousand_separator: ''
prefix_suffix: true
group_column: value
group_columns: { }
group_rows: true
delta_limit: 0
delta_offset: 0
delta_reversed: false
delta_first_last: false
multi_type: separator
separator: ', '
field_api_classes: false
entity_type: entity_test
entity_field: id
plugin_id: field
field_test_parent:
id: field_test_parent
table: entity_test__field_test_parent
field: field_test_parent
filters:
type:
id: type
table: entity_test
field: type
value: entity_test
entity_type: entity_test
entity_field: type
plugin_id: string
sorts:
name:
id: name
table: entity_test
field: name
relationship: none
group_type: group
admin_label: ''
order: ASC
exposed: false
expose:
label: ''
plugin_id: standard
header: { }
footer: { }
empty: { }
relationships: { }
arguments: { }
display_extenders: { }
cache_metadata:
max-age: -1
contexts:
- entity_test_view_grants
- 'languages:language_content'
- 'languages:language_interface'
- url.query_args
tags: { }
name: 'Views tree test views'
type: module
description: 'Provides default views for views tree tests.'
package: Testing
# core: 8.x
dependencies:
- drupal:views_tree
# Information added by Drupal.org packaging script on 2018-10-02
version: '8.x-2.0-alpha1'
core: '8.x'
project: 'views_tree'
datestamp: 1538512991
<?php
namespace Drupal\Tests\views_tree\Kernel\Plugin\views\style;
use Drupal\views\Entity\View;
use Drupal\views\Views;
/**
* Tests the views tree list style plugin.
*
* @group views_tree
*
* @coversDefaultClass \Drupal\views_tree\Plugin\views\style\TreeTable
*/
class TreeTableTest extends TreeTestBase {
/**
* {@inheritdoc}
*/
public static $testViews = ['views_tree_test'];
/**
* {@inheritdoc}
*/
protected function setUp($import_test_views = TRUE) {
parent::setUp($import_test_views);
// Change view display to use the tree table style.
/** @var \Drupal\views\ViewEntityInterface $view */
$view = View::load('views_tree_test');
$display =& $view->getDisplay('default');
$display['display_options']['style']['type'] = 'tree_table';
$display['display_options']['style']['options']['display_hierarchy_column'] = 'name';
unset($display['display_options']['style']['options']['type']);
unset($display['display_options']['style']['options']['collapsible_tree']);
// Display the 'id' column so the table has more than a single column.
$display['display_options']['fields']['id']['exclude'] = FALSE;
$view->save();
}
/**
* Tests the tree table style plugin.
*/
public function testTreeTableStyle() {
$view = Views::getView('views_tree_test');
$this->executeView($view);
$this->assertCount(15, $view->result);
// Render the view, which will re-sort the result.
// @see template_preprocess_views_tree_table()
$output = $view->render('default');
$rendered_output = \Drupal::service('renderer')->renderRoot($output);
// Verify parents are properly set in the result.
$result = $view->result;
$this->assertEquals(1, $result[0]->views_tree_parent);
$this->assertEquals(6, $result[11]->views_tree_parent);
// Verify rendered output.
$this->setRawContent($rendered_output);
$rows = $this->xpath('//tbody/tr');
$this->assertEquals(1, (string) $rows[0]->attributes()['data-hierarchy-level']);
$this->assertEquals(2, (string) $rows[1]->attributes()['data-hierarchy-level']);
$this->assertEquals(3, (string) $rows[6]->attributes()['data-hierarchy-level']);
$this->assertEquals(1, (string) $rows[11]->attributes()['data-hierarchy-level']);
// Verify the hierarchy display class is added to the correct cell.
$this->assertContains('views-tree-hierarchy-cell', (string) $rows[0]->td->attributes()->class);
$this->assertNotContains('views-tree-hierarchy-cell', (string) $rows[0]->td[1]->attributes()->class);
}
}
<?php
namespace Drupal\Tests\views_tree\Kernel\Plugin\views\style;
use Drupal\views\Views;
/**
* Tests the views tree list style plugin.
*
* @group views_tree
*
* @coversDefaultClass \Drupal\views_tree\Plugin\views\style\Tree
*/
class TreeTest extends TreeTestBase {
/**
* {@inheritdoc}
*/
public static $testViews = ['views_tree_test'];
/**
* Tests the tree style plugin.
*/
public function testTreeStyle() {
$view = Views::getView('views_tree_test');
$this->executeView($view);
$this->assertCount(15, $view->result);
// Render the view, which will re-sort the result.
// @see template_preprocess_views_tree()
$output = $view->render('default');
$rendered_output = \Drupal::service('renderer')->renderRoot($output);
// Verify parents are properly set in the result.
$result = $view->result;
$this->assertEquals(1, $result[0]->views_tree_parent);
$this->assertEquals(6, $result[11]->views_tree_parent);
// Verify rendered output.
$this->setRawContent($rendered_output);
$rows = $this->xpath('//span[contains(@class, "field-content")]');
$this->assertEquals('parent 1', (string) $rows[0]);
$this->assertEquals('child 1 (parent 1)', (string) $rows[1]);
$this->assertEquals('parent 2', (string) $rows[4]);
$this->assertEquals('grand child 1 (c 1, p 2)', (string) $rows[6]);
$this->assertEquals('parent 3', (string) $rows[11]);
}
}
<?php
namespace Drupal\Tests\views_tree\Kernel\Plugin\views\style;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\Tests\field\Traits\EntityReferenceTestTrait;
use Drupal\Tests\views\Kernel\ViewsKernelTestBase;
use Drupal\views\Tests\ViewTestData;
/**
* Base class for testing tree style plugins.
*/
abstract class TreeTestBase extends ViewsKernelTestBase {
use EntityReferenceTestTrait;
/**
* Parent entities.
*
* @var \Drupal\entity_test\Entity\EntityTest[]
*/
protected $parents;
/**
* {@inheritdoc}
*/
public static $modules = [
'entity_test',
'field',
'views_tree',
'views_tree_test',
];
/**
* {@inheritdoc}
*/
protected function setUp($import_test_views = TRUE) {
parent::setUp(FALSE);
ViewTestData::createTestViews(get_class($this), ['views_tree_test']);
$this->installEntitySchema('entity_test');
// Create reference from entity_test to entity_test.
$this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_parent', 'field_test_parent', 'entity_test', 'default', [], FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
$this->createHierarchy();
}
/**
* Creates a hierarchy of entity_test entities.
*/
protected function createHierarchy() {
// Create 3 parent nodes.
foreach (range(1, 3) as $i) {
$entity = EntityTest::create(['name' => 'parent ' . $i]);
$entity->save();
$this->parents[$entity->id()] = $entity;
// Add 3 child entities for each parent.
foreach (range(1, 3) as $j) {
$child = EntityTest::create([
'name' => 'child ' . $j . ' (parent ' . $i . ')',
'field_test_parent' => ['target_id' => $entity->id()],
]);
$child->save();
// For parent 2, child 1, add 3 grandchildren.
if ($i === 2 && $j === 1) {
foreach (range(1, 3) as $k) {
$grand_child = EntityTest::create([
'name' => 'grand child ' . $k . ' (c ' . $j . ', p ' . $i . ')',
'field_test_parent' => ['target_id' => $child->id()],
]);
$grand_child->save();
}
}
}
}
}
}
<?php
namespace Drupal\Tests\views_tree\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\views\ResultRow;
use Drupal\views_tree\TreeItem;
use Drupal\views_tree\TreeHelper;
use Drupal\views_tree\ViewsResultTreeValues;
/**
* @coversDefaultClass \Drupal\views_tree\TreeHelper
* @group views_tree
*/
class TreeHelperTest extends UnitTestCase {
/**
* Mocked views tree result.
*
* @var \Drupal\views_tree\ViewsResultTreeValues
*/
protected $viewsResultTree;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$views_result_tree = $this->prophesize(ViewsResultTreeValues::class);
$this->viewsResultTree = $views_result_tree->reveal();
}
/**
* @covers ::getTreeFromResult
*/
public function testGetTreeFromResultFromEmptyResult() {
$tree_helper = new TreeHelper($this->viewsResultTree);
$this->assertEquals(new TreeItem(NULL, []), $tree_helper->getTreeFromResult([]));
}
/**
* @covers ::getTreeFromResult
*/
public function testGetTreeFromResultWithNoHierarchy() {
$tree_helper = new TreeHelper($this->viewsResultTree);
$tree_data = [];
$tree_data[] = new ResultRow([
'views_tree_main' => 1,
'views_tree_parent' => 0,
]);
$tree_data[] = new ResultRow([
'views_tree_main' => 2,
'views_tree_parent' => 0,
]);
$tree_data[] = new ResultRow([
'views_tree_main' => 3,
'views_tree_parent' => 0,
]);
$expected_tree = new TreeItem(NULL, $tree_data);
$this->assertEquals($expected_tree, $tree_helper->getTreeFromResult($tree_data));
}
/**
* @covers ::getTreeFromResult
*/
public function testGetTreeFromResultWithOneLevelHierarchy() {
$tree_helper = new TreeHelper($this->viewsResultTree);
$tree_data = [];
$tree_data[] = new ResultRow([
'views_tree_main' => 1,
'views_tree_parent' => 0,
]);
$tree_data[] = new ResultRow([
'views_tree_main' => 2,
'views_tree_parent' => 1,
]);
$tree_data[] = new ResultRow([
'views_tree_main' => 3,
'views_tree_parent' => 1,
]);
$expected_tree = (new TreeItem(NULL))->addLeave(
(new TreeItem($tree_data[0]))
->addLeave($tree_data[1])
->addLeave($tree_data[2])
);
$this->assertEquals($expected_tree, $tree_helper->getTreeFromResult($tree_data));
}
/**
* @covers ::getTreeFromResult
*/
public function testGetTreeFromResultWithMultipleLevelHierarchy() {
$tree_helper = new TreeHelper($this->viewsResultTree);
$tree_data = [];
$tree_data[] = new ResultRow([
'views_tree_main' => 1,
'views_tree_parent' => 0,
]);
$tree_data[] = new ResultRow([
'views_tree_main' => 2,
'views_tree_parent' => 1,
]);
$tree_data[] = new ResultRow([
'views_tree_main' => 3,
'views_tree_parent' => 1,
]);
$tree_data[] = new ResultRow([
'views_tree_main' => 4,
'views_tree_parent' => 1,
]);
$tree_data[] = new ResultRow([
'views_tree_main' => 5,
'views_tree_parent' => 4,
]);
$tree_data[] = new ResultRow([
'views_tree_main' => 6,
'views_tree_parent' => 5,
]);
$expected_tree = (new TreeItem(NULL))->addLeave(
(new TreeItem($tree_data[0]))
->addLeave($tree_data[1])
->addLeave($tree_data[2])
->addLeave((new TreeItem($tree_data[3]))
->addLeave((new TreeItem($tree_data[4]))
->addLeave(new TreeItem($tree_data[5]))
))
);
$this->assertEquals($expected_tree, $tree_helper->getTreeFromResult($tree_data));
}
/**
* @covers ::applyFunctionToTree
*/
public function testApplyFunctionToTree() {
$tree = new TreeItem(1);
$tree->addLeave((new TreeItem(2))
->addLeave(2.5)
->addLeave(3.5)
);
$expected_tree = new TreeItem(2);
$expected_tree->addLeave((new TreeItem(3))
->addLeave(3.5)
->addLeave(4.5)
);
$tree_helper = new TreeHelper($this->viewsResultTree);
$result = $tree_helper->applyFunctionToTree($tree, function ($i) {
return $i + 1;
});
$this->assertEquals($expected_tree, $result);
}
/**
* @covers ::applyFunctionToTree
*/
public function testApplyFunctionToTreeWithNulls() {
$tree = new TreeItem(NULL);
$tree->addLeave((new TreeItem(2))
->addLeave(NULL)
->addLeave(3.5)
);
$expected_tree = new TreeItem(NULL);
$expected_tree->addLeave((new TreeItem(3))
->addLeave(NULL)
->addLeave(4.5)
);
$tree_helper = new TreeHelper($this->viewsResultTree);
$result = $tree_helper->applyFunctionToTree($tree, function ($i) {
return $i + 1;
});
$this->assertEquals($expected_tree, $result);
}
}
<?php
namespace Drupal\Tests\views_tree\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\views_tree\TreeItem;
/**
* @coversDefaultClass \Drupal\views_tree\TreeItem
* @group views_tree
*/
class TreeItemTest extends UnitTestCase {
/**
* @covers ::getIterator
*/
public function testIterator() {
$tree = new TreeItem(NULL);
$tree
->addLeave(1)
->addLeave(2)
->addLeave(3);
$this->assertEquals([new TreeItem(1), new TreeItem(2), new TreeItem(3)], iterator_to_array($tree));
}
}
name: Views TreeItem
description: A Views style plugin to display a tree of elements using the adjacency model.
package: Views
# core: 8.x
type: module
dependencies:
- drupal:views
# Information added by Drupal.org packaging script on 2018-10-02
version: '8.x-2.0-alpha1'
core: '8.x'
project: 'views_tree'
datestamp: 1538512991
views_tree:
version: VERSION
css:
layout:
css/collapsible.css: {}
js:
js/collapsible.js: {}
dependencies:
- core/drupal
- core/drupalSettings
views_tree_table:
version: VERSION
css:
layout:
css/table.css: {}
<?php
/**
* @file
* Views tree module.
*/
/**
* Implements hook_theme().
*/
function views_tree_theme($existing, $type, $theme, $path) {
return [
'views_tree' => [
'variables' => [
'view' => NULL,
'options' => [],
'list_type' => 'ul',
'rows' => [],
'title' => NULL,
'items' => [],
],
],
'views_tree_table' => [
'variables' => [
'view' => NULL,
'options' => [],
'list_type' => 'ul',
'rows' => [],
'title' => NULL,
'items' => [],
],
],
];
}
/**
* Prepares variables for a views tree display.
*
* @param array $variables
* The variables to pass on to the template.
*/
function template_preprocess_views_tree(array &$variables) {
$rows = $variables['rows'];
/** @var \Drupal\views\ViewExecutable $view */
$view = $variables['view'];
$options = $view->getStyle()->options;
$variables['#attached']['library'][] = 'views_tree/views_tree';
// Add JS and CSS for collapsible tree, if configured.
if (!empty($options['collapsible_tree'])) {
$variables['#attached']['drupalSettings'] = [
'views_tree_settings' => [[
$view->id(),
$options['collapsible_tree'],
],
],
];
}
$variables['options'] = $options;
$variables['list_type'] = $options['type'];
/** @var \Drupal\views_tree\TreeHelper $tree_helper */
$tree_helper = \Drupal::service('views_tree.tree');
$variables['items'] = $tree_helper->buildRenderTree($view, $rows);
}
/**
* Prepares variables for a views tree table display.
*/
function template_preprocess_views_tree_table(array &$variables) {
// Set variables from core's table display.
template_preprocess_views_view_table($variables);
$view = $variables['view'];
$rows = $variables['rows'];
$options = $view->getStyle()->options;
// Add a class to the main field cell.
foreach ($rows as $key => $row) {
$row['columns'][$options['display_hierarchy_column']]['attributes']->addClass('views-tree-hierarchy-cell');
$rows[$key] = $row;
}
$tree_service = \Drupal::service('views_tree.tree');
$variables['items'] = $tree_service->buildRenderTree($view, $rows);
// Since an HTML table isn't representative of a hierarchy, add data
// data attributes for this representation.
$tree_service->addDataAttributes($variables['items']);
// Attach layout library.
$variables['#attached']['library'][] = 'views_tree/views_tree_table';
}
services:
views_tree.tree:
class: \Drupal\views_tree\TreeHelper
arguments: ['@views_tree.views_tree_values']
views_tree.views_tree_values:
class: \Drupal\views_tree\ViewsResultTreeValues
{#
/**
* @file
* Theme override to display a single page.
*
* The doctype, html, head and body tags are not in this template. Instead they
* can be found in the html.html.twig template in this directory.
*
* Available variables:
*
* General utility variables:
* - base_path: The base URL path of the Drupal installation. Will usually be
* "/" unless you have installed Drupal in a sub-directory.
* - is_front: A flag indicating if the current page is the front page.
* - logged_in: A flag indicating if the user is registered and signed in.
* - is_admin: A flag indicating if the user has permission to access
* administration pages.
*
* Site identity:
* - front_page: The URL of the front page. Use this instead of base_path when
* linking to the front page. This includes the language domain or prefix.
*
* Page content (in order of occurrence in the default page.html.twig):
* - node: Fully loaded node, if there is an automatically-loaded node
* associated with the page and the node ID is the second argument in the
* page's path (e.g. node/12345 and node/12345/revisions, but not
* comment/reply/12345).
*
* Regions:
* - page.header: Items for the header region.
* - page.primary_menu: Items for the primary menu region.
* - page.secondary_menu: Items for the secondary menu region.
* - page.highlighted: Items for the highlighted content region.
* - page.help: Dynamic help text, mostly for admin pages.
* - page.content: The main content of the current page.
* - page.sidebar_first: Items for the first sidebar.
* - page.sidebar_second: Items for the second sidebar.
* - page.footer: Items for the footer region.
* - page.breadcrumb: Items for the breadcrumb region.
*
* @see template_preprocess_page()
* @see html.html.twig
*/
#}
<div class="container-fluid">
<div class="row">
<div class="container headercontainer">
<header class="h_o_c_b">
{{ page.header }}
{{ page.primary_menu }}
</header>
</div>
</div>
</div>
{% if page.banner %}
<div class="b_o_c_b">
<div class="b_main_slider static_banner">
{{ page.banner }}
</div>
</div>
{% endif %}
<!-- breadcurmb start -->
<div class="container-fluid">
<div class="row">
<div class="container">
<div class="row">
<div class="col-12">
{{ page.breadcrumb }}
</div>
</div>
</div>
</div>
</div>
<!-- breadcurmd end -->
{% if page.content_top %}
<div class="contentTop-section">
{{ page.content_top }}
</div>
{% endif %}
{# <div class="container-fluid spacerTB">
<div class="row"> #}
<div class="container-fluid spacerTB">
<div class="row">
<div class="container">
<div class="a_s_w_c">
<div class="ls_i_c">
{% if page.sidebar_first %}
{{ page.sidebar_first }}
{% endif %}
{{ page.content }}
{% if page.sidebar_second %}
{{ page.sidebar_second }}
{% endif %}
</div>
</div>
</div>
</div>
</div>
{# </div>
</div> #}
<!-- <div class="layout-container">
<div class="layout-content">
{# {{ page.content }} #}
</div>{# /.layout-content #}
</div> -->
{% if page.content_bottom %}
</div class="contentBottom">
{{ page.content_bottom }}
</div>
{% endif %}
{% if page.footer_top %}
<div class="container-fluid spacerTB">
<div class="row">
<div class="container">
<div class="row mb-5">
{{ page.footer_top }}
</div>
</div>
</div>
</div>
{% endif %}
{% if page.footer %}
<div class="container-fluid f_l_c_b">
<div class="row">
<div class="container">
<div class="row">
<div class="col-lg-9">
<div class="row">
<div class="col-lg-3 col-12 f_cb_m">
{{ page.footer }}
</div>
<div class="col-lg-3 col-12 f_cb_m">
{{ page.footer_first }}
</div>
<div class="col-lg-3 col-12 f_cb_m">
{{ page.footer_second }}
</div>
<div class="col-lg-3 col-12 f_cb_m">
{{ page.footer_third }}
</div>
</div>
</div>
<div class="col-lg-3">
<div class="fl_c_b footer_newsletter_container">
{{ page.footer_fourth }}
</div>
</div>
</div>
</div>
</div>
</div>
{% endif %}
{{ page.footer_fifth }}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment