API page: https://api.drupal.org/api/drupal/core%21modules%21block%21block.api.php...

$build['#contexts'][] = 'user';

should be

$build['#cache']['contexts'][] = 'user';

CommentFileSizeAuthor
#2 mistake_in-2828372-2.patch558 bytesSut3kh

Comments

Sut3kh created an issue. See original summary.

Sut3kh’s picture

Status: Active » Needs review
StatusFileSize
new558 bytes
chi’s picture

Status: Needs review » Reviewed & tested by the community
Issue tags: -documentation bug +Documentation

  • xjm committed 7b1b981 on 8.3.x
    Issue #2828372 by Sut3kh: Mistake in hook_block_build_alter example
    

  • xjm committed da7d1ad on 8.2.x
    Issue #2828372 by Sut3kh: Mistake in hook_block_build_alter example
    
    (...
xjm’s picture

Status: Reviewed & tested by the community » Fixed

The documentation also says:

A renderable array of data, only containing #cache

So based on that, there is indeed no way that the current example can be correct. I also compared to other references to this in core:

[mandelbrot:drupal | Sat 12:06:24] $ grep -r "\$build\['\#contexts'\]\[\]" *
core/modules/block/block.api.php:    $build['#contexts'][] = 'user';
[mandelbrot:drupal | Sat 12:09:17] $ grep -r "\$build\['\#cache\'\]\[\'contexts'\]\[\]" *
core/modules/block/tests/modules/block_test/block_test.module:    $build['#cache']['contexts'][] = \Drupal::state()->get('block_test_block_alter_cache_context');
core/modules/history/history.module:    $build['#cache']['contexts'][] = 'user.roles:authenticated';
core/modules/node/src/Controller/NodeViewController.php:    $build['#cache']['contexts'][] = 'user.roles:anonymous';
core/modules/quickedit/quickedit.module:  $build['#cache']['contexts'][] = 'user.permissions';
core/modules/search/src/Controller/SearchController.php:    $build['#cache']['contexts'][] = 'url.query_args:keys';
core/tests/Drupal/Tests/Core/Render/RendererTestBase.php:    $build['#cache']['contexts'][] = 'user';

So that also supports the correction. All the documentation for the hook was added in #2543340: Convert BlockViewBuilder to use #lazy_builder (but don't yet let context-aware blocks be placeholdered) and has not changed since, so it looks like it was just a typo in the original patch (which in fact even added the usage in block_test.module that the hook docs contradicted).

Committed and pushed to 8.3.x and 8.2.x. Thanks!

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.