See also #2332955: Nested entity rendering problem in DrupalCommerceEntityController::buildContent()

The unset($entity->content) in EntityAPIController::buildContent() causes a problem when rendering the same entity in nested view modes.
E.g. if an entity display has a field that renders "related entities" or "child entities", and one of them happens to be the same entity itself, then buildContent() can blow up.

More detail:
EntityAPIController::buildContent() has the following lines, among others:

    // Remove previously built content, if exists.
    $entity->content = $content;
    ..
    // Add in fields.
    if (!empty($this->entityInfo['fieldable'])) {
      $entity->content += field_attach_view($this->entityType, $entity, $view_mode, $langcode);
    }
    ..
    $build = $entity->content;
    unset($entity->content);

Problem: If the same entity is being rendered again as part of field_attach_view(), $entity->content will be empty when the += hits.

This could be avoided with this cheap trick (this helps to understand what is happening):

      $entity->content = $entity->content + field_attach_view($this->entityType, $entity, $view_mode, $langcode);

However, this is not a clean solution. It still means that parts of field_attach_view() will have the wrong values in $entity->content.

Maybe this is better:

  public function buildContent($entity, $view_mode = 'full', $langcode = NULL, $content = array()) {
    $oldcontent 
    // Remove previously built content, if exists.
    $entity->content = $content;
    ...
    // Add in fields.
    if (!empty($this->entityInfo['fieldable'])) {
      $entity->content += field_attach_view($this->entityType, $entity, $view_mode, $langcode);
    }
    ...
    $build = $entity->content;
    unset($entity->content);
    if (isset($oldcontent)) {
      $entity->content = $oldcontent;
    }
Support from Acquia helps fund testing for Drupal Acquia logo

Comments

donquixote’s picture

Status: Active » Needs review
FileSize
1.52 KB
donquixote’s picture

I added a try / finally in #2332955-5: Nested entity rendering problem in DrupalCommerceEntityController::buildContent() for commerce.
Everything that we do there can or should also be done here. But I will for now only work on the commerce issue.

Chris Matthews’s picture

The patch in #1 to entity.controller.inc applied cleanly to the latest entity 7.x-1.x-dev, but still needs to be reviewed and tested.

das-peter’s picture