本文整理汇总了PHP中Drupal::entityManager方法的典型用法代码示例。如果您正苦于以下问题:PHP Drupal::entityManager方法的具体用法?PHP Drupal::entityManager怎么用?PHP Drupal::entityManager使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal
的用法示例。
在下文中一共展示了Drupal::entityManager方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testStorageMethods
/**
* Tests storage methods.
*/
public function testStorageMethods()
{
$entity_type = \Drupal::entityManager()->getDefinition('config_test');
// Test the static extractID() method.
$expected_id = 'test_id';
$config_name = $entity_type->getConfigPrefix() . '.' . $expected_id;
$storage = $this->storage;
$this->assertIdentical($storage::getIDFromConfigName($config_name, $entity_type->getConfigPrefix()), $expected_id);
// Create three entities, two with the same style.
$style = $this->randomMachineName(8);
for ($i = 0; $i < 2; $i++) {
$entity = $this->storage->create(array('id' => $this->randomMachineName(), 'label' => $this->randomString(), 'style' => $style));
$entity->save();
}
$entity = $this->storage->create(array('id' => $this->randomMachineName(), 'label' => $this->randomString(), 'style' => $this->randomMachineName(9)));
$entity->save();
// Ensure that the configuration entity can be loaded by UUID.
$entity_loaded_by_uuid = entity_load_by_uuid($entity_type->id(), $entity->uuid());
if (!$entity_loaded_by_uuid) {
$this->fail(sprintf("Failed to load '%s' entity ID '%s' by UUID '%s'.", $entity_type->id(), $entity->id(), $entity->uuid()));
}
// Compare UUIDs as the objects are not identical since
// $entity->enforceIsNew is FALSE and $entity_loaded_by_uuid->enforceIsNew
// is NULL.
$this->assertIdentical($entity->uuid(), $entity_loaded_by_uuid->uuid());
$entities = $this->storage->loadByProperties();
$this->assertEqual(count($entities), 3, 'Three entities are loaded when no properties are specified.');
$entities = $this->storage->loadByProperties(array('style' => $style));
$this->assertEqual(count($entities), 2, 'Two entities are loaded when the style property is specified.');
// Assert that both returned entities have a matching style property.
foreach ($entities as $entity) {
$this->assertIdentical($entity->get('style'), $style, 'The loaded entity has the correct style value specified.');
}
}
示例2: validateStub
/**
* Perform validation on a stub entity.
*
* @param string $entity_type_id
* The entity type we are stubbing.
* @param string $entity_id
* ID of the stubbed entity to validate.
*
* @return \Drupal\Core\Entity\EntityConstraintViolationListInterface
* List of constraint violations identified.
*/
protected function validateStub($entity_type_id, $entity_id)
{
$controller = \Drupal::entityManager()->getStorage($entity_type_id);
/** @var \Drupal\Core\Entity\ContentEntityInterface $stub_entity */
$stub_entity = $controller->load($entity_id);
return $stub_entity->validate();
}
示例3: buildOptionsForm
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state)
{
parent::buildOptionsForm($form, $form_state);
$form['grid_style'] = array('#prefix' => '<h4>Grid Settings</h4>', '#type' => 'select', '#title' => t('Mode'), '#description' => t('Choose grid style:'), '#options' => array('classic' => t('Classic Grid'), 'masonry' => t('Masonry Simple'), 'masonry_resize' => t('Masonry Resize')), '#default_value' => $this->options['grid_style'], '#attributes' => array('class' => array('grid-style')));
$field_options = array();
$fields = \Drupal::entityManager()->getFieldMapByFieldType('image');
foreach ($fields as $field) {
foreach ($field as $key => $value) {
$field_options[$key] = $key;
}
}
$form['masonry_background'] = array('#type' => 'select', '#title' => t('Image'), '#options' => $field_options, '#default_value' => $this->options['masonry_background'], '#states' => array('visible' => array('.grid-style' => array('value' => 'masonry_resize'))));
$form['grid_ratio'] = array('#type' => 'textfield', '#title' => t('Ratio'), '#description' => t('The ratio image'), '#default_value' => $this->options['grid_ratio'], '#states' => array('visible' => array('.grid-style' => array('value' => 'masonry_resize'))));
$form['grid_cols_lg'] = array('#type' => 'select', '#title' => t('Large Desktop Items'), '#description' => t('Number of items on large desktop'), '#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 7, 8 => 8, 9 => 9, 10 => 10, 11 => 11, 12 => 12), '#default_value' => $this->options['grid_cols_lg']);
$form['grid_cols_md'] = array('#type' => 'select', '#title' => t('Desktop Items'), '#description' => t('Number of items on desktop'), '#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 7, 8 => 8, 9 => 9, 10 => 10, 11 => 11, 12 => 12), '#default_value' => $this->options['grid_cols_md']);
$form['grid_cols_sm'] = array('#type' => 'select', '#title' => t('Tablet Items'), '#description' => t('Number of items on tablet'), '#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 7, 8 => 8, 9 => 9, 10 => 10, 11 => 11, 12 => 12), '#default_value' => $this->options['grid_cols_sm']);
$form['grid_cols_xs'] = array('#type' => 'select', '#title' => t('Phone Items'), '#description' => t('Number of items on phone'), '#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 7, 8 => 8, 9 => 9, 10 => 10, 11 => 11, 12 => 12), '#default_value' => $this->options['grid_cols_xs']);
$form['grid_margin'] = array('#type' => 'textfield', '#title' => t('Margin'), '#description' => t('The spacing beetween items'), '#default_value' => $this->options['grid_margin'], '#field_suffix' => 'px');
$form['grid_filter'] = array('#type' => 'select', '#title' => t('Use Filter'), '#options' => array(0 => t('No'), 1 => t('Yes')), '#description' => t('Filter items by taxonomy term'), '#default_value' => $this->options['grid_filter'], '#attributes' => array('class' => array('grid-filter-option')));
$categories = array();
$categories['select'] = t('Select');
foreach (Vocabulary::loadMultiple() as $vocabulary) {
$categories[$vocabulary->id()] = $vocabulary->get('name');
}
$form['grid_filter_vocabulary'] = array('#type' => 'select', '#title' => t('Filter Vocabulary'), '#options' => $categories, '#description' => t('Which taxonomy vocabulary do you want to use for the filter'), '#default_value' => $this->options['grid_filter_vocabulary'], '#states' => array('visible' => array('.grid-filter-option' => array('value' => 1))));
}
示例4: testUpdateHookN
/**
* Tests that local actions/tasks are being converted into blocks.
*/
public function testUpdateHookN()
{
$this->runUpdates();
/** @var \Drupal\block\BlockInterface $block_storage */
$block_storage = \Drupal::entityManager()->getStorage('block');
/* @var \Drupal\block\BlockInterface[] $help_blocks */
$help_blocks = $block_storage->loadByProperties(['theme' => 'bartik', 'region' => 'help']);
$this->assertRaw('Because your site has custom theme(s) installed, we had to set local actions and tasks blocks into the content region. Please manually review the block configurations and remove the removed variables from your templates.');
// Disable maintenance mode.
// @todo Can be removed once maintenance mode is automatically turned off
// after updates in https://www.drupal.org/node/2435135.
\Drupal::state()->set('system.maintenance_mode', FALSE);
// We finished updating so we can log in the user now.
$this->drupalLogin($this->rootUser);
$page = Node::create(['type' => 'page', 'title' => 'Page node']);
$page->save();
// Ensures that blocks inside help region has been moved to content region.
foreach ($help_blocks as $block) {
$new_block = $block_storage->load($block->id());
$this->assertEqual($new_block->getRegion(), 'content');
}
// Local tasks are visible on the node page.
$this->drupalGet('node/' . $page->id());
$this->assertText(t('Edit'));
// Local actions are visible on the content listing page.
$this->drupalGet('admin/content');
$action_link = $this->cssSelect('.action-links');
$this->assertTrue($action_link);
$this->drupalGet('admin/structure/block/list/seven');
/** @var \Drupal\Core\Config\StorageInterface $config_storage */
$config_storage = \Drupal::service('config.storage');
$this->assertTrue($config_storage->exists('block.block.test_theme_local_tasks'), 'Local task block has been created for the custom theme.');
$this->assertTrue($config_storage->exists('block.block.test_theme_local_actions'), 'Local action block has been created for the custom theme.');
}
示例5: testTermRevisionNode
/**
* Tests the Drupal 6 term-node revision association to Drupal 8 migration.
*/
public function testTermRevisionNode()
{
$node = \Drupal::entityManager()->getStorage('node')->loadRevision(2);
$this->assertIdentical(2, count($node->vocabulary_3_i_2_));
$this->assertIdentical('4', $node->vocabulary_3_i_2_[0]->target_id);
$this->assertIdentical('5', $node->vocabulary_3_i_2_[1]->target_id);
}
示例6: getOverviewRouteInfo
/**
* Returns the route info for the field overview of a given entity bundle.
*
* @param string $entity_type_id
* An entity type.
* @param string $bundle
* The entity bundle.
*
* @return \Drupal\Core\Url
* A URL object.
*/
public static function getOverviewRouteInfo($entity_type_id, $bundle)
{
$entity_type = \Drupal::entityManager()->getDefinition($entity_type_id);
if ($entity_type->get('field_ui_base_route')) {
return new Url("field_ui.overview_{$entity_type_id}", array($entity_type->getBundleEntityType() => $bundle));
}
}
示例7: assertFieldAccess
/**
* Checks views field access for a given entity type and field name.
*
* To use this method, set up an entity of type $entity_type_id, with field
* $field_name. Create an entity instance that contains content $field_content
* in that field.
*
* This method will check that a user with permission can see the content in a
* view, and a user without access permission on that field cannot.
*
* @param string $entity_type_id
* The entity type ID.
* @param string $field_name
* The field name.
* @param string $field_content
* The expected field content.
*/
protected function assertFieldAccess($entity_type_id, $field_name, $field_content)
{
\Drupal::state()->set('views_field_access_test-field', $field_name);
$entity_type = \Drupal::entityManager()->getDefinition($entity_type_id);
$view_id = $this->randomMachineName();
$data_table = $entity_type->getDataTable();
// Use the data table as long as the field is not 'uuid'. This is the only
// column that can only be obtained from the base table.
$base_table = $data_table && $field_name !== 'uuid' ? $data_table : $entity_type->getBaseTable();
$entity = View::create(['id' => $view_id, 'base_table' => $base_table, 'display' => ['default' => ['display_plugin' => 'default', 'id' => 'default', 'display_options' => ['fields' => [$field_name => ['table' => $base_table, 'field' => $field_name, 'id' => $field_name, 'plugin_id' => 'field']]]]]]);
$entity->save();
/** @var \Drupal\Core\Session\AccountSwitcherInterface $account_switcher */
$account_switcher = \Drupal::service('account_switcher');
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = \Drupal::service('renderer');
$account_switcher->switchTo($this->userWithAccess);
$executable = Views::getView($view_id);
$build = $executable->preview();
$this->setRawContent($renderer->renderRoot($build));
$this->assertText($field_content);
$this->assertTrue(isset($executable->field[$field_name]));
$account_switcher->switchTo($this->userWithoutAccess);
$executable = Views::getView($view_id);
$build = $executable->preview();
$this->setRawContent($renderer->renderRoot($build));
$this->assertNoText($field_content);
$this->assertFalse(isset($executable->field[$field_name]));
\Drupal::state()->delete('views_field_access_test-field');
}
示例8: testPrintLinkExists
/**
* Tests that the links are rendered correctly in the page.
*/
public function testPrintLinkExists()
{
$this->drupalGet('admin/config/user-interface/printable/links');
$this->assertResponse(200);
// Enable the print link in content area.
$this->drupalPostForm(NULL, array('print_print_link_pos' => 'node'), t('Submit'));
$this->drupalGet('admin/config/user-interface/printable/pdf');
$this->assertResponse(200);
$node_type_storage = \Drupal::entityManager()->getStorage('node_type');
// Test /node/add page with only one content type.
$node_type_storage->load('article')->delete();
$this->drupalGet('node/add');
// Create a node.
$edit = array();
$edit['title[0][value]'] = $this->randomMachineName(8);
$edit['body[0][value]'] = $this->randomMachineName(16);
$this->drupalPostForm('node/add/page', $edit, t('Save'));
// Check that the Basic page has been created.
$this->assertRaw(t('!post %title has been created.', array('!post' => 'Basic page', '%title' => $edit['title[0][value]'])), 'Basic page created.');
// Check that the node exists in the database.
$node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
$this->assertTrue($node, 'Node found in database.');
// Verify that pages do not show submitted information by default.
$this->drupalGet('node/' . $node->id());
$this->assertResponse(200);
$this->assertRaw('Print', 'Print link discovered successfully in the printable page');
}
示例9: init
/**
* Overrides \Drupal\views\Plugin\views\argument\ArgumentPluginBase::init().
*/
public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL)
{
parent::init($view, $display, $options);
$field_storage_definitions = \Drupal::entityManager()->getFieldStorageDefinitions($this->definition['entity_type']);
$field_storage = $field_storage_definitions[$this->definition['field_name']];
$this->allowed_values = options_allowed_values($field_storage);
}
示例10: testViewAdd
/**
* Tests creating a node revision view.
*/
public function testViewAdd()
{
$this->drupalCreateContentType(array('type' => 'article'));
// Create two nodes with two revision.
$node_storage = \Drupal::entityManager()->getStorage('node');
/** @var \Drupal\node\NodeInterface $node */
$node = $node_storage->create(array('title' => $this->randomString(), 'type' => 'article', 'created' => REQUEST_TIME + 40));
$node->save();
$node = $node->createDuplicate();
$node->setNewRevision();
$node->created->value = REQUEST_TIME + 20;
$node->save();
$node = $node_storage->create(array('title' => $this->randomString(), 'type' => 'article', 'created' => REQUEST_TIME + 30));
$node->save();
$node = $node->createDuplicate();
$node->setNewRevision();
$node->created->value = REQUEST_TIME + 10;
$node->save();
$view = array();
$view['label'] = $this->randomMachineName(16);
$view['id'] = strtolower($this->randomMachineName(16));
$view['description'] = $this->randomMachineName(16);
$view['page[create]'] = FALSE;
$view['show[wizard_key]'] = 'node_revision';
$this->drupalPostForm('admin/structure/views/add', $view, t('Save and edit'));
$view_storage_controller = \Drupal::entityManager()->getStorage('view');
/** @var \Drupal\views\Entity\View $view */
$view = $view_storage_controller->load($view['id']);
$this->assertEqual($view->get('base_table'), 'node_field_revision');
$executable = Views::executableFactory()->get($view);
$this->executeView($executable);
$this->assertIdenticalResultset($executable, array(array('vid' => 1), array('vid' => 3), array('vid' => 2), array('vid' => 4)), array('vid' => 'vid'));
}
示例11: preRender
public function preRender(&$values)
{
$vocabularies = entity_load_multiple('taxonomy_vocabulary');
$this->field_alias = $this->aliases['nid'];
$nids = array();
foreach ($values as $result) {
if (!empty($result->{$this->aliases['nid']})) {
$nids[] = $result->{$this->aliases['nid']};
}
}
if ($nids) {
$vocabs = array_filter($this->options['vids']);
if (empty($this->options['limit'])) {
$vocabs = array();
}
$result = \Drupal::entityManager()->getStorage('taxonomy_term')->getNodeTerms($nids, $vocabs);
foreach ($result as $node_nid => $data) {
foreach ($data as $tid => $term) {
$this->items[$node_nid][$tid]['name'] = \Drupal::entityManager()->getTranslationFromContext($term)->label();
$this->items[$node_nid][$tid]['tid'] = $tid;
$this->items[$node_nid][$tid]['vocabulary_vid'] = $term->getVocabularyId();
$this->items[$node_nid][$tid]['vocabulary'] = String::checkPlain($vocabularies[$term->getVocabularyId()]->label());
if (!empty($this->options['link_to_taxonomy'])) {
$this->items[$node_nid][$tid]['make_link'] = TRUE;
$this->items[$node_nid][$tid]['path'] = 'taxonomy/term/' . $tid;
}
}
}
}
}
示例12: buildOptionsForm
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state)
{
parent::buildOptionsForm($form, $form_state);
$form['view_mode'] = array('#type' => 'select', '#options' => \Drupal::entityManager()->getViewModeOptions($this->entityType), '#title' => t('View mode'), '#default_value' => $this->options['view_mode']);
$form['entity_id'] = array('#title' => t('ID'), '#type' => 'textfield', '#default_value' => $this->options['entity_id']);
$form['bypass_access'] = array('#type' => 'checkbox', '#title' => t('Bypass access checks'), '#description' => t('If enabled, access permissions for rendering the entity are not checked.'), '#default_value' => !empty($this->options['bypass_access']));
}
示例13: testConfigurationRename
/**
* Tests configuration renaming.
*/
public function testConfigurationRename()
{
$content_type = entity_create('node_type', array('type' => Unicode::strtolower($this->randomName(16)), 'name' => $this->randomName()));
$content_type->save();
$staged_type = $content_type->type;
$active = $this->container->get('config.storage');
$staging = $this->container->get('config.storage.staging');
$config_name = $content_type->getEntityType()->getConfigPrefix() . '.' . $content_type->id();
// Emulate a staging operation.
$this->copyConfig($active, $staging);
// Change the machine name of the content type.
$content_type->type = Unicode::strtolower($this->randomName(8));
$content_type->save();
$active_type = $content_type->type;
$renamed_config_name = $content_type->getEntityType()->getConfigPrefix() . '.' . $content_type->id();
$this->assertTrue($active->exists($renamed_config_name), 'The content type has the new name in the active store.');
$this->assertFalse($active->exists($config_name), "The content type's old name does not exist active store.");
$this->configImporter()->reset();
$this->assertEqual(0, count($this->configImporter()->getUnprocessedConfiguration('create')), 'There are no configuration items to create.');
$this->assertEqual(0, count($this->configImporter()->getUnprocessedConfiguration('delete')), 'There are no configuration items to delete.');
$this->assertEqual(0, count($this->configImporter()->getUnprocessedConfiguration('update')), 'There are no configuration items to update.');
// We expect that changing the machine name of the content type will
// rename five configuration entities: the node type, the body field
// instance, two entity form displays, and the entity view display.
// @see \Drupal\node\Entity\NodeType::postSave()
$expected = array('node.type.' . $active_type . '::node.type.' . $staged_type, 'entity.form_display.node.' . $active_type . '.default::entity.form_display.node.' . $staged_type . '.default', 'entity.view_display.node.' . $active_type . '.default::entity.view_display.node.' . $staged_type . '.default', 'entity.view_display.node.' . $active_type . '.teaser::entity.view_display.node.' . $staged_type . '.teaser', 'field.instance.node.' . $active_type . '.body::field.instance.node.' . $staged_type . '.body');
$renames = $this->configImporter()->getUnprocessedConfiguration('rename');
$this->assertIdentical($expected, $renames);
$this->drupalGet('admin/config/development/configuration');
foreach ($expected as $rename) {
$names = $this->configImporter()->getStorageComparer()->extractRenameNames($rename);
$this->assertText(String::format('!source_name to !target_name', array('!source_name' => $names['old_name'], '!target_name' => $names['new_name'])));
// Test that the diff link is present for each renamed item.
$href = \Drupal::urlGenerator()->getPathFromRoute('config.diff', array('source_name' => $names['old_name'], 'target_name' => $names['new_name']));
$this->assertLinkByHref($href);
$hrefs[$rename] = $href;
}
// Ensure that the diff works for each renamed item.
foreach ($hrefs as $rename => $href) {
$this->drupalGet($href);
$names = $this->configImporter()->getStorageComparer()->extractRenameNames($rename);
$config_entity_type = \Drupal::service('config.manager')->getEntityTypeIdByName($names['old_name']);
$entity_type = \Drupal::entityManager()->getDefinition($config_entity_type);
$old_id = ConfigEntityStorage::getIDFromConfigName($names['old_name'], $entity_type->getConfigPrefix());
$new_id = ConfigEntityStorage::getIDFromConfigName($names['new_name'], $entity_type->getConfigPrefix());
// Because table columns can be on multiple lines, need to assert a regex
// pattern rather than normal text.
$id_key = $entity_type->getKey('id');
$text = "{$id_key}: {$old_id}";
$this->assertTextPattern('/\\-\\s+' . preg_quote($text, '/') . '/', "'-{$text}' found.");
$text = "{$id_key}: {$new_id}";
$this->assertTextPattern('/\\+\\s+' . preg_quote($text, '/') . '/', "'+{$text}' found.");
}
// Run the import.
$this->drupalPostForm('admin/config/development/configuration', array(), t('Import all'));
$this->assertText(t('There are no configuration changes.'));
$this->assertFalse(entity_load('node_type', $active_type), 'The content no longer exists with the old name.');
$content_type = entity_load('node_type', $staged_type);
$this->assertIdentical($staged_type, $content_type->type);
}
示例14: createTestViews
/**
* Create test views from config.
*
* @param string $class
* The name of the test class. Installs the listed test views *in order*.
* @param array $modules
* The module directories to look in for test views.
*/
public static function createTestViews($class, array $modules)
{
$views = array();
while ($class) {
if (property_exists($class, 'testViews')) {
$views = array_merge($views, $class::$testViews);
}
$class = get_parent_class($class);
}
if (!empty($views)) {
$storage = \Drupal::entityManager()->getStorage('view');
$module_handler = \Drupal::moduleHandler();
foreach ($modules as $module) {
$config_dir = drupal_get_path('module', $module) . '/test_views';
if (!is_dir($config_dir) || !$module_handler->moduleExists($module)) {
continue;
}
$file_storage = new FileStorage($config_dir);
$available_views = $file_storage->listAll('views.view.');
foreach ($views as $id) {
$config_name = 'views.view.' . $id;
if (in_array($config_name, $available_views)) {
$storage->create($file_storage->read($config_name))->save();
}
}
}
}
// Rebuild the router once.
\Drupal::service('router.builder')->rebuild();
}
示例15: validate
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint)
{
/* @var \Drupal\Core\Field\FieldItemInterface $value */
if (!isset($value)) {
return;
}
$id = $value->target_id;
// '0' or NULL are considered valid empty references.
if (empty($id)) {
return;
}
/* @var \Drupal\Core\Entity\FieldableEntityInterface $referenced_entity */
$referenced_entity = $value->entity;
if ($referenced_entity) {
$entity = $value->getEntity();
$check_permission = TRUE;
if (!$entity->isNew()) {
$existing_entity = \Drupal::entityManager()->getStorage($entity->getEntityTypeId())->loadUnchanged($entity->id());
$referenced_entities = $existing_entity->{$value->getFieldDefinition()->getName()}->referencedEntities();
// Check permission if we are not already referencing the entity.
foreach ($referenced_entities as $ref) {
if (isset($referenced_entities[$ref->id()])) {
$check_permission = FALSE;
break;
}
}
}
// We check that the current user had access to view any newly added
// referenced entity.
if ($check_permission && !$referenced_entity->access('view')) {
$type = $value->getFieldDefinition()->getSetting('target_type');
$this->context->addViolation($constraint->message, array('%type' => $type, '%id' => $id));
}
}
}