Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / modules / book / src / Form / BookAdminEditForm.php
1 <?php
2
3 namespace Drupal\book\Form;
4
5 use Drupal\book\BookManager;
6 use Drupal\book\BookManagerInterface;
7 use Drupal\Component\Utility\Crypt;
8 use Drupal\Core\Entity\EntityStorageInterface;
9 use Drupal\Core\Form\FormBase;
10 use Drupal\Core\Form\FormStateInterface;
11 use Drupal\Core\Render\Element;
12 use Drupal\Core\Url;
13 use Drupal\node\NodeInterface;
14 use Symfony\Component\DependencyInjection\ContainerInterface;
15
16 /**
17  * Provides a form for administering a single book's hierarchy.
18  *
19  * @internal
20  */
21 class BookAdminEditForm extends FormBase {
22
23   /**
24    * The node storage.
25    *
26    * @var \Drupal\Core\Entity\EntityStorageInterface
27    */
28   protected $nodeStorage;
29
30   /**
31    * The book manager.
32    *
33    * @var \Drupal\book\BookManagerInterface
34    */
35   protected $bookManager;
36
37   /**
38    * Constructs a new BookAdminEditForm.
39    *
40    * @param \Drupal\Core\Entity\EntityStorageInterface $node_storage
41    *   The custom block storage.
42    * @param \Drupal\book\BookManagerInterface $book_manager
43    *   The book manager.
44    */
45   public function __construct(EntityStorageInterface $node_storage, BookManagerInterface $book_manager) {
46     $this->nodeStorage = $node_storage;
47     $this->bookManager = $book_manager;
48   }
49
50   /**
51    * {@inheritdoc}
52    */
53   public static function create(ContainerInterface $container) {
54     $entity_manager = $container->get('entity.manager');
55     return new static(
56       $entity_manager->getStorage('node'),
57       $container->get('book.manager')
58     );
59   }
60
61   /**
62    * {@inheritdoc}
63    */
64   public function getFormId() {
65     return 'book_admin_edit';
66   }
67
68   /**
69    * {@inheritdoc}
70    */
71   public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
72     $form['#title'] = $node->label();
73     $form['#node'] = $node;
74     $this->bookAdminTable($node, $form);
75     $form['save'] = [
76       '#type' => 'submit',
77       '#value' => $this->t('Save book pages'),
78     ];
79
80     return $form;
81   }
82
83   /**
84    * {@inheritdoc}
85    */
86   public function validateForm(array &$form, FormStateInterface $form_state) {
87     if ($form_state->getValue('tree_hash') != $form_state->getValue('tree_current_hash')) {
88       $form_state->setErrorByName('', $this->t('This book has been modified by another user, the changes could not be saved.'));
89     }
90   }
91
92   /**
93    * {@inheritdoc}
94    */
95   public function submitForm(array &$form, FormStateInterface $form_state) {
96     // Save elements in the same order as defined in post rather than the form.
97     // This ensures parents are updated before their children, preventing orphans.
98     $user_input = $form_state->getUserInput();
99     if (isset($user_input['table'])) {
100       $order = array_flip(array_keys($user_input['table']));
101       $form['table'] = array_merge($order, $form['table']);
102
103       foreach (Element::children($form['table']) as $key) {
104         if ($form['table'][$key]['#item']) {
105           $row = $form['table'][$key];
106           $values = $form_state->getValue(['table', $key]);
107
108           // Update menu item if moved.
109           if ($row['parent']['pid']['#default_value'] != $values['pid'] || $row['weight']['#default_value'] != $values['weight']) {
110             $link = $this->bookManager->loadBookLink($values['nid'], FALSE);
111             $link['weight'] = $values['weight'];
112             $link['pid'] = $values['pid'];
113             $this->bookManager->saveBookLink($link, FALSE);
114           }
115
116           // Update the title if changed.
117           if ($row['title']['#default_value'] != $values['title']) {
118             $node = $this->nodeStorage->load($values['nid']);
119             $node->revision_log = $this->t('Title changed from %original to %current.', ['%original' => $node->label(), '%current' => $values['title']]);
120             $node->title = $values['title'];
121             $node->book['link_title'] = $values['title'];
122             $node->setNewRevision();
123             $node->save();
124             $this->logger('content')->notice('book: updated %title.', ['%title' => $node->label(), 'link' => $node->link($this->t('View'))]);
125           }
126         }
127       }
128     }
129
130     $this->messenger()->addStatus($this->t('Updated book %title.', ['%title' => $form['#node']->label()]));
131   }
132
133   /**
134    * Builds the table portion of the form for the book administration page.
135    *
136    * @param \Drupal\node\NodeInterface $node
137    *   The node of the top-level page in the book.
138    * @param array $form
139    *   The form that is being modified, passed by reference.
140    *
141    * @see self::buildForm()
142    */
143   protected function bookAdminTable(NodeInterface $node, array &$form) {
144     $form['table'] = [
145       '#type' => 'table',
146       '#header' => [
147         $this->t('Title'),
148         $this->t('Weight'),
149         $this->t('Parent'),
150         $this->t('Operations'),
151       ],
152       '#empty' => $this->t('No book content available.'),
153       '#tabledrag' => [
154         [
155           'action' => 'match',
156           'relationship' => 'parent',
157           'group' => 'book-pid',
158           'subgroup' => 'book-pid',
159           'source' => 'book-nid',
160           'hidden' => TRUE,
161           'limit' => BookManager::BOOK_MAX_DEPTH - 2,
162         ],
163         [
164           'action' => 'order',
165           'relationship' => 'sibling',
166           'group' => 'book-weight',
167         ],
168       ],
169     ];
170
171     $tree = $this->bookManager->bookSubtreeData($node->book);
172     // Do not include the book item itself.
173     $tree = array_shift($tree);
174     if ($tree['below']) {
175       $hash = Crypt::hashBase64(serialize($tree['below']));
176       // Store the hash value as a hidden form element so that we can detect
177       // if another user changed the book hierarchy.
178       $form['tree_hash'] = [
179         '#type' => 'hidden',
180         '#default_value' => $hash,
181       ];
182       $form['tree_current_hash'] = [
183         '#type' => 'value',
184         '#value' => $hash,
185       ];
186       $this->bookAdminTableTree($tree['below'], $form['table']);
187     }
188   }
189
190   /**
191    * Helps build the main table in the book administration page form.
192    *
193    * @param array $tree
194    *   A subtree of the book menu hierarchy.
195    * @param array $form
196    *   The form that is being modified, passed by reference.
197    *
198    * @see self::buildForm()
199    */
200   protected function bookAdminTableTree(array $tree, array &$form) {
201     // The delta must be big enough to give each node a distinct value.
202     $count = count($tree);
203     $delta = ($count < 30) ? 15 : intval($count / 2) + 1;
204
205     $access = \Drupal::currentUser()->hasPermission('administer nodes');
206     $destination = $this->getDestinationArray();
207
208     foreach ($tree as $data) {
209       $nid = $data['link']['nid'];
210       $id = 'book-admin-' . $nid;
211
212       $form[$id]['#item'] = $data['link'];
213       $form[$id]['#nid'] = $nid;
214       $form[$id]['#attributes']['class'][] = 'draggable';
215       $form[$id]['#weight'] = $data['link']['weight'];
216
217       if (isset($data['link']['depth']) && $data['link']['depth'] > 2) {
218         $indentation = [
219           '#theme' => 'indentation',
220           '#size' => $data['link']['depth'] - 2,
221         ];
222       }
223
224       $form[$id]['title'] = [
225         '#prefix' => !empty($indentation) ? \Drupal::service('renderer')->render($indentation) : '',
226         '#type' => 'textfield',
227         '#default_value' => $data['link']['title'],
228         '#maxlength' => 255,
229         '#size' => 40,
230       ];
231
232       $form[$id]['weight'] = [
233         '#type' => 'weight',
234         '#default_value' => $data['link']['weight'],
235         '#delta' => max($delta, abs($data['link']['weight'])),
236         '#title' => $this->t('Weight for @title', ['@title' => $data['link']['title']]),
237         '#title_display' => 'invisible',
238         '#attributes' => [
239           'class' => ['book-weight'],
240         ],
241       ];
242
243       $form[$id]['parent']['nid'] = [
244         '#parents' => ['table', $id, 'nid'],
245         '#type' => 'hidden',
246         '#value' => $nid,
247         '#attributes' => [
248           'class' => ['book-nid'],
249         ],
250       ];
251
252       $form[$id]['parent']['pid'] = [
253         '#parents' => ['table', $id, 'pid'],
254         '#type' => 'hidden',
255         '#default_value' => $data['link']['pid'],
256         '#attributes' => [
257           'class' => ['book-pid'],
258         ],
259       ];
260
261       $form[$id]['parent']['bid'] = [
262         '#parents' => ['table', $id, 'bid'],
263         '#type' => 'hidden',
264         '#default_value' => $data['link']['bid'],
265         '#attributes' => [
266           'class' => ['book-bid'],
267         ],
268       ];
269
270       $form[$id]['operations'] = [
271         '#type' => 'operations',
272       ];
273       $form[$id]['operations']['#links']['view'] = [
274         'title' => $this->t('View'),
275         'url' => new Url('entity.node.canonical', ['node' => $nid]),
276       ];
277
278       if ($access) {
279         $form[$id]['operations']['#links']['edit'] = [
280           'title' => $this->t('Edit'),
281           'url' => new Url('entity.node.edit_form', ['node' => $nid]),
282           'query' => $destination,
283         ];
284         $form[$id]['operations']['#links']['delete'] = [
285           'title' => $this->t('Delete'),
286           'url' => new Url('entity.node.delete_form', ['node' => $nid]),
287           'query' => $destination,
288         ];
289       }
290
291       if ($data['below']) {
292         $this->bookAdminTableTree($data['below'], $form);
293       }
294     }
295   }
296
297 }