CustomBlockForm.php 8.23 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\custom_block\CustomBlockForm.
6 7 8 9
 */

namespace Drupal\custom_block;

10
use Drupal\Core\Cache\Cache;
11
use Drupal\Core\Entity\ContentEntityForm;
12
use Drupal\Core\Entity\EntityManagerInterface;
13
use Drupal\Core\Entity\EntityStorageInterface;
14
use Drupal\Core\Language\Language;
15 16
use Drupal\Core\Language\LanguageManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
17 18 19 20

/**
 * Form controller for the custom block edit forms.
 */
21
class CustomBlockForm extends ContentEntityForm {
22

23 24 25
  /**
   * The custom block storage.
   *
26
   * @var \Drupal\Core\Entity\EntityStorageInterface
27 28 29 30 31 32 33 34 35 36 37
   */
  protected $customBlockStorage;

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManager
   */
  protected $languageManager;

  /**
38
   * Constructs a CustomBlockForm object.
39 40 41
   *
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
42 43
   * @param \Drupal\Core\Entity\EntityStorageInterface $custom_block_storage
   *   The custom block storage.
44 45 46
   * @param \Drupal\Core\Language\LanguageManager $language_manager
   *   The language manager.
   */
47
  public function __construct(EntityManagerInterface $entity_manager, EntityStorageInterface $custom_block_storage, LanguageManager $language_manager) {
48 49 50 51 52 53 54 55 56 57 58 59
    parent::__construct($entity_manager);
    $this->customBlockStorage = $custom_block_storage;
    $this->languageManager = $language_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $entity_manager = $container->get('entity.manager');
    return new static(
      $entity_manager,
60
      $entity_manager->getStorage('custom_block'),
61 62 63 64
      $container->get('language_manager')
    );
  }

65
  /**
66
   * Overrides \Drupal\Core\Entity\EntityForm::prepareEntity().
67 68 69 70 71 72
   *
   * Prepares the custom block object.
   *
   * Fills in a few default values, and then invokes hook_custom_block_prepare()
   * on all modules.
   */
73 74
  protected function prepareEntity() {
    $block = $this->entity;
75
    // Set up default values, if required.
76 77 78
    $block_type = entity_load('custom_block_type', $block->bundle());
    if (!$block->isNew()) {
      $block->setRevisionLog(NULL);
79 80 81 82 83 84
    }
    // Always use the default revision setting.
    $block->setNewRevision($block_type->revision);
  }

  /**
85
   * {@inheritdoc}
86
   */
87 88
  public function form(array $form, array &$form_state) {
    $block = $this->entity;
89
    $account = $this->currentUser();
90 91

    if ($this->operation == 'edit') {
92
      $form['#title'] = $this->t('Edit custom block %label', array('%label' => $block->label()));
93
    }
94 95 96
    // Override the default CSS class name, since the user-defined custom block
    // type name in 'TYPE-block-form' potentially clashes with third-party class
    // names.
97
    $form['#attributes']['class'][0] = drupal_html_class('block-' . $block->bundle() . '-form');
98

99 100
    if ($this->moduleHandler->moduleExists('language')) {
      $language_configuration = language_get_default_configuration('custom_block', $block->bundle());
101

102 103
      // Set the correct default language.
      if ($block->isNew()) {
104
        $language_default = $this->languageManager->getCurrentLanguage($language_configuration['langcode']);
105 106
        $block->langcode->value = $language_default->id;
      }
107 108 109
    }

    $form['langcode'] = array(
110
      '#title' => $this->t('Language'),
111
      '#type' => 'language_select',
112
      '#default_value' => $block->getUntranslated()->language()->id,
113
      '#languages' => Language::STATE_ALL,
114 115 116
      '#access' => isset($language_configuration['language_show']) && $language_configuration['language_show'],
    );

117
    $form['advanced'] = array(
118 119 120 121 122 123 124 125
      '#type' => 'vertical_tabs',
      '#weight' => 99,
    );

    // Add a log field if the "Create new revision" option is checked, or if the
    // current user has the ability to check that option.
    $form['revision_information'] = array(
      '#type' => 'details',
126
      '#title' => $this->t('Revision information'),
127 128
      // Open by default when "Create new revision" is checked.
      '#open' => $block->isNewRevision(),
129
      '#group' => 'advanced',
130 131 132 133
      '#attributes' => array(
        'class' => array('custom-block-form-revision-information'),
      ),
      '#attached' => array(
134
        'library' => array('custom_block/drupal.custom_block'),
135 136
      ),
      '#weight' => 20,
137
      '#access' => $block->isNewRevision() || $account->hasPermission('administer blocks'),
138 139 140 141
    );

    $form['revision_information']['revision'] = array(
      '#type' => 'checkbox',
142
      '#title' => $this->t('Create new revision'),
143
      '#default_value' => $block->isNewRevision(),
144
      '#access' => $account->hasPermission('administer blocks'),
145 146 147 148 149 150 151 152
    );

    // Check the revision log checkbox when the log textarea is filled in.
    // This must not happen if "Create new revision" is enabled by default,
    // since the state would auto-disable the checkbox otherwise.
    if (!$block->isNewRevision()) {
      $form['revision_information']['revision']['#states'] = array(
        'checked' => array(
153
          'textarea[name="revision_log"]' => array('empty' => FALSE),
154 155 156 157
        ),
      );
    }

158
    $form['revision_information']['revision_log'] = array(
159
      '#type' => 'textarea',
160
      '#title' => $this->t('Revision log message'),
161
      '#rows' => 4,
162
      '#default_value' => $block->getRevisionLog(),
163
      '#description' => $this->t('Briefly desribe the changes you have made.'),
164 165 166 167 168 169
    );

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

  /**
170
   * Overrides \Drupal\Core\Entity\EntityForm::submit().
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
   *
   * Updates the custom block object by processing the submitted values.
   *
   * This function can be called by a "Next" button of a wizard to update the
   * form state's entity with the current step's values before proceeding to the
   * next step.
   */
  public function submit(array $form, array &$form_state) {
    // Build the block object from the submitted values.
    $block = parent::submit($form, $form_state);

    // Save as a new revision if requested to do so.
    if (!empty($form_state['values']['revision'])) {
      $block->setNewRevision();
    }

    return $block;
  }

  /**
191
   * {@inheritdoc}
192 193
   */
  public function save(array $form, array &$form_state) {
194
    $block = $this->entity;
195
    $insert = $block->isNew();
196 197
    $block->save();
    $watchdog_args = array('@type' => $block->bundle(), '%info' => $block->label());
198
    $block_type = entity_load('custom_block_type', $block->bundle());
199 200 201 202
    $t_args = array('@type' => $block_type->label(), '%info' => $block->label());

    if ($insert) {
      watchdog('content', '@type: added %info.', $watchdog_args, WATCHDOG_NOTICE);
203
      drupal_set_message($this->t('@type %info has been created.', $t_args));
204 205 206
    }
    else {
      watchdog('content', '@type: updated %info.', $watchdog_args, WATCHDOG_NOTICE);
207
      drupal_set_message($this->t('@type %info has been updated.', $t_args));
208 209
    }

210 211 212
    if ($block->id()) {
      $form_state['values']['id'] = $block->id();
      $form_state['id'] = $block->id();
213
      if ($insert) {
214 215
        if (!$theme = $block->getTheme()) {
          $theme = $this->config('system.theme')->get('default');
216
        }
217 218 219 220 221 222 223
        $form_state['redirect_route'] = array(
          'route_name' => 'block.admin_add',
          'route_parameters' => array(
            'plugin_id' => 'custom_block:' . $block->uuid(),
            'theme' => $theme,
          ),
        );
224 225
      }
      else {
226
        $form_state['redirect_route']['route_name'] = 'custom_block.list';
227 228 229 230 231
      }
    }
    else {
      // In the unlikely case something went wrong on save, the block will be
      // rebuilt and block form redisplayed.
232
      drupal_set_message($this->t('The block could not be saved.'), 'error');
233 234 235 236
      $form_state['rebuild'] = TRUE;
    }

    // Clear the page and block caches.
237
    Cache::invalidateTags(array('content' => TRUE));
238 239
  }

240 241 242 243 244
  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, array &$form_state) {
    if ($this->entity->isNew()) {
245
      $exists = $this->customBlockStorage->loadByProperties(array('info' => $form_state['values']['info']));
246
      if (!empty($exists)) {
247
        $this->setFormError('info', $form_state, $this->t('A block with description %name already exists.', array(
248
          '%name' => $form_state['values']['info'][0]['value'],
249
        )));
250 251 252 253
      }
    }
  }

254
}