本文整理汇总了PHP中Drupal::entityQuery方法的典型用法代码示例。如果您正苦于以下问题:PHP Drupal::entityQuery方法的具体用法?PHP Drupal::entityQuery怎么用?PHP Drupal::entityQuery使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal
的用法示例。
在下文中一共展示了Drupal::entityQuery方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: load
/**
* {@inheritdoc}
*/
public function load()
{
// It is not possible to use the standard load method, because this needs
// all field instance entities only for the given baseEntityType.
$ids = \Drupal::entityQuery('field_instance_config')->condition('id', $this->baseEntityType . '.', 'STARTS_WITH')->execute();
return $this->storage->loadMultiple($ids);
}
示例2: testAddProductAdmin
/**
* Tests creating a product via the admin.
*/
function testAddProductAdmin()
{
$title = $this->randomMachineName();
$store_ids = array_map(function ($store) {
return $store->id();
}, $this->stores);
$this->drupalGet('admin/commerce/products');
$this->clickLink('Add product');
$product_variation_values = ['variations[form][inline_entity_form][sku][0][value]' => $this->randomMachineName(), 'variations[form][inline_entity_form][status][value]' => 1];
$this->drupalPostForm(NULL, $product_variation_values, t('Create variation'));
$edit = ['title[0][value]' => $title];
foreach ($store_ids as $store_id) {
$edit['stores[target_id][value][' . $store_id . ']'] = $store_id;
}
$this->drupalPostForm(NULL, $edit, t('Save and publish'));
$result = \Drupal::entityQuery('commerce_product')->condition("title", $edit['title[0][value]'])->range(0, 1)->execute();
$product_id = reset($result);
$product = Product::load($product_id);
$this->assertNotNull($product, 'The new product has been created in the database.');
$this->assertText(t('The product @title has been successfully saved', ['@title' => $title]), 'Product success text is shown');
$this->assertText($title, 'Created product name exists on this page.');
$this->assertFieldValues($product->getStores(), $this->stores, 'Created product has the correct associated stores.');
$this->assertFieldValues($product->getStoreIds(), $store_ids, 'Created product has the correct associated store ids.');
// Assert that the frontend product page is displaying.
$this->drupalGet('product/' . $product->id());
$this->assertResponse(200);
$this->assertText($product->getTitle(), 'Product title exists');
// Test product variations
$product_variation = \Drupal::entityQuery('commerce_product_variation')->condition("sku", $product_variation_values['variations[form][inline_entity_form][sku][0][value]'])->range(0, 1)->execute();
$product_variation = ProductVariation::load(current($product_variation));
$this->assertNotNull($product_variation, 'The new product variation has been created in the database.');
}
示例3: build
/**
* {@inheritdoc}
*/
public function build()
{
$query = \Drupal::entityQuery('node')->condition('status', 1)->condition('type', 'team_member')->sort('field_order', 'ASC');
$nids = $query->execute();
$nodes = node_load_multiple($nids);
//$nodes = entity_load_multiple('node', $nids);
$ind = 1;
$output = '<div class="tabbable tabs-left tabcordion">
<ul class="nav nav-tabs">';
foreach ($nodes as $node) {
$class = $ind == 1 ? 'active' : '';
$output .= '<li class="' . $class . '"><a data-target="#team_member_tab' . $ind . '" data-toggle="tab">' . $node->title->value . '<span>' . $node->get('field_designation')->value . '</span></a></li>';
$ind++;
}
$ind = 1;
$output .= '</ul>
<div class="tab-content">';
foreach ($nodes as $node) {
$class = $ind == 1 ? 'active' : '';
if (is_object($node->field_image->entity)) {
$path = $node->field_image->entity->getFileUri();
$url = ImageStyle::load('person_picture')->buildUrl($path);
$tab_content_html = '<div class="row"><div class="col-md-3"><img src="' . $url . '" alt=""></div><div class="col-md-9">' . $node->get('body')->value . '</div> </div>';
} else {
$tab_content_html = '<div>' . $node->get('body')->value . '</div>';
}
$output .= '<div class="tab-pane ' . $class . '" id="team_member_tab' . $ind . '"> ' . $tab_content_html . ' </div>';
$ind++;
}
$output .= '</div>
</div>';
return array('#type' => 'markup', '#markup' => $output, '#attached' => array('library' => array('barney_river_utilities/tabcordion', 'barney_river_utilities/tabcordion_hook')));
}
示例4: validate
/**
* {@inheritdoc}
*/
public function validate($items, Constraint $constraint)
{
$bundles = $constraint->bundles;
if (!($item = $items->first())) {
return;
}
$field_name = $items->getFieldDefinition()->getName();
/** @var \Drupal\Core\Entity\EntityInterface $entity */
$entity = $items->getEntity();
$bundle = $entity->bundle();
if (!in_array($bundle, $bundles)) {
// The constraint does not apply to this bundle.
return;
}
$bundle_key = $entity->getEntityType()->getKey('bundle');
$entity_type_id = $entity->getEntityTypeId();
$id_key = $entity->getEntityType()->getKey('id');
$query = \Drupal::entityQuery($entity_type_id)->condition($field_name, $item->value)->condition($bundle_key, $bundles, 'IN');
if (!empty($entity->id())) {
$query->condition($id_key, $items->getEntity()->id(), '<>');
}
$value_taken = (bool) $query->range(0, 1)->count()->execute();
if ($value_taken) {
$this->context->addViolation($constraint->message, ['%value' => $item->value, '@entity_type' => $entity->getEntityType()->getLowercaseLabel(), '@field_name' => Unicode::strtolower($items->getFieldDefinition()->getLabel())]);
}
}
示例5: listItems
/**
* Lists the feed items belonging to a feed.
*/
public function listItems(FeedInterface $feeds_feed, Request $request)
{
$processor = $feeds_feed->getType()->getProcessor();
$header = ['title' => $this->t('Label'), 'imported' => $this->t('Imported'), 'guid' => ['data' => $this->t('GUID'), 'class' => [RESPONSIVE_PRIORITY_LOW]], 'url' => ['data' => $this->t('URL'), 'class' => [RESPONSIVE_PRIORITY_LOW]]];
$build = [];
$build['table'] = ['#type' => 'table', '#header' => $header, '#rows' => [], '#empty' => $this->t('There are no items yet.')];
// @todo Allow processors to create their own entity listings.
if (!$processor instanceof EntityProcessorInterface) {
return $build;
}
$entity_ids = \Drupal::entityQuery($processor->entityType())->condition('feeds_item.target_id', $feeds_feed->id())->pager(50)->sort('feeds_item.imported', 'DESC')->execute();
$storage = $this->entityManager()->getStorage($processor->entityType());
foreach ($storage->loadMultiple($entity_ids) as $entity) {
$ago = \Drupal::service('date.formatter')->formatInterval(REQUEST_TIME - $entity->get('feeds_item')->imported);
$row = [];
// Entity link.
$row[] = ['data' => $entity->link(Unicode::truncate($entity->label(), 75, TRUE, TRUE)), 'title' => $entity->label()];
// Imported ago.
$row[] = $this->t('@time ago', ['@time' => $ago]);
// Item GUID.
$row[] = ['data' => SafeMarkup::checkPlain(Unicode::truncate($entity->get('feeds_item')->guid, 30, FALSE, TRUE)), 'title' => $entity->get('feeds_item')->guid];
// Item URL.
$row[] = ['data' => SafeMarkup::checkPlain(Unicode::truncate($entity->get('feeds_item')->url, 30, FALSE, TRUE)), 'title' => $entity->get('feeds_item')->url];
$build['table']['#rows'][] = $row;
}
$build['pager'] = ['#type' => 'pager'];
$build['#title'] = $this->t('%title items', ['%title' => $feeds_feed->label()]);
return $build;
}
示例6: removeFields
/**
* Removes Simplenews fields.
*/
public static function removeFields()
{
$simplenews_fields_ids = \Drupal::entityQuery('field_config')->condition('field_type', 'simplenews_', 'STARTS_WITH')->execute();
$simplenews_fields = \Drupal::entityManager()->getStorage('field_config')->loadMultiple($simplenews_fields_ids);
$field_config_storage = \Drupal::entityManager()->getStorage('field_config');
$field_config_storage->delete($simplenews_fields);
}
示例7: collectRenderDisplay
/**
* Returns the entity_form_display object used to build an entity form.
*
* Depending on the configuration of the form mode for the entity bundle, this
* can be either the display object associated with the form mode, or the
* 'default' display.
*
* This method should only be used internally when rendering an entity form.
* When assigning suggested display options for a component in a given form
* mode, entity_get_form_display() should be used instead, in order to avoid
* inadvertently modifying the output of other form modes that might happen to
* use the 'default' display too. Those options will then be effectively
* applied only if the form mode is configured to use them.
*
* hook_entity_form_display_alter() is invoked on each display, allowing 3rd
* party code to alter the display options held in the display before they are
* used to generate render arrays.
*
* @param \Drupal\Core\Entity\FieldableEntityInterface $entity
* The entity for which the form is being built.
* @param string $form_mode
* The form mode.
*
* @return \Drupal\Core\Entity\Display\EntityFormDisplayInterface
* The display object that should be used to build the entity form.
*
* @see entity_get_form_display()
* @see hook_entity_form_display_alter()
*/
public static function collectRenderDisplay(FieldableEntityInterface $entity, $form_mode)
{
$entity_type = $entity->getEntityTypeId();
$bundle = $entity->bundle();
// Check the existence and status of:
// - the display for the form mode,
// - the 'default' display.
if ($form_mode != 'default') {
$candidate_ids[] = $entity_type . '.' . $bundle . '.' . $form_mode;
}
$candidate_ids[] = $entity_type . '.' . $bundle . '.default';
$results = \Drupal::entityQuery('entity_form_display')->condition('id', $candidate_ids)->condition('status', TRUE)->execute();
// Load the first valid candidate display, if any.
$storage = \Drupal::entityManager()->getStorage('entity_form_display');
foreach ($candidate_ids as $candidate_id) {
if (isset($results[$candidate_id])) {
$display = $storage->load($candidate_id);
break;
}
}
// Else create a fresh runtime object.
if (empty($display)) {
$display = $storage->create(array('targetEntityType' => $entity_type, 'bundle' => $bundle, 'mode' => $form_mode, 'status' => TRUE));
}
// Let the display know which form mode was originally requested.
$display->originalMode = $form_mode;
// Let modules alter the display.
$display_context = array('entity_type' => $entity_type, 'bundle' => $bundle, 'form_mode' => $form_mode);
\Drupal::moduleHandler()->alter('entity_form_display', $display, $display_context);
return $display;
}
示例8: rollback
/**
* Rolls back the configured migrations.
*/
public function rollback()
{
static::$messages = new DrushLogMigrateMessage();
$query = \Drupal::entityQuery('migration');
$names = $query->execute();
// Order the migrations according to their dependencies.
/** @var MigrationInterface[] $migrations */
$migrations = \Drupal::entityManager()->getStorage('migration')->loadMultiple($names);
// Assume we want all those tagged 'Drupal %'.
foreach ($migrations as $migration_id => $migration) {
$keep = FALSE;
$tags = $migration->get('migration_tags');
foreach ($tags as $tag) {
if (strpos($tag, 'Drupal ') === 0) {
$keep = TRUE;
break;
}
}
if (!$keep) {
unset($migrations[$migration_id]);
}
}
// Roll back in reverse order.
$this->migrationList = array_reverse($migrations);
foreach ($this->migrationList as $migration_id => $migration) {
drush_print(dt('Rolling back @migration', ['@migration' => $migration_id]));
$executable = new MigrateExecutable($migration, static::$messages);
// drush_op() provides --simulate support.
drush_op([$executable, 'rollback']);
$migration->delete();
}
}
示例9: loadEntityByLabel
/**
* Load an entity by it's label.
*
* @param string $label
* The label of the entity to load.
* @param string $entity_type
* The entity type to load.
*
* @return \Drupal\Core\Entity\EntityInterface
* A loaded entity.
*/
protected function loadEntityByLabel($label, $entity_type = 'node')
{
$type_manager = \Drupal::entityTypeManager();
$label_key = $type_manager->getDefinition($entity_type)->getKey('label');
$entities = \Drupal::entityQuery($entity_type)->condition($label_key, $label, '=')->execute();
return $type_manager->getStorage($entity_type)->load(array_shift($entities));
}
示例10: testAddressFormatImport
/**
* Test importing address formats using service.
*/
function testAddressFormatImport()
{
$externalRepository = new AddressFormatRepository();
$externalCount = count($externalRepository->getAll());
$count = \Drupal::entityQuery('address_format')->count()->execute();
$this->assertEqual($externalCount, $count, 'All address formats imported at installation.');
}
示例11: content
/**
* {@inheritdoc}
*/
public function content()
{
// Get the list of the reservation node ids.
$storage = \Drupal::entityManager()->getStorage('node');
$reserved_list = \Drupal::entityQuery('node')->condition('status', 1)->condition('type', 'balagan_reservation')->condition('field_balagan_reserv_accom', 'NULL', '<>')->condition('field_balagan_reserv_customer', 'NULL', '<>')->execute();
$reserved_accom = array();
$build = array();
foreach ($reserved_list as $nid) {
$reserved_accom[] = $storage->load($nid)->field_balagan_reserv_accom->getValue()[0]['target_id'];
}
if (!empty($reserved_accom)) {
$accommodations = \Drupal::entityQuery('node')->condition('status', 1)->condition('type', 'balagan_accommodation')->condition('nid', $reserved_accom, 'NOT IN')->execute();
foreach ($accommodations as $item) {
$node = node_load($item);
$locality = $node->field_balagan_accom_address->getValue()[0]['locality'];
$start = $node->field_balagan_accom_date->getValue()[0]['value'];
$end = $node->field_balagan_accom_date->getValue()[1]['value'];
$people = $node->field_balagan_accom_people->getValue()[0]['value'];
$link = $node->toLink()->toRenderable();
$build[] = $link;
$build[] = array('markup' => array('#type' => 'markup', '#markup' => ' ' . $locality . ' ' . $start . ' - ' . $end . ' ' . 'Room for: ' . $people . '<BR>'));
}
}
return $build;
}
示例12: testTaxonomyEfq
/**
* Tests that a basic taxonomy entity query works.
*/
function testTaxonomyEfq()
{
$terms = array();
for ($i = 0; $i < 5; $i++) {
$term = $this->createTerm($this->vocabulary);
$terms[$term->id()] = $term;
}
$result = \Drupal::entityQuery('taxonomy_term')->execute();
sort($result);
$this->assertEqual(array_keys($terms), $result, 'Taxonomy terms were retrieved by entity query.');
$tid = reset($result);
$ids = (object) array('entity_type' => 'taxonomy_term', 'entity_id' => $tid, 'bundle' => $this->vocabulary->id());
$term = _field_create_entity_from_ids($ids);
$this->assertEqual($term->id(), $tid, 'Taxonomy term can be created based on the IDs.');
// Create a second vocabulary and five more terms.
$vocabulary2 = $this->createVocabulary();
$terms2 = array();
for ($i = 0; $i < 5; $i++) {
$term = $this->createTerm($vocabulary2);
$terms2[$term->id()] = $term;
}
$result = \Drupal::entityQuery('taxonomy_term')->condition('vid', $vocabulary2->id())->execute();
sort($result);
$this->assertEqual(array_keys($terms2), $result, format_string('Taxonomy terms from the %name vocabulary were retrieved by entity query.', array('%name' => $vocabulary2->label())));
$tid = reset($result);
$ids = (object) array('entity_type' => 'taxonomy_term', 'entity_id' => $tid, 'bundle' => $vocabulary2->id());
$term = _field_create_entity_from_ids($ids);
$this->assertEqual($term->id(), $tid, 'Taxonomy term can be created based on the IDs.');
}
示例13: checkAccess
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account)
{
/** @var \Drupal\crm_core_contact\Entity\ContactType $entity */
// First check permission.
if (parent::checkAccess($entity, $operation, $account)->isForbidden()) {
return AccessResult::forbidden();
}
switch ($operation) {
case 'enable':
// Only disabled contact type can be enabled.
return AccessResult::allowedIf(!$entity->status());
case 'disable':
return AccessResult::allowedIf($entity->status());
case 'delete':
// If contact instance of this contact type exist, you can't delete it.
$results = \Drupal::entityQuery('crm_core_contact')->condition('type', $entity->id())->execute();
return AccessResult::allowedIf(empty($results));
// @todo Which is it?
// @todo Which is it?
case 'edit':
case 'update':
// If the contact type is locked, you can't edit it.
return AccessResult::allowed();
}
}
示例14: testWidget
/**
* Tests the widget.
*/
protected function testWidget()
{
/** @var \Drupal\currency\ConfigImporterInterface $config_importer */
$config_importer = \Drupal::service('currency.config_importer');
$config_importer->importCurrency('EUR');
$user = $this->drupalCreateUser(['administer user fields']);
$this->drupalLogin($user);
// Test the widget when setting a default field value.
$field_name = strtolower($this->randomMachineName());
$this->drupalPostForm('admin/config/people/accounts/fields/add-field', ['label' => $this->randomString(), 'field_name' => $field_name, 'new_storage_type' => 'payment_form'], t('Save and continue'));
$this->drupalPostForm(NULL, [], t('Save field settings'));
$this->drupalPostForm(NULL, [], t('Add and configure a new line item'));
$this->drupalPostForm(NULL, ['default_value_input[field_' . $field_name . '][line_items][line_items][payment_basic][plugin_form][description]' => $this->randomString()], t('Save settings'));
// Get all payment_form fields.
$field_names = \Drupal::entityQuery('field_storage_config')->condition('type', 'payment_form')->execute();
$this->assertTrue(in_array('user.field_' . $field_name, $field_names));
// Test the widget when creating an entity.
$this->drupalPostForm('user/' . $user->id() . '/edit', ['field_' . $field_name . '[line_items][add_more][type]' => 'payment_basic'], t('Add and configure a new line item'));
$description = $this->randomString();
$this->drupalPostForm(NULL, ['field_' . $field_name . '[line_items][line_items][payment_basic][plugin_form][amount][amount]' => '9,87', 'field_' . $field_name . '[line_items][line_items][payment_basic][plugin_form][amount][currency_code]' => 'EUR', 'field_' . $field_name . '[line_items][line_items][payment_basic][plugin_form][description]' => $description, 'field_' . $field_name . '[line_items][line_items][payment_basic][plugin_form][quantity]' => 37], t('Save'));
// Test whether the widget displays field values.
$this->drupalGet('user/' . $user->id() . '/edit');
$this->assertFieldByName('field_' . $field_name . '[line_items][line_items][payment_basic][plugin_form][amount][amount]', '9.87');
$this->assertFieldByName('field_' . $field_name . '[line_items][line_items][payment_basic][plugin_form][amount][currency_code]', 'EUR');
$this->assertFieldByName('field_' . $field_name . '[line_items][line_items][payment_basic][plugin_form][description]', $description);
$this->assertFieldByName('field_' . $field_name . '[line_items][line_items][payment_basic][plugin_form][quantity]', 37);
}
示例15: testAutoCreate
/**
* Tests that the autocomplete input element appears and the creation of a new
* entity.
*/
public function testAutoCreate()
{
$this->drupalGet('node/add/' . $this->referencingType);
$this->assertFieldByXPath('//input[@id="edit-test-field-0-target-id" and contains(@class, "form-autocomplete")]', NULL, 'The autocomplete input element appears.');
$new_title = $this->randomMachineName();
// Assert referenced node does not exist.
$base_query = \Drupal::entityQuery('node');
$base_query->condition('type', $this->referencedType)->condition('title', $new_title);
$query = clone $base_query;
$result = $query->execute();
$this->assertFalse($result, 'Referenced node does not exist yet.');
$edit = array('title[0][value]' => $this->randomMachineName(), 'test_field[0][target_id]' => $new_title);
$this->drupalPostForm("node/add/{$this->referencingType}", $edit, 'Save');
// Assert referenced node was created.
$query = clone $base_query;
$result = $query->execute();
$this->assertTrue($result, 'Referenced node was created.');
$referenced_nid = key($result);
$referenced_node = Node::load($referenced_nid);
// Assert the referenced node is associated with referencing node.
$result = \Drupal::entityQuery('node')->condition('type', $this->referencingType)->execute();
$referencing_nid = key($result);
$referencing_node = Node::load($referencing_nid);
$this->assertEqual($referenced_nid, $referencing_node->test_field->target_id, 'Newly created node is referenced from the referencing node.');
// Now try to view the node and check that the referenced node is shown.
$this->drupalGet('node/' . $referencing_node->id());
$this->assertText($referencing_node->label(), 'Referencing node label found.');
$this->assertText($referenced_node->label(), 'Referenced node label found.');
}