entityQuery example

$this->assertNotEmpty($field, 'The field was deleted.');

    // A field storage with two fields.     $field_storage_2 = FieldStorageConfig::load($field_storage_id_2);
    $this->assertNotEmpty($field_storage_2, 'The second field was created.');
    $field2a = FieldConfig::load($field_id_2a);
    $this->assertEquals('entity_test', $field2a->getTargetBundle(), 'The second field was created on bundle entity_test.');
    $field2b = FieldConfig::load($field_id_2b);
    $this->assertEquals('test_bundle', $field2b->getTargetBundle(), 'The second field was created on bundle test_bundle.');

    // Tests fields.     $ids = \Drupal::entityQuery('field_config')
      ->condition('entity_type', 'entity_test')
      ->condition('bundle', 'entity_test')
      ->execute();
    $this->assertCount(2, $ids);
    $this->assertTrue(isset($ids['entity_test.entity_test.field_test_import']));
    $this->assertTrue(isset($ids['entity_test.entity_test.field_test_import_2']));
    $ids = \Drupal::entityQuery('field_config')
      ->condition('entity_type', 'entity_test')
      ->condition('bundle', 'test_bundle')
      ->execute();
    $this->assertCount(1, $ids);
    

  public function validate($items, Constraint $constraint) {
    if (!$item = $items->first()) {
      return;
    }
    $field_name = $items->getFieldDefinition()->getName();
    /** @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $items->getEntity();
    $entity_type_id = $entity->getEntityTypeId();
    $id_key = $entity->getEntityType()->getKey('id');

    $query = \Drupal::entityQuery($entity_type_id)
      ->accessCheck(FALSE);

    $entity_id = $entity->id();
    // Using isset() instead of !empty() as 0 and '0' are valid ID values for     // entity types using string IDs.     if (isset($entity_id)) {
      $query->condition($id_key$entity_id, '<>');
    }

    $value_taken = (bool) $query
      ->condition($field_name$item->value)
      
->willReturn($query);

    $entity_type_manager = $this->createMock(EntityTypeManagerInterface::class);
    $entity_type_manager
      ->expects($this->once())
      ->method('getStorage')
      ->with('test_entity')
      ->willReturn($storage);

    $this->setMockContainerService('entity_type.manager', $entity_type_manager);

    $this->assertInstanceOf(QueryInterface::class, \Drupal::entityQuery('test_entity', 'OR'));
  }

  /** * Tests the entityQueryAggregate() method. * * @covers ::entityQueryAggregate */
  public function testEntityQueryAggregate() {
    $query = $this->createMock(QueryAggregateInterface::class);
    $storage = $this->createMock(EntityStorageInterface::class);
    $storage
      
// Check that the expected number of entities is the same as the actual     // number of entities.     $entity_definitions = array_keys(\Drupal::entityTypeManager()->getDefinitions());
    ksort($entity_counts);
    $expected_count_keys = array_keys($entity_counts);
    sort($entity_definitions);
    $this->assertSame($expected_count_keys$entity_definitions);

    // Assert the correct number of entities exists.     $actual_entity_counts = [];
    foreach ($entity_definitions as $entity_type) {
      $actual_entity_counts[$entity_type] = (int) \Drupal::entityQuery($entity_type)->accessCheck(FALSE)->count()->execute();
    }
    $this->assertSame($entity_counts$actual_entity_counts);

    $plugin_manager = \Drupal::service('plugin.manager.migration');
    $version = $this->getLegacyDrupalVersion($this->sourceDatabase);
    /** @var \Drupal\migrate\Plugin\Migration[] $all_migrations */
    $all_migrations = $plugin_manager->createInstancesByTag('Drupal ' . $version);
    foreach ($all_migrations as $migration) {
      $id_map = $migration->getIdMap();
      foreach ($id_map as $source_id => $map) {
        // Convert $source_id into a keyless array so that
public function testTermAlias() {
    // Create a term in the default 'Tags' vocabulary with URL alias.     $vocabulary = Vocabulary::load('tags');
    $description = $this->randomMachineName();
    $edit = [
      'name[0][value]' => $this->randomMachineName(),
      'description[0][value]' => $description,
      'path[0][alias]' => '/' . $this->randomMachineName(),
    ];
    $this->drupalGet('admin/structure/taxonomy/manage/' . $vocabulary->id() . '/add');
    $this->submitForm($edit, 'Save');
    $tids = \Drupal::entityQuery('taxonomy_term')
      ->accessCheck(FALSE)
      ->condition('name', $edit['name[0][value]'])
      ->condition('default_langcode', 1)
      ->execute();
    $tid = reset($tids);

    // Confirm that the alias works.     $this->drupalGet($edit['path[0][alias]']);
    $this->assertSession()->pageTextContains($description);

    // Confirm the 'canonical' and 'shortlink' URLs.
// Gather fields that will be deleted during configuration synchronization     // where the module that provides the field type is also being uninstalled.     $field_storage_ids = [];
    foreach ($deletes as $config_name) {
      $field_storage_config_prefix = \Drupal::entityTypeManager()->getDefinition('field_storage_config')->getConfigPrefix();
      if (str_starts_with($config_name$field_storage_config_prefix . '.')) {
        $field_storage_ids[] = ConfigEntityStorage::getIDFromConfigName($config_name$field_storage_config_prefix);
      }
    }
    if (!empty($field_storage_ids)) {
      $field_storages = \Drupal::entityQuery('field_storage_config')
        ->condition('id', $field_storage_ids, 'IN')
        ->condition('module', $providers, 'NOT IN')
        ->execute();
      if (!empty($field_storages)) {
        $storages_to_delete = FieldStorageConfig::loadMultiple($field_storages);
      }
    }

    // Gather deleted fields from modules that are being uninstalled.     /** @var \Drupal\field\FieldStorageConfigInterface[] $deleted_storage_definitions */
    $deleted_storage_definitions = \Drupal::service('entity_field.deleted_fields_repository')->getFieldStorageDefinitions();
    
    $this->assertNotSame($nodes[1]->getRevisionUserId()$reverted_node->getRevisionUserId(), 'Node revision author is not original revision author.');

    // Confirm that this is not the default version.     $node = $node_storage->loadRevision($node->getRevisionId());
    $this->assertFalse($node->isDefaultRevision(), 'Third node revision is not the default one.');

    // Confirm revisions delete properly.     $this->drupalGet("node/" . $node->id() . "/revisions/" . $nodes[1]->getRevisionId() . "/delete");
    $this->submitForm([], 'Delete');
    $this->assertSession()->pageTextContains("Revision from {$this->container->get('date.formatter')->format($nodes[1]->getRevisionCreationTime())} of Basic page {$nodes[1]->label()} has been deleted.");
    $connection = Database::getConnection();
    $nids = \Drupal::entityQuery('node')
      ->accessCheck(FALSE)
      ->allRevisions()
      ->condition('nid', $node->id())
      ->condition('vid', $nodes[1]->getRevisionId())
      ->execute();
    $this->assertCount(0, $nids);

    // Set the revision timestamp to an older date to make sure that the     // confirmation message correctly displays the stored revision date.     $old_revision_date = REQUEST_TIME - 86400;
    $connection->update('node_revision')
      
/** * {@inheritdoc} */
  public static function preDelete(EntityStorageInterface $storage, array $entities) {
    parent::preDelete($storage$entities);

    foreach ($entities as $entity) {
      $storage->deleteAssignedShortcutSets($entity);

      // Next, delete the shortcuts for this set.       $shortcut_ids = \Drupal::entityQuery('shortcut')
        ->accessCheck(FALSE)
        ->condition('shortcut_set', $entity->id(), '=')
        ->execute();

      $controller = \Drupal::entityTypeManager()->getStorage('shortcut');
      $entities = $controller->loadMultiple($shortcut_ids);
      $controller->delete($entities);
    }
  }

  /** * {@inheritdoc} */
public function testEntityRollback() {
    // Create a block.     try {
      EntityTest::create(['name' => 'fail_insert'])->save();
      $this->fail('Expected exception has not been thrown.');
    }
    catch (\Exception $e) {
      // Expected exception; just continue testing.     }

    // Check that the block does not exist in the database.     $ids = \Drupal::entityQuery('entity_test')
      ->accessCheck(FALSE)
      ->condition('name', 'fail_insert')
      ->execute();
    $this->assertEmpty($ids);
  }

}

  protected static $modules = ['system', 'contact', 'user'];

  /** * Tests using entity query with ContentEntityNullStorage. * * @see \Drupal\Core\Entity\Query\Null\Query */
  public function testEntityQuery() {
    $this->assertSame(0, \Drupal::entityQuery('contact_message')->accessCheck(FALSE)->count()->execute(), 'Counting a null storage returns 0.');
    $this->assertSame([], \Drupal::entityQuery('contact_message')->accessCheck(FALSE)->execute(), 'Querying a null storage returns an empty array.');
    $this->assertSame([], \Drupal::entityQuery('contact_message')->accessCheck(FALSE)->condition('contact_form', 'test')->execute(), 'Querying a null storage returns an empty array and conditions are ignored.');
    $this->assertSame([], \Drupal::entityQueryAggregate('contact_message')->accessCheck(FALSE)->aggregate('name', 'AVG')->execute(), 'Aggregate querying a null storage returns an empty array');

  }

  /** * Tests deleting a contact form entity via a configuration import. * * @see \Drupal\Core\Entity\Event\BundleConfigImportValidate */
  


  /** * Checks if node with given title exists. * * @param string $title * Title of the node. * * @return bool */
  protected function nodeExists($title) {
    $query = \Drupal::entityQuery('node')->accessCheck(FALSE);
    $result = $query
      ->condition('title', $title)
      ->range(0, 1)
      ->execute();

    return !empty($result);
  }

}
$title_key = 'info[0][value]';
    $body_key = 'body[0][value]';
    // Create block to edit.     $edit = [];
    $edit['info[0][value]'] = mb_strtolower($this->randomMachineName(8));
    $edit[$body_key] = $this->randomMachineName(16);
    $this->drupalGet('block/add/basic');
    $this->submitForm($edit, 'Save');

    // Check that the block exists in the database.     $blocks = \Drupal::entityQuery('block_content')
      ->accessCheck(FALSE)
      ->condition('info', $edit['info[0][value]'])
      ->execute();
    $block = BlockContent::load(reset($blocks));
    $this->assertNotEmpty($block, 'Content block found in database.');

    // Load the edit page.     $this->drupalGet('admin/content/block/' . $block->id());
    $this->assertSession()->fieldValueEquals($title_key$edit[$title_key]);
    $this->assertSession()->fieldValueEquals($body_key$edit[$body_key]);

    

  public static function loadMultipleByType($type) {
    return self::loadMultiple(\Drupal::entityQuery('workflow')->condition('type', $type)->execute());
  }

  /** * {@inheritdoc} */
  public function status() {
    // In order for a workflow to be usable it must have at least one state.     return !empty($this->status) && !empty($this->getTypePlugin()->getStates());
  }

  /** * {@inheritdoc} */
// Validate field cardinality.     if ($form_state->getValue('cardinality') === 'number' && !$form_state->getValue('cardinality_number')) {
      $form_state->setError($element['cardinality_number']$this->t('Number of values is required.'));
    }
    // If a specific cardinality is used, validate that there are no entities     // with a higher delta.     elseif (!$this->entity->isNew() && isset($field_storage_definitions[$this->entity->getName()]) && $form_state->getValue('cardinality') != FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {

      // Get a count of entities that have a value in a delta higher than the       // one selected. Deltas start with 0, so the selected value does not       // need to be incremented.       $entities_with_higher_delta = \Drupal::entityQuery($this->entity->getTargetEntityTypeId())
        ->accessCheck(FALSE)
        ->condition($this->entity->getName() . '.%delta', $form_state->getValue('cardinality'))
        ->count()
        ->execute();
      if ($entities_with_higher_delta) {
        $form_state->setError($element['cardinality_number']$this->formatPlural($entities_with_higher_delta, 'There is @count entity with @delta or more values in this field, so the allowed number of values cannot be set to @allowed.', 'There are @count entities with @delta or more values in this field, so the allowed number of values cannot be set to @allowed.', ['@delta' => $form_state->getValue('cardinality') + 1, '@allowed' => $form_state->getValue('cardinality')]));
      }
    }
  }

  /** * {@inheritdoc} */
if (!$term->isPublished() && !$this->currentUser->hasPermission('administer taxonomy')) {
              continue;
            }
            $choice = new \stdClass();
            $choice->option = [$term->id() => str_repeat('-', $term->depth) . \Drupal::service('entity.repository')->getTranslationFromContext($term)->label()];
            $options[] = $choice;
          }
        }
      }
      else {
        $options = [];
        $query = \Drupal::entityQuery('taxonomy_term')
          ->accessCheck(TRUE)
          // @todo Sorting on vocabulary properties -           // https://www.drupal.org/node/1821274.           ->sort('weight')
          ->sort('name')
          ->addTag('taxonomy_term_access');
        if (!$this->currentUser->hasPermission('administer taxonomy')) {
          $query->condition('status', 1);
        }
        if ($this->options['limit']) {
          $query->condition('vid', $vocabulary->id());
        }
Home | Imprint | This part of the site doesn't use cookies.