Problem

When trying to view a revision of content whose template file uses twig tweak functions, I get a 500 error on prod. When I test the same content on local, I get the following error:

The website encountered an unexpected error. Please try again later.
Error: Call to a member function access() on string in Drupal\twig_tweak\TwigExtension->drupalField() (line 362 of modules/contrib/twig_tweak/src/TwigExtension.php).

The code in question is:

  public function drupalField($field_name, $entity_type, $id = NULL, $view_mode = 'default', $langcode = NULL, $check_access = TRUE) {
    if ($id) {
      $entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($id);
    }
    else {
      @trigger_error('Loading entities from route is deprecated in Twig Tweak 2.4 and will not be supported in Twig Tweak 3.0', E_USER_DEPRECATED);
      $entity = \Drupal::routeMatch()->getParameter($entity_type);
    }
    if ($entity && (!$check_access || $entity->access('view'))) {
      $entity = \Drupal::service('entity.repository')
        ->getTranslationFromContext($entity, $langcode);
      if (isset($entity->{$field_name})) {
        return $entity->{$field_name}->view($view_mode);
      }
    }
  }

where the line if ($entity && (!$check_access || $entity->access('view'))) { is assuming that $entity is an entity. However, this doesn't work when an entity ID is not passed or the route is relying on the entity.

My (hopefully) short-term workaround is to use a ternary in the templates, such as {{ drupal_field('field_sub_title_text', 'node', (entity_id ? node.id : node) , 'full') }} where the node object is actually a node object when the route rendering the template is canonical, but when it's a revision with the pattern node/{NID}/revisions/{REVISION_ID}/view the node variable in the page template is a string containing the NID.

I think that a better solution would be to get the revision ID of the content being passed so that with a fix like mine, the correct content is shown when viewing a revision. I'm assuming that only using the NID will give the current active revision's data as opposed to a previous revision when viewing changes.

Comments

dorficus created an issue. See original summary.

chi’s picture

Status: Active » Closed (won't fix)
Related issues: +#2730631: Upcast node and node_revision parameters of node revision routes

It's up to developer to make sure that drupal_field() gets a correct entity ID. If the route does not contain entity object you have to pass entity ID explicitly. Note that loading entity objects from route is deprecated and will be removed in the next major version of the module. So it's recommended always pass entity ID to that function.

To render the field with respect of loaded node revision use the following code.
{{ node.field_sub_title_text|view }}
If you don't have node variable in your template you have to create it in an appropriate preprocess hook.