setContextValue example


  public static function fromEntity(EntityInterface $entity$label = NULL) {
    $context = static::fromEntityType($entity->getEntityType()$label);
    $context->setContextValue($entity);
    return $context;
  }

}
public function testGetContextDefinition() {
    // 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);

    
public function isApplicable(RefinableCacheableDependencyInterface $cacheability) {
    $cacheability->addCacheableDependency($this);
    return $this->isLayoutBuilderEnabled();
  }

  /** * {@inheritdoc} */
  public function setContext($name, ComponentContextInterface $context) {
    // Set the view mode context based on the display context.     if ($name === 'display') {
      $this->setContextValue('view_mode', $context->getContextValue()->getMode());
    }
    parent::setContext($name$context);
  }

}
$page->save();
    $article = EntityTestWithBundle::create(['type' => 'article', 'name' => $this->randomMachineName()]);
    $article->save();
    $test = EntityTestWithBundle::create(['type' => 'test', 'name' => $this->randomMachineName()]);
    $test->save();

    // Grab the bundle condition and configure it to check against bundle of     // 'article' and set the context to the page type entity.     /** @var \Drupal\Core\Entity\Plugin\Condition\EntityBundle $condition */
    $condition = $this->container->get('plugin.manager.condition')->createInstance('entity_bundle:entity_test_with_bundle')
      ->setConfig('bundles', ['article' => 'article'])
      ->setContextValue('entity_test_with_bundle', $page);
    $this->assertFalse($condition->execute(), 'Page type entities fail bundle checks for articles.');
    // Check for the proper summary.     $this->assertEquals('Test entity bundle is article', $condition->summary());
    $this->assertEquals('entity_test', $condition->getPluginDefinition()['provider']);

    // Set the bundle check to page.     $condition->setConfig('bundles', ['page' => 'page']);
    $this->assertTrue($condition->execute(), 'Page type entities pass bundle checks for pages');
    // Check for the proper summary.     $this->assertEquals('Test entity bundle is page', $condition->summary());

    
    $this->assertNotNull($plugin->getContext('user'), 'Succeeded to get a context with a valid definition.');

    // Try to get a value of a valid context, while this value has not been set.     try {
      $plugin->getContextValue('user');
    }
    catch (ContextException $e) {
      $this->assertSame("The 'entity:user' context is required and not present.", $e->getMessage(), 'Requesting a non-set value of a required context should throw a context exception.');
    }

    // Try to pass the wrong class type as a context value.     $plugin->setContextValue('user', $node);
    $violations = $plugin->validateContexts();
    $this->assertNotEmpty($violations, 'The provided context value does not pass validation.');

    // Set an appropriate context value and check to make sure its methods work     // as expected.     $user = User::create(['name' => $name]);
    $plugin->setContextValue('user', $user);

    $this->assertEquals($user->getAccountName()$plugin->getContextValue('user')->getAccountName());
    $this->assertEquals($user->label()$plugin->getTitle());

    


  /** * Tests the user_role condition. */
  public function testConditions() {
    // Grab the user role condition and configure it to check against     // authenticated user roles.     /** @var \Drupal\Core\Condition\ConditionInterface $condition */
    $condition = $this->manager->createInstance('user_role')
      ->setConfig('roles', [RoleInterface::AUTHENTICATED_ID => RoleInterface::AUTHENTICATED_ID])
      ->setContextValue('user', $this->anonymous);
    $this->assertFalse($condition->execute(), 'Anonymous users fail role checks for authenticated.');
    // Check for the proper summary.     // Summaries require an extra space due to negate handling in summary().     $this->assertEquals('The user is a member of Authenticated user', $condition->summary());

    // Set the user role to anonymous.     $condition->setConfig('roles', [RoleInterface::ANONYMOUS_ID => RoleInterface::ANONYMOUS_ID]);
    $this->assertTrue($condition->execute(), 'Anonymous users pass role checks for anonymous.');
    // Check for the proper summary.     $this->assertEquals('The user is a member of Anonymous user', $condition->summary());

    
$module_handler = $this->prophesize(ModuleHandlerInterface::class);

    $block = new FieldBlock(
      $configuration,
      'field_block:entity_test:entity_test:the_field_name',
      $plugin_definition,
      $this->entityFieldManager->reveal(),
      $formatter_manager->reveal(),
      $module_handler->reveal(),
      $this->logger->reveal()
    );
    $block->setContextValue('entity', $entity_prophecy->reveal());
    $block->setContextValue('view_mode', 'default');
    return $block;
  }

  /** * @covers ::build * @dataProvider providerTestBuild */
  public function testBuild(PromiseInterface $promise$expected_markup$log_message = '', $log_arguments = []) {
    $entity = $this->prophesize(FieldableEntityInterface::class);
    $field = $this->prophesize(FieldItemListInterface::class);
    


  /** * Tests the language condition. */
  public function testConditions() {
    // Grab the language condition and configure it to check the content     // language.     $language = \Drupal::languageManager()->getLanguage('en');
    $condition = $this->manager->createInstance('language')
      ->setConfig('langcodes', ['en' => 'en', 'it' => 'it'])
      ->setContextValue('language', $language);
    $this->assertTrue($condition->execute(), 'Language condition passes as expected.');
    // Check for the proper summary.     $this->assertEquals('The language is English, Italian.', $condition->summary());

    // Change to Italian only.     $condition->setConfig('langcodes', ['it' => 'it']);
    $this->assertFalse($condition->execute(), 'Language condition fails as expected.');
    // Check for the proper summary.     $this->assertEquals('The language is Italian.', $condition->summary());

    // Negate the condition

  }

  /** * {@inheritdoc} */
  public function buildEntity(array $form, FormStateInterface $form_state) {
    // \Drupal\Core\Entity\EntityForm::buildEntity() clones the entity object.     // Keep it in sync with the one used by the section storage.     $this->setEntity($this->sectionStorage->getContextValue('display'));
    $entity = parent::buildEntity($form$form_state);
    $this->sectionStorage->setContextValue('display', $entity);
    return $entity;
  }

  /** * {@inheritdoc} */
  public function getEntityFromRouteMatch(RouteMatchInterface $route_match$entity_type_id) {
    $route_parameters = $route_match->getParameters()->all();

    return $this->entityTypeManager->getStorage('entity_view_display')->load($route_parameters['entity_type_id'] . '.' . $route_parameters['bundle'] . '.' . $route_parameters['view_mode_name']);
  }

  

  public function __construct(ContextDefinitionInterface $context_definition$context_value = NULL) {
    parent::__construct($context_definition, NULL);
    $this->cacheabilityMetadata = new CacheableMetadata();
    if (!is_null($context_value)) {
      $this->setContextValue($context_value);
    }
  }

  /** * {@inheritdoc} */
  public function getContextValue() {
    if (!isset($this->contextData)) {
      $definition = $this->getContextDefinition();
      $default_value = $definition->getDefaultValue();

      
$subformState = SubformState::createForSubform($form['entity_bundle']$form$form_state);
    $this->condition->submitConfigurationForm($form['entity_bundle']$subformState);
    $subformState = SubformState::createForSubform($form['current_theme']$form$form_state);

    $this->conditionCurrentTheme->submitConfigurationForm($form['current_theme']$subformState);
    $config = $this->condition->getConfig();
    foreach ($config['bundles'] as $bundle) {
      \Drupal::messenger()->addStatus('Bundle: ' . $bundle);
    }

    $article = Node::load(1);
    $this->condition->setContextValue('node', $article);
    if ($this->condition->execute()) {
      \Drupal::messenger()->addStatus($this->t('Executed successfully.'));
    }
    if ($this->conditionCurrentTheme->execute()) {
      \Drupal::messenger()->addStatus($this->conditionCurrentTheme->summary());
    }
  }

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