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

/**
 * @file
 * Contains \Drupal\system\Form\DateFormatFormBase.
 */

namespace Drupal\system\Form;

10 11
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
12
use Drupal\Core\Config\Entity\ConfigEntityStorageInterface;
13
use Drupal\Core\Datetime\DateFormatter;
14
use Drupal\Core\Form\FormStateInterface;
15
use Drupal\Core\Language\LanguageInterface;
16
use Symfony\Component\DependencyInjection\ContainerInterface;
17
use Drupal\Core\Datetime\DrupalDateTime;
18
use Drupal\Core\Entity\EntityForm;
19 20

/**
21
 * Provides a base form for date formats.
22
 */
23
abstract class DateFormatFormBase extends EntityForm {
24

25
  /**
26
   * The date formatter service.
27
   *
28
   * @var \Drupal\Core\Datetime\DateFormatter
29
   */
30
  protected $dateFormatter;
31

32
  /**
33
   * The date format storage.
34
   *
35
   * @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface
36 37 38
   */
  protected $dateFormatStorage;

39 40
  /**
   * Constructs a new date format form.
41
   *
42
   * @param \Drupal\Core\Datetime\DateFormatter $date_formatter
43
   *   The date service.
44 45
   * @param \Drupal\Core\Config\Entity\ConfigEntityStorageInterface $date_format_storage
   *   The date format storage.
46
   */
47
  public function __construct(DateFormatter $date_formatter, ConfigEntityStorageInterface $date_format_storage) {
48
    $date = new DrupalDateTime();
49

50
    $this->dateFormatter = $date_formatter;
51
    $this->dateFormatStorage = $date_format_storage;
52 53 54 55 56
  }

  /**
   * {@inheritdoc}
   */
57
  public static function create(ContainerInterface $container) {
58
    return new static(
59
      $container->get('date.formatter'),
60
      $container->get('entity.manager')->getStorage('date_format')
61 62
    );
  }
63

64 65 66 67 68 69 70 71 72 73 74
  /**
   * Checks for an existing date format.
   *
   * @param string|int $entity_id
   *   The entity ID.
   * @param array $element
   *   The form element.
   *
   * @return bool
   *   TRUE if this format already exists, FALSE otherwise.
   */
75
  public function exists($entity_id, array $element) {
76 77
    return (bool) $this->dateFormatStorage
      ->getQuery()
78 79 80 81
      ->condition('id', $element['#field_prefix'] . $entity_id)
      ->execute();
  }

82 83 84
  /**
   * {@inheritdoc}
   */
85
  public function form(array $form, FormStateInterface $form_state) {
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    $form['label'] = array(
      '#type' => 'textfield',
      '#title' => 'Name',
      '#maxlength' => 100,
      '#description' => t('Name of the date format'),
      '#default_value' => $this->entity->label(),
    );

    $form['id'] = array(
      '#type' => 'machine_name',
      '#description' => t('A unique machine-readable name. Can only contain lowercase letters, numbers, and underscores.'),
      '#disabled' => !$this->entity->isNew(),
      '#default_value' => $this->entity->id(),
      '#machine_name' => array(
        'exists' => array($this, 'exists'),
101
        'replace_pattern' =>'([^a-z0-9_]+)|(^custom$)',
102
        'error' => $this->t('The machine-readable name must be unique, and can only contain lowercase letters, numbers, and underscores. Additionally, it can not be the reserved word "custom".'),
103 104 105 106 107 108
      ),
    );
    $form['date_format_pattern'] = array(
      '#type' => 'textfield',
      '#title' => t('Format string'),
      '#maxlength' => 100,
109
      '#description' => $this->t('A user-defined date format. See the <a href="@url">PHP manual</a> for available options.', array('@url' => 'http://php.net/manual/function.date.php')),
110
      '#required' => TRUE,
111 112 113 114
      '#attributes' => [
        'data-drupal-date-formatter' => 'source',
      ],
      '#field_suffix' => ' <small class="js-hide" data-drupal-date-formatter="preview">' . $this->t('Displayed as %date_format', ['%date_format' => '']) . '</small>',
115 116
    );

117 118 119
    $form['langcode'] = array(
      '#type' => 'language_select',
      '#title' => t('Language'),
120
      '#languages' => LanguageInterface::STATE_ALL,
121
      '#default_value' => $this->entity->language()->getId(),
122
    );
123 124
    $form['#attached']['drupalSettings']['dateFormats'] = $this->dateFormatter->getSampleDateFormats();
    $form['#attached']['library'][] = 'system/drupal.system.date';
125 126 127 128 129 130
    return parent::form($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
131
  public function validate(array $form, FormStateInterface $form_state) {
132 133 134 135 136
    parent::validate($form, $form_state);

    // The machine name field should already check to see if the requested
    // machine name is available. Regardless of machine_name or human readable
    // name, check to see if the provided pattern exists.
137
    $pattern = trim($form_state->getValue('date_format_pattern'));
138
    foreach ($this->dateFormatStorage->loadMultiple() as $format) {
139
      if ($format->getPattern() == $pattern && ($this->entity->isNew() || $format->id() != $this->entity->id())) {
140
        $form_state->setErrorByName('date_format_pattern', $this->t('This format already exists. Enter a unique format string.'));
141 142
        continue;
      }
143 144 145 146 147 148
    }
  }

  /**
   * {@inheritdoc}
   */
149
  public function submitForm(array &$form, FormStateInterface $form_state) {
150
    $form_state->setValue('pattern', trim($form_state->getValue('date_format_pattern')));
151 152
    parent::submitForm($form, $form_state);
  }
153

154 155 156 157 158 159 160 161 162 163 164
  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $status = $this->entity->save();
    if ($status == SAVED_UPDATED) {
      drupal_set_message(t('Custom date format updated.'));
    }
    else {
      drupal_set_message(t('Custom date format added.'));
    }
165
    $form_state->setRedirectUrl($this->entity->urlInfo('collection'));
166 167 168
  }

}