BookSettingsForm.php 2.56 KB
Newer Older
1 2
<?php

3
namespace Drupal\book\Form;
4

5
use Drupal\Core\Form\ConfigFormBase;
6
use Drupal\Core\Form\FormStateInterface;
7 8 9 10

/**
 * Configure book settings for this site.
 */
11
class BookSettingsForm extends ConfigFormBase {
12 13

  /**
14
   * {@inheritdoc}
15
   */
16
  public function getFormId() {
17 18 19
    return 'book_admin_settings';
  }

20 21 22 23 24 25 26
  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['book.settings'];
  }

27
  /**
28
   * {@inheritdoc}
29
   */
30
  public function buildForm(array $form, FormStateInterface $form_state) {
31
    $types = node_type_get_names();
32
    $config = $this->config('book.settings');
33 34
    $form['book_allowed_types'] = array(
      '#type' => 'checkboxes',
35
      '#title' => $this->t('Content types allowed in book outlines'),
36 37
      '#default_value' => $config->get('allowed_types'),
      '#options' => $types,
38
      '#description' => $this->t('Users with the %outline-perm permission can add all content types.', array('%outline-perm' => $this->t('Administer book outlines'))),
39 40 41 42
      '#required' => TRUE,
    );
    $form['book_child_type'] = array(
      '#type' => 'radios',
43
      '#title' => $this->t('Content type for the <em>Add child page</em> link'),
44 45 46 47 48 49 50 51 52 53
      '#default_value' => $config->get('child_type'),
      '#options' => $types,
      '#required' => TRUE,
    );
    $form['array_filter'] = array('#type' => 'value', '#value' => TRUE);

    return parent::buildForm($form, $form_state);
  }

  /**
54
   * {@inheritdoc}
55
   */
56
  public function validateForm(array &$form, FormStateInterface $form_state) {
57 58
    $child_type = $form_state->getValue('book_child_type');
    if ($form_state->isValueEmpty(array('book_allowed_types', $child_type))) {
59
      $form_state->setErrorByName('book_child_type', $this->t('The content type for the %add-child link must be one of those selected as an allowed book outline type.', array('%add-child' => $this->t('Add child page'))));
60 61 62 63 64 65
    }

    parent::validateForm($form, $form_state);
  }

  /**
66
   * {@inheritdoc}
67
   */
68
  public function submitForm(array &$form, FormStateInterface $form_state) {
69
    $allowed_types = array_filter($form_state->getValue('book_allowed_types'));
70 71 72 73
    // We need to save the allowed types in an array ordered by machine_name so
    // that we can save them in the correct order if node type changes.
    // @see book_node_type_update().
    sort($allowed_types);
74
    $this->config('book.settings')
75 76
    // Remove unchecked types.
      ->set('allowed_types', $allowed_types)
77
      ->set('child_type', $form_state->getValue('book_child_type'))
78 79 80 81 82 83
      ->save();

    parent::submitForm($form, $form_state);
  }

}