The FieldBlock block plugin essentially ignores any cache metadata that is set in the render array returned from a field formatter. Here's the build method of the block:


  /**
   * {@inheritdoc}
   */
  public function build() {
    $display_settings = $this->getConfiguration()['formatter'];
    $entity = $this->getEntity();

    // If this entity was constructed with sample data, return nothing to force
    // a placeholder to render instead. The sample data is rarely user friendly
    // can create issues in field formatters and blocks that assume the entity
    // has legit data.
    if ($entity->has_sample_data) {
      return [];
    }

    try {
      $build = $entity->get($this->fieldName)->view($display_settings);
    }
    // @todo Remove in https://www.drupal.org/project/drupal/issues/2367555.
    catch (EnforcedResponseException $e) {
      throw $e;
    }
    catch (\Exception $e) {
      $build = [];
      $this->logger->warning('The field "%field" failed to render with the error of "%error".', ['%field' => $this->fieldName, '%error' => $e->getMessage()]);
    }
    CacheableMetadata::createFromObject($this)->applyTo($build);
    return $build;
  }

The CacheableMetadata::createFromObject($this)->applyTo($build); is troublesome because it just overwrites the cache metadata that may already exist on the $build render array.

CommentFileSizeAuthor
#2 field-block-cache-3071646.patch773 bytesbkosborne

Comments

bkosborne created an issue. See original summary.

bkosborne’s picture

Status: Active » Needs review
Issue tags: +Needs tests
StatusFileSize
new773 bytes
tim.plunkett’s picture

Status: Needs review » Needs work
Issue tags: +Blocks-Layouts

Good find!

+++ b/core/modules/layout_builder/src/Plugin/Block/FieldBlock.php
@@ -169,7 +169,11 @@ public function build() {
+      ->merge(CacheableMetadata::createFromObject($this))

I think this is more common: ->addCacheableDependency($this)

NW for the tests.

Version: 8.8.x-dev » 8.9.x-dev

Drupal 8.8.0-alpha1 will be released the week of October 14th, 2019, which means new developments and disruptive changes should now be targeted against the 8.9.x-dev branch. (Any changes to 8.9.x will also be committed to 9.0.x in preparation for Drupal 9’s release, but some changes like significant feature additions will be deferred to 9.1.x.). For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

Version: 8.9.x-dev » 9.1.x-dev

Drupal 8.9.0-beta1 was released on March 20, 2020. 8.9.x is the final, long-term support (LTS) minor release of Drupal 8, which means new developments and disruptive changes should now be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

tim.plunkett’s picture