BookAdminEditForm.php 7.34 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\book\Form\BookAdminEditForm.
 */

namespace Drupal\book\Form;

10
use Drupal\book\BookManagerInterface;
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
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Entity\EntityStorageControllerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\menu_link\MenuLinkStorageControllerInterface;
use Drupal\node\NodeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a form for administering a single book's hierarchy.
 */
class BookAdminEditForm extends FormBase {

  /**
   * The menu cache object for this controller.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cache;

  /**
   * The node storage controller.
   *
   * @var \Drupal\Core\Entity\EntityStorageControllerInterface
   */
  protected $nodeStorage;

  /**
39
   * The book manager.
40
   *
41
   * @var \Drupal\book\BookManagerInterface
42
   */
43
  protected $bookManager;
44 45 46 47 48 49 50 51

  /**
   * Constructs a new BookAdminEditForm.
   *
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache
   *   The menu cache object to be used by this controller.
   * @param \Drupal\Core\Entity\EntityStorageControllerInterface $node_storage
   *   The custom block storage controller.
52 53
   * @param \Drupal\book\BookManagerInterface $book_manager
   *   The book manager.
54
   */
55
  public function __construct(CacheBackendInterface $cache, EntityStorageControllerInterface $node_storage, BookManagerInterface $book_manager) {
56 57
    $this->cache = $cache;
    $this->nodeStorage = $node_storage;
58
    $this->bookManager = $book_manager;
59 60 61 62 63 64 65 66 67 68
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $entity_manager = $container->get('entity.manager');
    return new static(
      $container->get('cache.menu'),
      $entity_manager->getStorageController('node'),
69
      $container->get('book.manager')
70 71 72 73 74 75
    );
  }

  /**
   * {@inheritdoc}
   */
76
  public function getFormId() {
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
    return 'book_admin_edit';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, array &$form_state, NodeInterface $node = NULL) {
    $form['#title'] = $node->label();
    $form['#node'] = $node;
    $this->bookAdminTable($node, $form);
    $form['save'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save book pages'),
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, array &$form_state) {
    if ($form_state['values']['tree_hash'] != $form_state['values']['tree_current_hash']) {
100
      $this->setFormError('', $form_state, $this->t('This book has been modified by another user, the changes could not be saved.'));
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, array &$form_state) {
    // Save elements in the same order as defined in post rather than the form.
    // This ensures parents are updated before their children, preventing orphans.
    $order = array_flip(array_keys($form_state['input']['table']));
    $form['table'] = array_merge($order, $form['table']);

    // Track updates.
    $updated = FALSE;
    foreach (element_children($form['table']) as $key) {
      if ($form['table'][$key]['#item']) {
        $row = $form['table'][$key];
        $values = $form_state['values']['table'][$key];

        // Update menu item if moved.
121 122 123 124 125
        if ($row['pid']['#default_value'] != $values['pid'] || $row['weight']['#default_value'] != $values['weight']) {
          $link = $this->bookManager->loadBookLink($values['nid'], FALSE);
          $link['weight'] = $values['weight'];
          $link['pid'] = $values['pid'];
          $this->bookManager->saveBookLink($link, FALSE);
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
          $updated = TRUE;
        }

        // Update the title if changed.
        if ($row['title']['#default_value'] != $values['title']) {
          $node = $this->nodeStorage->load($values['nid']);
          $node->log = $this->t('Title changed from %original to %current.', array('%original' => $node->label(), '%current' => $values['title']));
          $node->title = $values['title'];
          $node->book['link_title'] = $values['title'];
          $node->setNewRevision();
          $node->save();
          watchdog('content', 'book: updated %title.', array('%title' => $node->label()), WATCHDOG_NOTICE, l($this->t('view'), 'node/' . $node->id()));
        }
      }
    }
    if ($updated) {
      // Flush static and cache.
      drupal_static_reset('book_menu_subtree_data');
144
      $cid = 'book-links:subtree-cid:' . $form['#node']->book['nid'];
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
      $this->cache->delete($cid);
    }

    drupal_set_message($this->t('Updated book %title.', array('%title' => $form['#node']->label())));
  }

  /**
   * Builds the table portion of the form for the book administration page.
   *
   * @param \Drupal\node\NodeInterface $node
   *   The node of the top-level page in the book.
   * @param array $form
   *   The form that is being modified, passed by reference.
   *
   * @see self::buildForm()
   */
  protected function bookAdminTable(NodeInterface $node, array &$form) {
    $form['table'] = array(
      '#theme' => 'book_admin_table',
      '#tree' => TRUE,
    );

167
    $tree = \Drupal::service('book.manager')->bookMenuSubtreeData($node->book);
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
    // Do not include the book item itself.
    $tree = array_shift($tree);
    if ($tree['below']) {
      $hash = Crypt::hashBase64(serialize($tree['below']));
      // Store the hash value as a hidden form element so that we can detect
      // if another user changed the book hierarchy.
      $form['tree_hash'] = array(
        '#type' => 'hidden',
        '#default_value' => $hash,
      );
      $form['tree_current_hash'] = array(
        '#type' => 'value',
        '#value' => $hash,
      );
      $this->bookAdminTableTree($tree['below'], $form['table']);
    }
  }

  /**
   * Helps build the main table in the book administration page form.
   *
   * @param array $tree
   *   A subtree of the book menu hierarchy.
   * @param array $form
   *   The form that is being modified, passed by reference.
   *
   * @see self::buildForm()
   */
  protected function bookAdminTableTree(array $tree, array &$form) {
    // The delta must be big enough to give each node a distinct value.
    $count = count($tree);
    $delta = ($count < 30) ? 15 : intval($count / 2) + 1;

    foreach ($tree as $data) {
      $form['book-admin-' . $data['link']['nid']] = array(
        '#item' => $data['link'],
        'nid' => array('#type' => 'value', '#value' => $data['link']['nid']),
        'depth' => array('#type' => 'value', '#value' => $data['link']['depth']),
        'title' => array(
          '#type' => 'textfield',
208
          '#default_value' => $data['link']['title'],
209 210 211 212 213 214 215 216 217 218
          '#maxlength' => 255,
          '#size' => 40,
        ),
        'weight' => array(
          '#type' => 'weight',
          '#default_value' => $data['link']['weight'],
          '#delta' => max($delta, abs($data['link']['weight'])),
          '#title' => $this->t('Weight for @title', array('@title' => $data['link']['title'])),
          '#title_display' => 'invisible',
        ),
219
        'pid' => array(
220
          '#type' => 'hidden',
221
          '#default_value' => $data['link']['pid'],
222
        ),
223
        'nid' => array(
224
          '#type' => 'hidden',
225
          '#default_value' => $data['link']['nid'],
226 227 228 229 230 231 232 233 234
        ),
      );
      if ($data['below']) {
        $this->bookAdminTableTree($data['below'], $form);
      }
    }
  }

}