I try to create a REST resource. I used EntityResource as base. I would like to return my fields in html. Here is a exemple of my code :
public function get($id) {
if (!$this->currentUser->hasPermission('access content')) {
throw new AccessDeniedHttpException();
}
$entity = \Drupal::entityTypeManager()->getStorage('node')->load($id);
$entity_access = $entity->access('view', NULL, TRUE);
if (!$entity_access->isAllowed()) {
throw new AccessDeniedHttpException($entity_access->getReason() ? : $this->generateFallbackAccessDeniedMessage($entity, 'view'));
}
$result = array();
$other_entity_dependency = array();
if ($entity instanceof FieldableEntityInterface) {
$fields = array();
$contentType = $entity->bundle();
if (isset($contentType) && !empty($contentType)) {
foreach (\Drupal::entityManager()->getFieldDefinitions('node', $contentType) as $field_name => $field_definition) {
if (!empty($field_definition->getTargetBundle())) {
$fields[] = $field_name;
}
}
}
foreach ($fields as $field_name) {
$field = $entity->$field_name;
$field_access = $field->access('view', NULL, TRUE);
if ($field_access->isAllowed()) {
$value = \Drupal::service('renderer')->render($field->view())
$result[$field_name]['value'] = $value;
$result[$field_name]['label'] = $field->getFieldDefinition()->getLabel();
}
}
}
$response = new ResourceResponse($result, Response::HTTP_OK);
$response->addCacheableDependency($entity);
$response->addCacheableDependency($entity_access);
return $response;
}
The problem is that when I use a render function, I have this error :
The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Please ensure you are not rendering content too early. Returned object class: Drupal\rest\ResourceResponse.
I haven't this issue when I use $field->value
instead of \Drupal::service('renderer')->render($field->view())
, but I would like to have the html render of fields, for file or image too (these types of fields are empty when I use $field->value
).
How can I solve this problem ?
$value = $field->view()
and be done with it?$value = $field->view()
I get this error : Uncaught PHP Exception Symfony\\Component\\Serializer\\Exception\\UnexpectedValueException: "Could not normalize object of type Drupal\\Core\\Url, no supporting normalizer found."