BookSettingsForm.php 2.48 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

/**
 * Configure book settings for this site.
10 11
 *
 * @internal
12
 */
13
class BookSettingsForm extends ConfigFormBase {
14 15

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

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

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

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

  /**
55
   * {@inheritdoc}
56
   */
57
  public function validateForm(array &$form, FormStateInterface $form_state) {
58
    $child_type = $form_state->getValue('book_child_type');
59 60
    if ($form_state->isValueEmpty(['book_allowed_types', $child_type])) {
      $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.', ['%add-child' => $this->t('Add child page')]));
61 62 63 64 65 66
    }

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

  /**
67
   * {@inheritdoc}
68
   */
69
  public function submitForm(array &$form, FormStateInterface $form_state) {
70
    $allowed_types = array_filter($form_state->getValue('book_allowed_types'));
71 72 73 74
    // 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);
75
    $this->config('book.settings')
76 77
    // Remove unchecked types.
      ->set('allowed_types', $allowed_types)
78
      ->set('child_type', $form_state->getValue('book_child_type'))
79 80 81 82 83 84
      ->save();

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

}