QuickEditFieldForm.php 8.64 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\quickedit\Form\QuickEditFieldForm.
6 7
 */

8
namespace Drupal\quickedit\Form;
9

10
use Drupal\Core\Entity\ContentEntityInterface;
11
use Drupal\Core\Entity\EntityInterface;
12
use Drupal\Core\Entity\EntityStorageInterface;
13
use Drupal\Core\Entity\EntityChangedInterface;
14
use Drupal\Core\Extension\ModuleHandlerInterface;
15
use Drupal\Core\Form\FormBase;
16
use Drupal\Core\Render\Element;
17
use Drupal\entity\Entity\EntityFormDisplay;
18
use Drupal\user\TempStoreFactory;
19
use Symfony\Component\DependencyInjection\ContainerInterface;
20 21 22 23

/**
 * Builds and process a form for editing a single entity field.
 */
24
class QuickEditFieldForm extends FormBase {
25

26 27 28 29 30 31 32
  /**
   * Stores the tempstore factory.
   *
   * @var \Drupal\user\TempStoreFactory
   */
  protected $tempStoreFactory;

33
  /**
34 35 36 37 38 39 40 41 42
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The node type storage.
   *
43
   * @var \Drupal\Core\Entity\EntityStorageInterface
44 45 46 47 48 49 50 51 52 53
   */
  protected $nodeTypeStorage;

  /**
   * Constructs a new EditFieldForm.
   *
   * @param \Drupal\user\TempStoreFactory $temp_store_factory
   *   The tempstore factory.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
54
   * @param \Drupal\Core\Entity\EntityStorageInterface $node_type_storage
55 56
   *   The node type storage.
   */
57
  public function __construct(TempStoreFactory $temp_store_factory, ModuleHandlerInterface $module_handler, EntityStorageInterface $node_type_storage) {
58 59 60 61 62 63 64 65 66 67 68 69
    $this->moduleHandler = $module_handler;
    $this->nodeTypeStorage = $node_type_storage;
    $this->tempStoreFactory = $temp_store_factory;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('user.tempstore'),
      $container->get('module_handler'),
70
      $container->get('entity.manager')->getStorage('node_type')
71 72 73 74 75 76
    );
  }

  /**
   * {@inheritdoc}
   */
77
  public function getFormId() {
78
    return 'quickedit_field_form';
79 80 81 82 83
  }

  /**
   * {@inheritdoc}
   *
84 85
   * Builds a form for a single entity field.
   */
86
  public function buildForm(array $form, array &$form_state, EntityInterface $entity = NULL, $field_name = NULL) {
87 88 89 90 91
    if (!isset($form_state['entity'])) {
      $this->init($form_state, $entity, $field_name);
    }

    // Add the field form.
92
    $form_state['form_display']->buildForm($entity, $form, $form_state);
93

94 95 96 97 98 99 100 101
    // Add a dummy changed timestamp field to attach form errors to.
    if ($entity instanceof EntityChangedInterface) {
      $form['changed_field'] = array(
        '#type' => 'hidden',
        '#value' => $entity->getChangedTime(),
      );
    }

102 103 104 105 106
    // Add a submit button. Give it a class for easy JavaScript targeting.
    $form['actions'] = array('#type' => 'actions');
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save'),
107
      '#attributes' => array('class' => array('quickedit-form-submit')),
108 109 110 111 112 113 114 115 116 117 118 119 120 121
    );

    // Simplify it for optimal in-place use.
    $this->simplify($form, $form_state);

    return $form;
  }

  /**
   * Initialize the form state and the entity before the first form build.
   */
  protected function init(array &$form_state, EntityInterface $entity, $field_name) {
    // @todo Rather than special-casing $node->revision, invoke prepareEdit()
    //   once http://drupal.org/node/1863258 lands.
122
    if ($entity->getEntityTypeId() == 'node') {
123 124
      $node_type_settings = $this->nodeTypeStorage->load($entity->bundle())->getModuleSettings('node');
      $options = (isset($node_type_settings['options'])) ? $node_type_settings['options'] : array();
125
      $entity->setNewRevision(!empty($options['revision']));
126
      $entity->revision_log = NULL;
127 128 129 130
    }

    $form_state['entity'] = $entity;
    $form_state['field_name'] = $field_name;
131

132 133 134 135 136 137 138 139 140
    // Fetch the display used by the form. It is the display for the 'default'
    // form mode, with only the current field visible.
    $display = EntityFormDisplay::collectRenderDisplay($entity, 'default');
    foreach ($display->getComponents() as $name => $optipns) {
      if ($name != $field_name) {
        $display->removeComponent($name);
      }
    }
    $form_state['form_display'] = $display;
141 142 143
  }

  /**
144
   * {@inheritdoc}
145
   */
146
  public function validateForm(array &$form, array &$form_state) {
147
    $entity = $this->buildEntity($form, $form_state);
148 149

    $form_state['form_display']->validateFormValues($entity, $form, $form_state);
150 151 152 153 154 155 156

    // Do validation on the changed field as well and assign the error to the
    // dummy form element we added for this. We don't know the name of this
    // field on the entity, so we need to find it and validate it ourselves.
    if ($changed_field_name = $this->getChangedFieldName($entity)) {
      $changed_field_errors = $entity->$changed_field_name->validate();
      if (count($changed_field_errors)) {
157
        $this->setFormError('changed_field', $form_state, $changed_field_errors[0]->getMessage());
158 159
      }
    }
160 161 162
  }

  /**
163 164
   * {@inheritdoc}
   *
165 166
   * Saves the entity with updated values for the edited field.
   */
167
  public function submitForm(array &$form, array &$form_state) {
168
    $form_state['entity'] = $this->buildEntity($form, $form_state);
169 170

    // Store entity in tempstore with its UUID as tempstore key.
171
    $this->tempStoreFactory->get('quickedit')->set($form_state['entity']->uuid(), $form_state['entity']);
172 173 174 175 176 177 178 179 180
  }

  /**
   * Returns a cloned entity containing updated field values.
   *
   * Calling code may then validate the returned entity, and if valid, transfer
   * it back to the form state and save it.
   */
  protected function buildEntity(array $form, array &$form_state) {
181
    /** @var $entity \Drupal\Core\Entity\EntityInterface */
182
    $entity = clone $form_state['entity'];
183
    $field_name = $form_state['field_name'];
184

185
    $form_state['form_display']->extractFormValues($entity, $form, $form_state);
186 187 188

    // @todo Refine automated log messages and abstract them to all entity
    //   types: http://drupal.org/node/1678002.
189 190
    if ($entity->getEntityTypeId() == 'node' && $entity->isNewRevision() && !isset($entity->revision_log)) {
      $entity->revision_log = t('Updated the %field-name field through in-place editing.', array('%field-name' => $entity->get($field_name)->getFieldDefinition()->getLabel()));
191 192 193 194 195 196 197 198 199 200 201 202 203
    }

    return $entity;
  }

  /**
   * Simplifies the field edit form for in-place editing.
   *
   * This function:
   * - Hides the field label inside the form, because JavaScript displays it
   *   outside the form.
   * - Adjusts textarea elements to fit their content.
   *
204 205 206 207
   * @param array &$form
   *   A reference to an associative array containing the structure of the form.
   * @param array &$form_state
   *   A reference to a keyed array containing the current state of the form.
208 209 210
   */
  protected function simplify(array &$form, array &$form_state) {
    $field_name = $form_state['field_name'];
211
    $widget_element =& $form[$field_name]['widget'];
212 213 214 215 216 217 218 219

    // Hide the field label from displaying within the form, because JavaScript
    // displays the equivalent label that was provided within an HTML data
    // attribute of the field's display element outside of the form. Do this for
    // widgets without child elements (like Option widgets) as well as for ones
    // with per-delta elements. Skip single checkboxes, because their title is
    // key to their UI. Also skip widgets with multiple subelements, because in
    // that case, per-element labeling is informative.
220
    $num_children = count(Element::children($widget_element));
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
    if ($num_children == 0 && $widget_element['#type'] != 'checkbox') {
      $widget_element['#title_display'] = 'invisible';
    }
    if ($num_children == 1 && isset($widget_element[0]['value'])) {
      // @todo While most widgets name their primary element 'value', not all
      //   do, so generalize this.
      $widget_element[0]['value']['#title_display'] = 'invisible';
    }

    // Adjust textarea elements to fit their content.
    if (isset($widget_element[0]['value']['#type']) && $widget_element[0]['value']['#type'] == 'textarea') {
      $lines = count(explode("\n", $widget_element[0]['value']['#default_value']));
      $widget_element[0]['value']['#rows'] = $lines + 1;
    }
  }

237 238 239
  /**
   * Finds the field name for the field carrying the changed timestamp, if any.
   *
240
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
241 242 243 244 245
   *   The entity.
   *
   * @return string|null
   *   The name of the field found or NULL if not found.
   */
246 247 248 249
  protected function getChangedFieldName(ContentEntityInterface $entity) {
    foreach ($entity->getFieldDefinitions() as $field) {
      if ($field->getType() == 'changed') {
        return $field->getName();
250 251 252 253
      }
    }
  }

254
}