When there are #context properties added in a render array, the only way to retrieve them is by checking if the property isset() on the context array:

$context = $element->getProperty('context', []);
$entity = isset($context['entity']) ? $context['entity'] : NULL;
if ($entity) {
  $another = isset($context['another']) ? $context['another'] : 'default_value';
  // Do something with $entity and $another contexts.
}

This can become extremely repetitious and dilutes the readability of the code (e.g. getProperty and isset()).

To improve the DX, a getContext helper method should be created on both the Element and Variables classes:

if ($entity = $element->getContext('entity')) {
  $another = $element->getContext('another', 'default_value');
  // Do something with $entity and $another contexts.
}

Comments

markcarver created an issue. See original summary.

markhalliwell’s picture

Title: Create getContext helper method on Element and Variables classes » Add getContext helper method for Element and Variables classes

  • markcarver committed d48c6b1 on 8.x-3.x
    Issue #2818829 by markcarver: Add getContext helper method for Element...
markhalliwell’s picture

Status: Active » Fixed

Status: Fixed » Closed (fixed)

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