Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
namespace Drupal\hierarchy_manager\Plugin\HmDisplayPlugin;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\hierarchy_manager\Plugin\HmDisplayPluginInterface;
use Drupal\hierarchy_manager\Plugin\HmDisplayPluginBase;
/**
* JsTree display plugin.
*
* @HmDisplayPlugin(
* id = "hm_display_jstree",
* label = @Translation("JsTree")
* )
*/
class HmDisplayJstree extends HmDisplayPluginBase implements HmDisplayPluginInterface {
use StringTranslationTrait;
/*
* Build the tree form.
*/
public function getForm(string $url_source, string $url_update, array &$form = [], FormStateInterface &$form_state = NULL, array $options = []) {
if (!empty($url_source)) {
if (!empty(($form_state))) {
$parent_formObj = $form_state->getFormObject();
$parent_id = $parent_formObj->getFormId();
}
// The jsTree theme.
$theme = isset($options['theme']) ? $options['theme'] : 'default';
// Search input.
$form['search'] = [
'#type' => 'textfield',
'#title' => $this
->t('Search'),
'#description' => $this->t('Type in the search keyword here to filter the tree below. Empty the keyword to reset the tree.'),
'#attributes' => [
'name' => 'jstree-search',
'id' => isset($parent_id) ? 'hm-jstree-search-' . $parent_id : 'hm-jstree-search',
'parent-id' => isset($parent_id) ? $parent_id : '',
'class' => [
'hm-jstree-search',
],
],
'#size' => 60,
'#maxlength' => 128,
];
$form['jstree'] = [
'#type' => 'html_tag',
'#suffix' => '<div class="description">' . $this->t('Click a tree node to edit it.') . '<br>' . $this->t('The tree node is draggable and droppable') . '</div>',
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
'#tag' => 'div',
'#value' => '',
'#attributes' => [
'class' => [
'hm-jstree',
],
'id' => isset($parent_id) ? 'hm-jstree-' . $parent_id : 'hm-jstree',
'parent-id' => isset($parent_id) ? $parent_id : '',
'theme' => $theme,
'data-source' => $url_source,
'url-update' => $url_update,
],
];
$form['#attached']['library'][] = 'hierarchy_manager/libraries.jquery.jstree.' . $theme;
$form['#attached']['library'][] = 'hierarchy_manager/feature.hm.jstree';
}
return $form;
}
/**
* Build the data array that JS library accepts.
*/
public function treeData(array $data) {
$jstree_data = [];
// The array key of jsTree is different from the data source.
// So we need to translate them.
foreach ($data as $tree_node) {
$jstree_node = $tree_node;
// The root id for jsTree is #.
if ($tree_node['parent'] === '0') {
$jstree_node['parent'] = '#';
}
// Custom data
$jstree_node['a_attr'] = ['href' => $jstree_node['edit_url']];
unset($jstree_node['edit_url']);
// Add this node into the data array.
$jstree_data[] = $jstree_node;
}
return $jstree_data;
}
}