You are here

class EntityCreateController in Entity API 8.0

A generic controller for creating entities.

Hierarchy

Expanded class hierarchy of EntityCreateController

File

src/Controller/EntityCreateController.php, line 22
Contains \Drupal\entity\Controller\EntityCreateController.

Namespace

Drupal\entity\Controller
View source
class EntityCreateController extends ControllerBase {

  /**
   * The entity type bundle info.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $entityTypeBundleInfo;

  /**
   * The renderer service.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * Constructs a new EntityCreateController object.
   *
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The entity type bundle info.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
   */
  public function __construct(EntityTypeBundleInfoInterface $entity_type_bundle_info, RendererInterface $renderer) {
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
    $this->renderer = $renderer;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.bundle.info'), $container
      ->get('renderer'));
  }

  /**
   * Displays add links for the available bundles.
   *
   * Redirects to the add form if there's only one bundle available.
   *
   * @param string $entity_type_id
   *   The entity type ID.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse|array
   *   If there's only one available bundle, a redirect response.
   *   Otherwise, a render array with the add links for each bundle.
   */
  public function addPage($entity_type_id) {
    $entity_type = $this
      ->entityTypeManager()
      ->getDefinition($entity_type_id);
    $bundle_type = $entity_type
      ->getBundleEntityType();
    $bundle_key = $entity_type
      ->getKey('bundle');
    $form_route_name = 'entity.' . $entity_type_id . '.add_form';
    $build = [
      '#theme' => 'entity_add_list',
      '#cache' => [
        'tags' => $entity_type
          ->getListCacheTags(),
      ],
      '#bundle_type' => $bundle_type,
    ];
    $bundles = $this->entityTypeBundleInfo
      ->getBundleInfo($entity_type_id);

    // Filter out the bundles the user doesn't have access to.
    $access_control_handler = $this
      ->entityTypeManager()
      ->getAccessControlHandler($bundle_type);
    foreach ($bundles as $bundle_name => $bundle_info) {
      $access = $access_control_handler
        ->createAccess($bundle_name, NULL, [], TRUE);
      if (!$access
        ->isAllowed()) {
        unset($bundles[$bundle_name]);
      }
      $this->renderer
        ->addCacheableDependency($build, $access);
    }

    // Redirect if there's only one bundle available.
    if (count($bundles) == 1) {
      $bundle_names = array_keys($bundles);
      $bundle_name = reset($bundle_names);
      return $this
        ->redirect($form_route_name, [
        $bundle_key => $bundle_name,
      ]);
    }

    // Prepare the #bundles array for the template.
    $bundles = $this
      ->loadBundleDescriptions($bundles, $bundle_type);
    foreach ($bundles as $bundle_name => $bundle_info) {
      $build['#bundles'][$bundle_name] = [
        'label' => $bundle_info['label'],
        'description' => $bundle_info['description'],
        'add_link' => Link::createFromRoute($bundle_info['label'], $form_route_name, [
          $bundle_key => $bundle_name,
        ]),
      ];
    }
    return $build;
  }

  /**
   * The title callback for the add page.
   *
   * @param string $entity_type_id
   *   The entity type ID.
   *
   * @return string
   *   The page title.
   */
  public function addPageTitle($entity_type_id) {
    $entity_type = $this
      ->entityTypeManager()
      ->getDefinition($entity_type_id);
    return $this
      ->t('Add @entity-type', [
      '@entity-type' => $entity_type
        ->getLowercaseLabel(),
    ]);
  }

  /**
   * Provides the add form for an entity.
   *
   * @param string $entity_type_id
   *   The entity type ID.
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match.
   *
   * @return array
   *   The add form.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   *   Thrown when the bundle parameter is invalid.
   */
  public function addForm($entity_type_id, RouteMatchInterface $route_match) {
    $entity_type = $this
      ->entityTypeManager()
      ->getDefinition($entity_type_id);
    $values = [];

    // Entities of this type have bundles, one was provided in the url.
    if ($bundle_key = $entity_type
      ->getKey('bundle')) {
      $bundle_name = $route_match
        ->getRawParameter($bundle_key);
      $bundles = $this->entityTypeBundleInfo
        ->getBundleInfo($entity_type_id);
      if (empty($bundle_name) || !isset($bundles[$bundle_name])) {

        // The bundle parameter is invalid.
        throw new NotFoundHttpException();
      }
      $values[$bundle_key] = $bundle_name;
    }
    $entity = $this
      ->entityTypeManager()
      ->getStorage($entity_type_id)
      ->create($values);
    return $this
      ->entityFormBuilder()
      ->getForm($entity, 'add');
  }

  /**
   * The title callback for the add form.
   *
   * @param string $entity_type_id
   *   The entity type ID.
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match.
   *
   * @return string
   *   The page title.
   */
  public function addFormTitle($entity_type_id, RouteMatchInterface $route_match) {
    $entity_type = $this
      ->entityTypeManager()
      ->getDefinition($entity_type_id);
    $bundle_key = $entity_type
      ->getKey('bundle');
    $bundles = $this->entityTypeBundleInfo
      ->getBundleInfo($entity_type_id);
    if ($bundle_key && count($bundles) > 1) {
      $bundle_name = $route_match
        ->getRawParameter($bundle_key);
      $title = $this
        ->t('Add @bundle', [
        '@bundle' => $bundles[$bundle_name]['label'],
      ]);
    }
    else {
      $title = $this
        ->t('Add @entity-type', [
        '@entity-type' => $entity_type
          ->getLowercaseLabel(),
      ]);
    }
    return $title;
  }

  /**
   * Expands the bundle information with descriptions, if known.
   *
   * @param array $bundles
   *   An array of bundle information.
   * @param string $bundle_type
   *   The id of the bundle entity type.
   *
   * @return array
   *   The expanded array of bundle information.
   */
  protected function loadBundleDescriptions(array $bundles, $bundle_type) {

    // Ensure the presence of the description key.
    foreach ($bundles as $bundle_name => &$bundle_info) {
      $bundle_info['description'] = '';
    }

    // Only bundles provided by entity types have descriptions.
    if (empty($bundle_type)) {
      return $bundles;
    }
    $bundle_entity_type = $this
      ->entityTypeManager()
      ->getDefinition($bundle_type);
    if (!$bundle_entity_type
      ->isSubclassOf('\\Drupal\\entity\\Entity\\EntityDescriptionInterface')) {
      return $bundles;
    }
    $bundle_names = array_keys($bundles);
    $bundle_entities = $this->entityTypeManager
      ->getStorage($bundle_type)
      ->loadMultiple($bundle_names);
    foreach ($bundles as $bundle_name => &$bundle_info) {
      if (isset($bundle_entities[$bundle_name])) {
        $bundle_info['description'] = $bundle_entities[$bundle_name]
          ->getDescription();
      }
    }
    return $bundles;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
EntityCreateController::$entityTypeBundleInfo protected property The entity type bundle info.
EntityCreateController::$renderer protected property The renderer service.
EntityCreateController::addForm public function Provides the add form for an entity.
EntityCreateController::addFormTitle public function The title callback for the add form.
EntityCreateController::addPage public function Displays add links for the available bundles.
EntityCreateController::addPageTitle public function The title callback for the add page.
EntityCreateController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
EntityCreateController::loadBundleDescriptions protected function Expands the bundle information with descriptions, if known.
EntityCreateController::__construct public function Constructs a new EntityCreateController object.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.