Same filename and directory in other branches
- 8.x-1.x src/Controller/EntityReferenceAjaxController.php
Namespace
Drupal\entity_reference_ajax_formatter\Controller
File
-
src/Controller/EntityReferenceAjaxController.php
View source
<?php
declare (strict_types=1);
namespace Drupal\entity_reference_ajax_formatter\Controller;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Render\RendererInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class EntityReferenceAjaxController extends ControllerBase {
protected RendererInterface $renderer;
public function __construct(RendererInterface $renderer) {
$this->renderer = $renderer;
}
public function viewField(EntityInterface $entity, string $field_name, string $view_mode, string $language, int $start, ?string $printed) {
if (!$entity instanceof ContentEntityInterface) {
throw new BadRequestHttpException('Requested Entity is not a Content Entity.');
}
if (!($field = $entity->getTranslation($language)
->get($field_name))) {
throw new BadRequestHttpException('Requested Field does not exist.');
}
$response = new AjaxResponse();
$field_elements = $field->view($view_mode);
$response->addCommand(new ReplaceCommand("#ajax-field-{$entity->getEntityTypeId()}-{$entity->id()}-{$field_name}", $this->renderer
->render($field_elements)));
return $response;
}
public static function create(ContainerInterface $container) {
return new static($container->get('renderer'));
}
}
Classes