Skip to content
Snippets Groups Projects

Add an overridden add page with destination support

Files
2
+ 79
0
<?php
namespace Drupal\entity\Controller;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\Controller\EntityController as BaseEntityController;
use Drupal\Core\Link;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Provides an add-page with destination support for entities.
*/
class EntityController extends BaseEntityController {
/**
* 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.
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object. If this contains a destination query parameter, it is
* "forwarded" to the add links (or the redirect response).
*
* @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, Request $request = NULL) {
$response = parent::addPage($entity_type_id);
if ($request && $request->query->has('destination')) {
// If the request includes a destination, fetch it to add it to the links
// below, but remove it from the request so that it does not override the
// redirect that happens in case there is only a single bundle.
$destination = $request->query->get('destination');
$request->query->remove('destination');
if ($response instanceof RedirectResponse) {
// Override the redirect to include the destination query parameter.
$form_route_name = 'entity.' . $entity_type_id . '.add_form';
$entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
$bundle_argument = $entity_type->getBundleEntityType() ?: $entity_type->getKey('bundle');
$bundle_names = array_keys($this->entityTypeBundleInfo->getBundleInfo($entity_type_id));
$bundle_name = reset($bundle_names);
$response = $this->redirect(
$form_route_name,
[$bundle_argument => $bundle_name],
['query' => ['destination' => $destination]]
);
}
else {
assert(is_array($response));
// Make sure that different destination query parameters create separate
// cache entries.
CacheableMetadata::createFromRenderArray($response)
->addCacheContexts(['url.query_args:destination'])
->applyTo($response);
assert(isset($response['#bundles']) && is_array($response['#bundles']));
foreach ($response['#bundles'] as $bundle) {
assert(isset($bundle['add_link']) && ($bundle['add_link'] instanceof Link));
// Add the destination to each add link.
$bundle['add_link']->getUrl()->mergeOptions([
'query' => [
'destination' => $destination,
],
]);
}
}
}
return $response;
}
}
Loading