EntityController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. <?php
  2. namespace Drupal\Core\Entity\Controller;
  3. use Drupal\Core\Entity\EntityDescriptionInterface;
  4. use Drupal\Core\Entity\EntityInterface;
  5. use Drupal\Core\Entity\EntityRepositoryInterface;
  6. use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
  7. use Drupal\Core\Entity\EntityTypeManagerInterface;
  8. use Drupal\Core\Entity\EntityTypeInterface;
  9. use Drupal\Core\Link;
  10. use Drupal\Core\Render\RendererInterface;
  11. use Drupal\Core\Routing\RouteMatchInterface;
  12. use Drupal\Core\Routing\UrlGeneratorInterface;
  13. use Drupal\Core\Routing\UrlGeneratorTrait;
  14. use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
  15. use Drupal\Core\StringTranslation\StringTranslationTrait;
  16. use Drupal\Core\StringTranslation\TranslationInterface;
  17. use Drupal\Core\Url;
  18. use Symfony\Component\DependencyInjection\ContainerInterface;
  19. use Symfony\Component\HttpFoundation\RedirectResponse;
  20. /**
  21. * Provides the add-page and title callbacks for entities.
  22. *
  23. * It provides:
  24. * - The add-page callback.
  25. * - An add title callback for entity types.
  26. * - An add title callback for entity types with bundles.
  27. * - A view title callback.
  28. * - An edit title callback.
  29. * - A delete title callback.
  30. */
  31. class EntityController implements ContainerInjectionInterface {
  32. use StringTranslationTrait;
  33. use UrlGeneratorTrait;
  34. /**
  35. * The entity manager.
  36. *
  37. * @var \Drupal\Core\Entity\EntityTypeManagerInterface
  38. */
  39. protected $entityTypeManager;
  40. /**
  41. * The entity type bundle info.
  42. *
  43. * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
  44. */
  45. protected $entityTypeBundleInfo;
  46. /**
  47. * The entity repository.
  48. *
  49. * @var \Drupal\Core\Entity\EntityRepositoryInterface
  50. */
  51. protected $entityRepository;
  52. /**
  53. * The renderer.
  54. *
  55. * @var \Drupal\Core\Render\RendererInterface
  56. */
  57. protected $renderer;
  58. /**
  59. * Constructs a new EntityController.
  60. *
  61. * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
  62. * The entity type manager.
  63. * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
  64. * The entity type bundle info.
  65. * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
  66. * The entity repository.
  67. * @param \Drupal\Core\Render\RendererInterface $renderer
  68. * The renderer.
  69. * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
  70. * The string translation.
  71. * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
  72. * The url generator.
  73. */
  74. public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, EntityRepositoryInterface $entity_repository, RendererInterface $renderer, TranslationInterface $string_translation, UrlGeneratorInterface $url_generator) {
  75. $this->entityTypeManager = $entity_type_manager;
  76. $this->entityTypeBundleInfo = $entity_type_bundle_info;
  77. $this->entityRepository = $entity_repository;
  78. $this->renderer = $renderer;
  79. $this->stringTranslation = $string_translation;
  80. $this->urlGenerator = $url_generator;
  81. }
  82. /**
  83. * {@inheritdoc}
  84. */
  85. public static function create(ContainerInterface $container) {
  86. return new static(
  87. $container->get('entity_type.manager'),
  88. $container->get('entity_type.bundle.info'),
  89. $container->get('entity.repository'),
  90. $container->get('renderer'),
  91. $container->get('string_translation'),
  92. $container->get('url_generator')
  93. );
  94. }
  95. /**
  96. * Returns a redirect response object for the specified route.
  97. *
  98. * @param string $route_name
  99. * The name of the route to which to redirect.
  100. * @param array $route_parameters
  101. * (optional) Parameters for the route.
  102. * @param array $options
  103. * (optional) An associative array of additional options.
  104. * @param int $status
  105. * (optional) The HTTP redirect status code for the redirect. The default is
  106. * 302 Found.
  107. *
  108. * @return \Symfony\Component\HttpFoundation\RedirectResponse
  109. * A redirect response object that may be returned by the controller.
  110. */
  111. protected function redirect($route_name, array $route_parameters = [], array $options = [], $status = 302) {
  112. $options['absolute'] = TRUE;
  113. return new RedirectResponse(Url::fromRoute($route_name, $route_parameters, $options)->toString(), $status);
  114. }
  115. /**
  116. * Displays add links for the available bundles.
  117. *
  118. * Redirects to the add form if there's only one bundle available.
  119. *
  120. * @param string $entity_type_id
  121. * The entity type ID.
  122. *
  123. * @return \Symfony\Component\HttpFoundation\RedirectResponse|array
  124. * If there's only one available bundle, a redirect response.
  125. * Otherwise, a render array with the add links for each bundle.
  126. */
  127. public function addPage($entity_type_id) {
  128. $entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
  129. $bundles = $this->entityTypeBundleInfo->getBundleInfo($entity_type_id);
  130. $bundle_key = $entity_type->getKey('bundle');
  131. $bundle_entity_type_id = $entity_type->getBundleEntityType();
  132. $build = [
  133. '#theme' => 'entity_add_list',
  134. '#bundles' => [],
  135. ];
  136. if ($bundle_entity_type_id) {
  137. $bundle_argument = $bundle_entity_type_id;
  138. $bundle_entity_type = $this->entityTypeManager->getDefinition($bundle_entity_type_id);
  139. $bundle_entity_type_label = $bundle_entity_type->getSingularLabel();
  140. $build['#cache']['tags'] = $bundle_entity_type->getListCacheTags();
  141. // Build the message shown when there are no bundles.
  142. $link_text = $this->t('Add a new @entity_type.', ['@entity_type' => $bundle_entity_type_label]);
  143. $link_route_name = 'entity.' . $bundle_entity_type->id() . '.add_form';
  144. $build['#add_bundle_message'] = $this->t('There is no @entity_type yet. @add_link', [
  145. '@entity_type' => $bundle_entity_type_label,
  146. '@add_link' => Link::createFromRoute($link_text, $link_route_name)->toString(),
  147. ]);
  148. // Filter out the bundles the user doesn't have access to.
  149. $access_control_handler = $this->entityTypeManager->getAccessControlHandler($entity_type_id);
  150. foreach ($bundles as $bundle_name => $bundle_info) {
  151. $access = $access_control_handler->createAccess($bundle_name, NULL, [], TRUE);
  152. if (!$access->isAllowed()) {
  153. unset($bundles[$bundle_name]);
  154. }
  155. $this->renderer->addCacheableDependency($build, $access);
  156. }
  157. // Add descriptions from the bundle entities.
  158. $bundles = $this->loadBundleDescriptions($bundles, $bundle_entity_type);
  159. }
  160. else {
  161. $bundle_argument = $bundle_key;
  162. }
  163. $form_route_name = 'entity.' . $entity_type_id . '.add_form';
  164. // Redirect if there's only one bundle available.
  165. if (count($bundles) == 1) {
  166. $bundle_names = array_keys($bundles);
  167. $bundle_name = reset($bundle_names);
  168. return $this->redirect($form_route_name, [$bundle_argument => $bundle_name]);
  169. }
  170. // Prepare the #bundles array for the template.
  171. foreach ($bundles as $bundle_name => $bundle_info) {
  172. $build['#bundles'][$bundle_name] = [
  173. 'label' => $bundle_info['label'],
  174. 'description' => isset($bundle_info['description']) ? $bundle_info['description'] : '',
  175. 'add_link' => Link::createFromRoute($bundle_info['label'], $form_route_name, [$bundle_argument => $bundle_name]),
  176. ];
  177. }
  178. return $build;
  179. }
  180. /**
  181. * Provides a generic add title callback for an entity type.
  182. *
  183. * @param string $entity_type_id
  184. * The entity type ID.
  185. *
  186. * @return string
  187. * The title for the entity add page.
  188. */
  189. public function addTitle($entity_type_id) {
  190. $entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
  191. return $this->t('Add @entity-type', ['@entity-type' => $entity_type->getSingularLabel()]);
  192. }
  193. /**
  194. * Provides a generic add title callback for entities with bundles.
  195. *
  196. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
  197. * The route match.
  198. * @param string $entity_type_id
  199. * The entity type ID.
  200. * @param string $bundle_parameter
  201. * The name of the route parameter that holds the bundle.
  202. *
  203. * @return string
  204. * The title for the entity add page, if the bundle was found.
  205. */
  206. public function addBundleTitle(RouteMatchInterface $route_match, $entity_type_id, $bundle_parameter) {
  207. $bundles = $this->entityTypeBundleInfo->getBundleInfo($entity_type_id);
  208. // If the entity has bundle entities, the parameter might have been upcasted
  209. // so fetch the raw parameter.
  210. $bundle = $route_match->getRawParameter($bundle_parameter);
  211. if ((count($bundles) > 1) && isset($bundles[$bundle])) {
  212. return $this->t('Add @bundle', ['@bundle' => $bundles[$bundle]['label']]);
  213. }
  214. // If the entity supports bundles generally, but only has a single bundle,
  215. // the bundle is probably something like 'Default' so that it preferable to
  216. // use the entity type label.
  217. else {
  218. return $this->addTitle($entity_type_id);
  219. }
  220. }
  221. /**
  222. * Provides a generic title callback for a single entity.
  223. *
  224. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
  225. * The route match.
  226. * @param \Drupal\Core\Entity\EntityInterface $_entity
  227. * (optional) An entity, passed in directly from the request attributes.
  228. *
  229. * @return string|null
  230. * The title for the entity view page, if an entity was found.
  231. */
  232. public function title(RouteMatchInterface $route_match, EntityInterface $_entity = NULL) {
  233. if ($entity = $this->doGetEntity($route_match, $_entity)) {
  234. return $entity->label();
  235. }
  236. }
  237. /**
  238. * Provides a generic edit title callback.
  239. *
  240. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
  241. * The route match.
  242. * @param \Drupal\Core\Entity\EntityInterface $_entity
  243. * (optional) An entity, passed in directly from the request attributes.
  244. *
  245. * @return string|null
  246. * The title for the entity edit page, if an entity was found.
  247. */
  248. public function editTitle(RouteMatchInterface $route_match, EntityInterface $_entity = NULL) {
  249. if ($entity = $this->doGetEntity($route_match, $_entity)) {
  250. return $this->t('Edit %label', ['%label' => $entity->label()]);
  251. }
  252. }
  253. /**
  254. * Provides a generic delete title callback.
  255. *
  256. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
  257. * The route match.
  258. * @param \Drupal\Core\Entity\EntityInterface $_entity
  259. * (optional) An entity, passed in directly from the request attributes, and
  260. * set in \Drupal\Core\Entity\Enhancer\EntityRouteEnhancer.
  261. *
  262. * @return string
  263. * The title for the entity delete page.
  264. */
  265. public function deleteTitle(RouteMatchInterface $route_match, EntityInterface $_entity = NULL) {
  266. if ($entity = $this->doGetEntity($route_match, $_entity)) {
  267. return $this->t('Delete %label', ['%label' => $entity->label()]);
  268. }
  269. }
  270. /**
  271. * Determines the entity.
  272. *
  273. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
  274. * The route match.
  275. * @param \Drupal\Core\Entity\EntityInterface $_entity
  276. * (optional) The entity, set in
  277. * \Drupal\Core\Entity\Enhancer\EntityRouteEnhancer.
  278. *
  279. * @return \Drupal\Core\Entity\EntityInterface|null
  280. * The entity, if it is passed in directly or if the first parameter of the
  281. * active route is an entity; otherwise, NULL.
  282. */
  283. protected function doGetEntity(RouteMatchInterface $route_match, EntityInterface $_entity = NULL) {
  284. if ($_entity) {
  285. $entity = $_entity;
  286. }
  287. else {
  288. // Let's look up in the route object for the name of upcasted values.
  289. foreach ($route_match->getParameters() as $parameter) {
  290. if ($parameter instanceof EntityInterface) {
  291. $entity = $parameter;
  292. break;
  293. }
  294. }
  295. }
  296. if (isset($entity)) {
  297. return $this->entityRepository->getTranslationFromContext($entity);
  298. }
  299. }
  300. /**
  301. * Expands the bundle information with descriptions, if known.
  302. *
  303. * @param array $bundles
  304. * An array of bundle information.
  305. * @param \Drupal\Core\Entity\EntityTypeInterface $bundle_entity_type
  306. * The bundle entity type definition.
  307. *
  308. * @return array
  309. * The expanded array of bundle information.
  310. */
  311. protected function loadBundleDescriptions(array $bundles, EntityTypeInterface $bundle_entity_type) {
  312. if (!$bundle_entity_type->entityClassImplements(EntityDescriptionInterface::class)) {
  313. return $bundles;
  314. }
  315. $bundle_names = array_keys($bundles);
  316. $storage = $this->entityTypeManager->getStorage($bundle_entity_type->id());
  317. /** @var \Drupal\Core\Entity\EntityDescriptionInterface[] $bundle_entities */
  318. $bundle_entities = $storage->loadMultiple($bundle_names);
  319. foreach ($bundles as $bundle_name => &$bundle_info) {
  320. if (isset($bundle_entities[$bundle_name])) {
  321. $bundle_info['description'] = $bundle_entities[$bundle_name]->getDescription();
  322. }
  323. }
  324. return $bundles;
  325. }
  326. }