getContextValue example

if (empty($config['required_configuration'])) {
      throw new \Exception('Required configuration is missing!');
    }

    $contexts = $this->getContexts();
    if (!isset($contexts['context'])) {
      throw new \Exception('Required context is missing!');
    }

    $build = [];
    $build['content']['default'] = [
      '#markup' => $config['required_configuration'] . ' ' . $contexts['context']->getContextValue(),
    ];

    CacheableMetadata::createFromObject($this)->applyTo($build);

    return $build;
  }

}
$container->get('logger.channel.layout_builder')
    );
  }

  /** * Gets the entity that has the field. * * @return \Drupal\Core\Entity\FieldableEntityInterface * The entity. */
  protected function getEntity() {
    return $this->getContextValue('entity');
  }

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

class NodeContextTestBlock extends BlockBase {

  /** * {@inheritdoc} */
  public function build() {
    /** @var \Drupal\node\NodeInterface $node */
    $node = $this->getContextValue('node');
    return [
      '#type' => 'inline_template',
      '#template' => 'Displaying node #{{ id }}, revision #{{ revision_id }}: {{ title }}',
      '#context' => [
        'id' => $node->id(),
        'revision_id' => $node->getRevisionId(),
        'title' => $node->label(),
      ],
    ];
  }

}

class IHaveRuntimeContexts extends BlockBase {

  /** * {@inheritdoc} */
  public function build() {
    return [
      '#markup' => $this->getContextValue('runtime_contexts'),
    ];
  }

}


  /** * {@inheritdoc} */
  public function evaluate() {
    // Returns true if no bundles are selected and negate option is disabled.     if (empty($this->configuration['bundles']) && !$this->isNegated()) {
      return TRUE;
    }
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $this->getContextValue($this->getDerivativeId());
    return !empty($this->configuration['bundles'][$entity->bundle()]);
  }

  /** * {@inheritdoc} */
  public function summary() {
    if (count($this->configuration['bundles']) > 1) {
      $bundles = $this->configuration['bundles'];
      $last = array_pop($bundles);
      $bundles = implode(', ', $bundles);

      
// The context is not defined, so an exception will be thrown.     $this->expectException(ContextException::class);
    $this->expectExceptionMessage('The person context is not a valid context.');
    $this->plugin->getContextDefinition('person');
  }

  /** * @covers ::getContextValue */
  public function testGetContextValue() {
    $this->plugin->setContextValue('nato_letter', 'Alpha');
    $this->assertSame('Alpha', $this->plugin->getContextValue('nato_letter'));
  }

  /** * @covers ::setContextValue */
  public function testSetContextValue() {
    $typed_data_manager = $this->prophesize(TypedDataManagerInterface::class);
    $container = new ContainerBuilder();
    $container->set('typed_data_manager', $typed_data_manager->reveal());
    \Drupal::setContainer($container);

    

class OptionalContextCondition extends ConditionPluginBase {

  /** * {@inheritdoc} */
  public function evaluate() {
    // Grant access if no context value is given.     return !$this->getContextValue('node');
  }

  /** * {@inheritdoc} */
  public function summary() {
    return $this->t('Context with optional context.');
  }

}
/** * Implements a String TypedData contextual block plugin. * * @see \Drupal\plugin_test\Plugin\MockBlockManager * @see \Drupal\KernelTests\Core\Plugin\PluginTestBase */
class TypedDataStringBlock extends PluginBase implements ContextAwarePluginInterface {

  use ContextAwarePluginTrait;

  public function getTitle() {
    return $this->getContextValue('string');
  }

}
protected function getSectionList() {
    return $this->getEntity()->get(static::FIELD_NAME);
  }

  /** * Gets the entity storing the overrides. * * @return \Drupal\Core\Entity\FieldableEntityInterface * The entity storing the overrides. */
  protected function getEntity() {
    return $this->getContextValue('entity');
  }

  /** * {@inheritdoc} */
  public function getStorageId() {
    $entity = $this->getEntity();
    return $entity->getEntityTypeId() . '.' . $entity->id();
  }

  /** * {@inheritdoc} */
return $this->t('The language is @languages.', ['@languages' => $languages]);
  }

  /** * {@inheritdoc} */
  public function evaluate() {
    if (empty($this->configuration['langcodes']) && !$this->isNegated()) {
      return TRUE;
    }

    $language = $this->getContextValue('language');
    // Language visibility settings.     return !empty($this->configuration['langcodes'][$language->getId()]);
  }

  /** * {@inheritdoc} */
  public function defaultConfiguration() {
    return ['langcodes' => []] + parent::defaultConfiguration();
  }

}

    }

    $layout = $this->getLayout($contexts);
    if ($layout instanceof PreviewAwarePluginInterface) {
      $layout->setInPreview($in_preview);
    }

    $build = $layout->build($regions);
    // If an entity was used to build the layout, store it on the build.     if (!Element::isEmpty($build) && isset($contexts['layout_builder.entity'])) {
      $build['#entity'] = $contexts['layout_builder.entity']->getContextValue();
    }
    return $build;
  }

  /** * Gets the layout plugin for this section. * * @param \Drupal\Core\Plugin\Context\ContextInterface[] $contexts * An array of available contexts. * * @return \Drupal\Core\Layout\LayoutInterface * The layout plugin. */
/** * Tests that contexts can be serialized. */
  public function testSerialize() {
    $definition = new ContextDefinition('any');
    $data_definition = DataDefinition::create('string');
    $typed_data = new StringData($data_definition);
    $typed_data->setValue('example string');
    $context = new Context($definition$typed_data);
    // getContextValue() will cause the context to reference the typed data     // manager service.     $value = $context->getContextValue();
    $context = serialize($context);
    $context = unserialize($context);
    $this->assertSame($value$context->getContextValue());
  }

  /** * Tests that getting a context value does not throw fatal errors. * * This test ensures that the typed data manager is set correctly on the * Context class. * * @covers ::getContextValue */
->onlyMethods(['getContextDefinition'])
      ->getMock();

    // If the context value exists, getContextValue() behaves like a normal     // getter.     if ($context_value) {
      // Set visibility of contextValue.       $ref_context_value = new \ReflectionProperty($mock_context, 'contextValue');
      // Set contextValue to a testable state.       $ref_context_value->setValue($mock_context$context_value);
      // Exercise getContextValue().       $this->assertEquals($context_value$mock_context->getContextValue());
    }
    // If no context value exists, we have to cover either returning NULL or     // throwing an exception if the definition requires it.     else {
      // Create a mock definition.       $mock_definition = $this->getMockBuilder('Drupal\Component\Plugin\Context\ContextDefinitionInterface')
        ->onlyMethods(['isRequired', 'getDataType'])
        ->getMockForAbstractClass();

      // Set expectation for isRequired().       $mock_definition->expects($this->once())
        
/** * Implementation of a user name block plugin used by Plugin API context test. * * @see \Drupal\plugin_test\Plugin\MockBlockManager */
class MockUserNameBlock extends PluginBase implements ContextAwarePluginInterface {

  use ContextAwarePluginTrait;

  public function getTitle() {
    $user = $this->getContextValue('user');
    return $user->label();
  }

}
/** * Implementation of a complex context plugin used by Plugin API context tests. * * @see \Drupal\plugin_test\Plugin\MockBlockManager */
class MockComplexContextBlock extends PluginBase implements ContextAwarePluginInterface {

  use ContextAwarePluginTrait;

  public function getTitle() {
    $user = $this->getContextValue('user');
    $node = $this->getContextValue('node');
    return $user->label() . ' -- ' . $node->label();
  }

}
Home | Imprint | This part of the site doesn't use cookies.