compose-8.x-1.x-dev/src/EntityPreviewLoader.php

src/EntityPreviewLoader.php
<?php
namespace Drupal\compose;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\KeyValueStore\KeyValueExpirableFactory;
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormBuilder;

/**
 * Checks access for displaying configuration translation page.
 */
class EntityPreviewLoader extends ControllerBase {

  /**
   * The entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Defines the key/value store factory.
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueExpirableFactory
   */
  protected $keyValueExpirableFactory;

  /**
   * Provides form building and processing.
   *
   * @var \Drupal\Core\Form\FormBuilder
   */
  protected $formBuilder;

  /**
   * {@inheritdoc}
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, KeyValueExpirableFactory $key_value_expirable_factory, FormBuilder $form_builder) {
    $this->entityTypeManager = $entity_type_manager;
    $this->keyValueExpirableFactory = $key_value_expirable_factory;
    $this->formBuilder = $form_builder;
  }

  /**
   * Checks access to the entity preview page.
   *
   * @param string $form_build_id
   *   The build ID of the form.
   * @param string $field_name
   *   The field name of the field using the ComposeWidget.
   * @param string $delta
   *   The delta of this specific reference by the field.
   * @param string $entity_type
   *   The entity type of the host entity of this field.
   * @param string $entity_id
   *   (optional) The ID of the entity. An ID will not exist for entities that
   *   are currently being created.
   *
   * @return $entity
   *   A \Drupal\Core\Entity object.
   */
  public function getPreviewEntity($form_build_id, $field_name, $delta, $entity_type, $entity_id) {
    if ($stored_form_state = $this->keyValueExpirableFactory->get('form_state')->get($form_build_id)) {
      $form_state = new FormState();
      $form_state->setFormState($stored_form_state);
      $form_cache = $this->formBuilder->getCache($form_build_id, $form_state);
      $entity = $form_cache[$field_name]['widget']['entities'][$delta]['#entity'];
      return $entity;
    }
    else {
      $entity = $this->entityTypeManager->getStorage($entity_type)->load($entity_id);
      return $entity;
    }
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc