BookSettingsForm.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace Drupal\book\Form;
  3. use Drupal\Core\Form\ConfigFormBase;
  4. use Drupal\Core\Form\FormStateInterface;
  5. /**
  6. * Configure book settings for this site.
  7. *
  8. * @internal
  9. */
  10. class BookSettingsForm extends ConfigFormBase {
  11. /**
  12. * {@inheritdoc}
  13. */
  14. public function getFormId() {
  15. return 'book_admin_settings';
  16. }
  17. /**
  18. * {@inheritdoc}
  19. */
  20. protected function getEditableConfigNames() {
  21. return ['book.settings'];
  22. }
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function buildForm(array $form, FormStateInterface $form_state) {
  27. $types = node_type_get_names();
  28. $config = $this->config('book.settings');
  29. $form['book_allowed_types'] = [
  30. '#type' => 'checkboxes',
  31. '#title' => $this->t('Content types allowed in book outlines'),
  32. '#default_value' => $config->get('allowed_types'),
  33. '#options' => $types,
  34. '#description' => $this->t('Users with the %outline-perm permission can add all content types.', ['%outline-perm' => $this->t('Administer book outlines')]),
  35. '#required' => TRUE,
  36. ];
  37. $form['book_child_type'] = [
  38. '#type' => 'radios',
  39. '#title' => $this->t('Content type for the <em>Add child page</em> link'),
  40. '#default_value' => $config->get('child_type'),
  41. '#options' => $types,
  42. '#required' => TRUE,
  43. ];
  44. return parent::buildForm($form, $form_state);
  45. }
  46. /**
  47. * {@inheritdoc}
  48. */
  49. public function validateForm(array &$form, FormStateInterface $form_state) {
  50. $child_type = array_filter($form_state->getValue('book_child_type'));
  51. if ($form_state->isValueEmpty(['book_allowed_types', $child_type])) {
  52. $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')]));
  53. }
  54. parent::validateForm($form, $form_state);
  55. }
  56. /**
  57. * {@inheritdoc}
  58. */
  59. public function submitForm(array &$form, FormStateInterface $form_state) {
  60. $allowed_types = array_filter($form_state->getValue('book_allowed_types'));
  61. // We need to save the allowed types in an array ordered by machine_name so
  62. // that we can save them in the correct order if node type changes.
  63. // @see book_node_type_update().
  64. sort($allowed_types);
  65. $this->config('book.settings')
  66. // Remove unchecked types.
  67. ->set('allowed_types', $allowed_types)
  68. ->set('child_type', array_filter($form_state->getValue('book_child_type')))
  69. ->save();
  70. parent::submitForm($form, $form_state);
  71. }
  72. }