/** * 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.'); } }
/** * 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(); }
/** * {@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)))); }
/** * 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.'); }
/** * 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); }
/** * 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)); } }
/** * 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'); }
/** * 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'); }
/** * 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); }
/** * 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')); }
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; } } } } }
/** * {@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'])); }
/** * 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); }
/** * 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(); }
/** * {@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)); } } }
/** * Test some of the methods. */ public function testMessageMethods() { $message_storage = $this->container->get('entity.manager')->getStorage('contact_message'); $message = $message_storage->create(array('contact_form' => 'feedback')); // Check for empty values first. $this->assertEqual($message->getMessage(), ''); $this->assertEqual($message->getSenderName(), ''); $this->assertEqual($message->getSenderMail(), ''); $this->assertFalse($message->copySender()); // Check for default values. $this->assertEqual('feedback', $message->getContactForm()->id()); $this->assertFalse($message->isPersonal()); // Set some values and check for them afterwards. $message->setMessage('welcome_message'); $message->setSenderName('sender_name'); $message->setSenderMail('sender_mail'); $message->setCopySender(TRUE); $this->assertEqual($message->getMessage(), 'welcome_message'); $this->assertEqual($message->getSenderName(), 'sender_name'); $this->assertEqual($message->getSenderMail(), 'sender_mail'); $this->assertTrue($message->copySender()); $no_access_user = $this->createUser(['uid' => 2]); $access_user = $this->createUser(['uid' => 3], ['access site-wide contact form']); $admin = $this->createUser(['uid' => 4], ['administer contact forms']); $this->assertFalse(\Drupal::entityManager()->getAccessControlHandler('contact_message')->createAccess(NULL, $no_access_user)); $this->assertTrue(\Drupal::entityManager()->getAccessControlHandler('contact_message')->createAccess(NULL, $access_user)); $this->assertTrue($message->access('edit', $admin)); $this->assertFalse($message->access('edit', $access_user)); }
/** * Creates a "ticket" support_ticket and verifies its consistency in the database. */ function testTicketCreation() { $ticket_type_storage = \Drupal::entityManager()->getStorage('support_ticket_type'); // Test /support_ticket/add page with only one content type. $this->drupalGet('support_ticket/add'); $this->assertResponse(200); $this->assertUrl('support_ticket/add/ticket'); // Create a ticket. $edit = array(); $edit['title[0][value]'] = $this->randomMachineName(8); $edit['body[0][value]'] = $this->randomMachineName(16); $edit['field_priority'] = '120'; // 120 = 'high' $edit['field_state'] = 'inactive'; $this->drupalPostForm('support_ticket/add/ticket', $edit, t('Save')); // Check that the ticket has been created. $this->assertRaw(t('@post %title has been created.', array('@post' => 'Ticket', '%title' => $edit['title[0][value]'])), 'Ticket created.'); // Check that the support_ticket exists in the database. $ticket = $this->supportTicketGetTicketByTitle($edit['title[0][value]']); $this->assertTrue($ticket, 'Ticket found in database.'); // View ticket to test single ticket output. $this->drupalGet('support_ticket/' . $ticket->id()); // Base "Submitted by..." heading. $this->assertText($ticket->getOwner()->getUsername()); $this->assertText(format_date($ticket->getCreatedTime())); // Check field display output for basic ticket fields. $elements = $this->cssSelect("div.field--name-field-priority div.field__item:contains('high')"); $this->assertEqual(count($elements), 1, 'Priority was set correctly.'); $elements = $this->cssSelect("div.field--name-field-state div.field__item:contains('inactive')"); $this->assertEqual(count($elements), 1, 'State was set correctly.'); }
/** * Tests the bubbling of cache tags. */ public function testCacheTags() { // Create the entity that will be commented upon. $commented_entity = entity_create('entity_test', array('name' => $this->randomMachineName())); $commented_entity->save(); // Verify cache tags on the rendered entity before it has comments. $build = \Drupal::entityManager()->getViewBuilder('entity_test')->view($commented_entity); drupal_render($build); $expected_cache_tags = array('entity_test_view', 'entity_test:' . $commented_entity->id(), 'comment_list'); sort($expected_cache_tags); $this->assertEqual($build['#cache']['tags'], $expected_cache_tags, 'The test entity has the expected cache tags before it has comments.'); // Create a comment on that entity. Comment loading requires that the uid // also exists in the {users} table. $user = $this->createUser(); $user->save(); $comment = entity_create('comment', array('subject' => 'Llama', 'comment_body' => array('value' => 'Llamas are cool!', 'format' => 'plain_text'), 'entity_id' => $commented_entity->id(), 'entity_type' => 'entity_test', 'field_name' => 'comment', 'comment_type' => 'comment', 'status' => CommentInterface::PUBLISHED, 'uid' => $user->id())); $comment->save(); // Load commented entity so comment_count gets computed. // @todo Remove the $reset = TRUE parameter after // https://www.drupal.org/node/597236 lands. It's a temporary work-around. $commented_entity = entity_load('entity_test', $commented_entity->id(), TRUE); // Verify cache tags on the rendered entity when it has comments. $build = \Drupal::entityManager()->getViewBuilder('entity_test')->view($commented_entity); drupal_render($build); $expected_cache_tags = array('entity_test_view', 'entity_test:' . $commented_entity->id(), 'comment_list', 'comment_view', 'comment:' . $comment->id(), 'config:filter.format.plain_text', 'user_view', 'user:2'); sort($expected_cache_tags); $this->assertEqual($build['#cache']['tags'], $expected_cache_tags, 'The test entity has the expected cache tags when it has comments.'); }
/** * Tests that default values are correctly translated to UUIDs in config. */ function testEntityReferenceDefaultValue() { // Create a node to be referenced. $referenced_node = $this->drupalCreateNode(array('type' => 'referenced_content')); $field_name = drupal_strtolower($this->randomMachineName()); $field_storage = entity_create('field_storage_config', array('field_name' => $field_name, 'entity_type' => 'node', 'type' => 'entity_reference', 'settings' => array('target_type' => 'node'))); $field_storage->save(); $field = entity_create('field_config', array('field_storage' => $field_storage, 'bundle' => 'reference_content', 'settings' => array('handler' => 'default', 'handler_settings' => array('target_bundles' => array('referenced_content'), 'sort' => array('field' => '_none'))))); $field->save(); // Set created node as default_value. $field_edit = array('default_value_input[' . $field_name . '][0][target_id]' => $referenced_node->getTitle() . ' (' . $referenced_node->id() . ')'); $this->drupalPostForm('admin/structure/types/manage/reference_content/fields/node.reference_content.' . $field_name, $field_edit, t('Save settings')); // Check that default value is selected in default value form. $this->drupalGet('admin/structure/types/manage/reference_content/fields/node.reference_content.' . $field_name); $this->assertRaw('name="default_value_input[' . $field_name . '][0][target_id]" value="' . $referenced_node->getTitle() . ' (' . $referenced_node->id() . ')', 'The default value is selected in instance settings page'); // Check if the ID has been converted to UUID in config entity. $config_entity = $this->container->get('config.factory')->get('field.field.node.reference_content.' . $field_name)->get(); $this->assertTrue(isset($config_entity['default_value'][0]['target_uuid']), 'Default value contains target_uuid property'); $this->assertEqual($config_entity['default_value'][0]['target_uuid'], $referenced_node->uuid(), 'Content uuid and config entity uuid are the same'); // Ensure the configuration has the expected dependency on the entity that // is being used a default value. $this->assertEqual(array($referenced_node->getConfigDependencyName()), $config_entity['dependencies']['content']); // Clear field definitions cache in order to avoid stale cache values. \Drupal::entityManager()->clearCachedFieldDefinitions(); // Create a new node to check that UUID has been converted to numeric ID. $new_node = entity_create('node', array('type' => 'reference_content')); $this->assertEqual($new_node->get($field_name)->offsetGet(0)->target_id, $referenced_node->id()); }
/** * Tests that page title is being converted into a block. */ public function testUpdateHookN() { $this->runUpdates(); /** @var \Drupal\block\BlockInterface $block_storage */ $block_storage = \Drupal::entityManager()->getStorage('block'); $this->assertRaw('Because your site has custom theme(s) installed, we have placed the page title block in the content region. Please manually review the block configuration and remove the page title variables from your page 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(); // Page title is visible on the home page. $this->drupalGet('/node'); $this->assertRaw('page-title'); // Page title is visible on a node page. $this->drupalGet('node/' . $page->id()); $this->assertRaw('page-title'); $this->drupalGet('admin/structure/block/list/bartik'); /** @var \Drupal\Core\Config\StorageInterface $config_storage */ $config_storage = \Drupal::service('config.storage'); $this->assertTrue($config_storage->exists('block.block.test_theme_page_title'), 'Page title block has been created for the custom theme.'); }
/** * {@inheritdoc} */ public static function preDelete(EntityStorageInterface $storage, array $entities) { $registration_storage = \Drupal::entityManager()->getStorage('registration'); /** @var \Drupal\rng\EventManagerInterface $event_manager */ $event_manager = \Drupal::service('rng.event_manager'); /** @var \Drupal\rng\RegistrationTypeInterface $registration_type */ foreach ($entities as $registration_type) { // Remove entity field references in // $event->{EventManagerInterface::FIELD_REGISTRATION_TYPE} $event_types = $event_manager->getEventTypes(); foreach ($event_types as $entity_type => $bundles) { $event_storage = \Drupal::entityManager()->getStorage($entity_type); foreach ($bundles as $bundle => $event_type) { $bundle_key = \Drupal::entityManager()->getDefinition($entity_type)->getKey('bundle'); $ids = $event_storage->getQuery()->condition($bundle_key, $bundle)->condition(EventManagerInterface::FIELD_REGISTRATION_TYPE, $registration_type->id())->execute(); foreach ($ids as $id) { $event_manager->getMeta($event_storage->load($id))->removeRegistrationType($registration_type->id())->save(); } } } // Remove registrations. $ids = $registration_storage->getQuery()->condition('type', $registration_type->id())->execute(); $registrations = $registration_storage->loadMultiple($ids); $registration_storage->delete($registrations); } parent::preDelete($storage, $entities); }
/** * {@inheritdoc} */ public function form(array $form, FormStateInterface $form_state) { $form = parent::form($form, $form_state); /* @var \Drupal\crm_core_contact\Entity\ContactType $type */ $type = $this->entity; $form['name'] = array('#title' => $this->t('Name'), '#type' => 'textfield', '#default_value' => $type->name, '#description' => $this->t('The human-readable name of this contact type. It is recommended that this name begin with a capital letter and contain only letters, numbers, and spaces. This name must be unique.'), '#required' => TRUE, '#size' => 32); $form['type'] = array('#type' => 'machine_name', '#default_value' => $type->id(), '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH, '#machine_name' => array('exists' => 'Drupal\\crm_core_contact\\Entity\\ContactType::load', 'source' => array('name')), '#description' => $this->t('A unique machine-readable name for this contact type. It must only contain lowercase letters, numbers, and underscores.')); $form['description'] = array('#title' => $this->t('Description'), '#type' => 'textarea', '#default_value' => $type->description, '#description' => $this->t('Describe this contact type.')); // Primary fields section. $form['primary_fields_container'] = array('#type' => 'fieldset', '#title' => $this->t('Primary Fields'), '#description' => $this->t('Primary fields are used to tell other modules what fields to use for common communications tasks such as sending an email, addressing an envelope, etc. Use the fields below to indicate the primary fields for this contact type.')); // @todo Move primary fields array to some hook. This Would allow extend this // list to other modules. This hook should return arra('key'=>t('Name')). $default_primary_fields = array('email', 'address', 'phone'); // $primary_fields = variable_get('crm_core_contact_default_primary_fields', $default_primary_fields); $primary_fields = $default_primary_fields; $options = array(); if (isset($type->type)) { /* @var \Drupal\Core\Field\FieldDefinitionInterface[] $instances */ $instances = \Drupal::entityManager()->getFieldDefinitions('crm_core_contact', $type->type); $instances = isset($instances[$type->type]) ? $instances[$type->type] : array(); foreach ($instances as $instance) { $options[$instance->getName()] = $instance->getLabel(); } } foreach ($primary_fields as $primary_field) { $form['primary_fields_container'][$primary_field] = array('#type' => 'select', '#title' => $this->t('Primary @field field', array('@field' => $primary_field)), '#default_value' => empty($type->primary_fields[$primary_field]) ? '' : $type->primary_fields[$primary_field], '#empty_value' => '', '#empty_option' => $this->t('--Please Select--'), '#options' => $options); } return $form; }
/** * Delete a group. */ function testDeleteGroup() { $data = array('format_type' => 'fieldset', 'label' => 'testing'); $group = $this->createGroup('node', $this->type, 'form', 'default', $data); $config_name = 'node.' . $this->type . '.form.default.' . $group->group_name; $this->drupalPostForm('admin/structure/types/manage/' . $this->type . '/groups/' . $config_name . '/delete', array(), t('Delete')); $this->assertRaw(t('The group %label has been deleted from the %type content type.', array('%label' => $group->label, '%type' => $this->type)), t('Group removal message displayed on screen.')); $display = EntityFormDisplay::load($group->entity_type . '.' . $group->bundle . '.' . $group->mode); $data = $display->getThirdPartySettings('field_group'); debug($data); // Test that group is not in the $groups array. \Drupal::entityManager()->getStorage('entity_form_display')->resetCache(); $loaded_group = field_group_load_field_group($group->group_name, 'node', $this->type, 'form', 'default'); debug($loaded_group); $this->assertNull($loaded_group, t('Group not found after deleting')); $data = array('format_type' => 'fieldset', 'label' => 'testing'); $group = $this->createGroup('node', $this->type, 'view', 'default', $data); $config_name = 'node.' . $this->type . '.view.default.' . $group->group_name; $this->drupalPostForm('admin/structure/types/manage/' . $this->type . '/groups/' . $config_name . '/delete', array(), t('Delete')); $this->assertRaw(t('The group %label has been deleted from the %type content type.', array('%label' => $group->label, '%type' => $this->type)), t('Group removal message displayed on screen.')); // Test that group is not in the $groups array. \Drupal::entityManager()->getStorage('entity_view_display')->resetCache(); $loaded_group = field_group_load_field_group($group->group_name, 'node', $this->type, 'view', 'default'); debug($loaded_group); $this->assertNull($loaded_group, t('Group not found after deleting')); }
/** * Test time zones and DST handling. */ function testTimeZoneHandling() { // Setup date/time settings for Honolulu time. $config = $this->config('system.date')->set('timezone.default', 'Pacific/Honolulu')->set('timezone.user.configurable', 0)->save(); entity_load('date_format', 'medium')->setPattern('Y-m-d H:i:s O')->save(); // Create some nodes with different authored-on dates. $date1 = '2007-01-31 21:00:00 -1000'; $date2 = '2007-07-31 21:00:00 -1000'; $this->drupalCreateContentType(array('type' => 'article')); $node1 = $this->drupalCreateNode(array('created' => strtotime($date1), 'type' => 'article')); $node2 = $this->drupalCreateNode(array('created' => strtotime($date2), 'type' => 'article')); // Confirm date format and time zone. $this->drupalGet('node/' . $node1->id()); $this->assertText('2007-01-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.'); $this->drupalGet('node/' . $node2->id()); $this->assertText('2007-07-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.'); // Set time zone to Los Angeles time. $config->set('timezone.default', 'America/Los_Angeles')->save(); \Drupal::entityManager()->getViewBuilder('node')->resetCache(array($node1, $node2)); // Confirm date format and time zone. $this->drupalGet('node/' . $node1->id()); $this->assertText('2007-01-31 23:00:00 -0800', 'Date should be two hours ahead, with GMT offset of -8 hours.'); $this->drupalGet('node/' . $node2->id()); $this->assertText('2007-08-01 00:00:00 -0700', 'Date should be three hours ahead, with GMT offset of -7 hours.'); }
/** * Tests creating a comment type programmatically and via a form. */ public function testCommentTypeCreation() { // Create a comment type programmatically. $type = $this->createCommentType('other'); $comment_type = CommentType::load('other'); $this->assertTrue($comment_type, 'The new comment type has been created.'); // Login a test user. $this->drupalLogin($this->adminUser); $this->drupalGet('admin/structure/comment/manage/' . $type->id()); $this->assertResponse(200, 'The new comment type can be accessed at the edit form.'); // Create a comment type via the user interface. $edit = array('id' => 'foo', 'label' => 'title for foo', 'description' => '', 'target_entity_type_id' => 'node'); $this->drupalPostForm('admin/structure/comment/types/add', $edit, t('Save')); $comment_type = CommentType::load('foo'); $this->assertTrue($comment_type, 'The new comment type has been created.'); // Check that the comment type was created in site default language. $default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId(); $this->assertEqual($comment_type->language()->getId(), $default_langcode); // Edit the comment-type and ensure that we cannot change the entity-type. $this->drupalGet('admin/structure/comment/manage/foo'); $this->assertNoField('target_entity_type_id', 'Entity type file not present'); $this->assertText(t('Target entity type')); // Save the form and ensure the entity-type value is preserved even though // the field isn't present. $this->drupalPostForm(NULL, array(), t('Save')); \Drupal::entityManager()->getStorage('comment_type')->resetCache(array('foo')); $comment_type = CommentType::load('foo'); $this->assertEqual($comment_type->getTargetEntityTypeId(), 'node'); }
/** * Gets the URI without the 'internal:' or 'entity:' scheme. * * The following two forms of URIs are transformed: * - 'entity:' URIs: to entity autocomplete ("label (entity id)") strings; * - 'internal:' URIs: the scheme is stripped. * * This method is the inverse of ::getUserEnteredStringAsUri(). * * @param string $uri * The URI to get the displayable string for. * * @return string * * @see static::getUserEnteredStringAsUri() */ protected static function getUriAsDisplayableString($uri) { $scheme = parse_url($uri, PHP_URL_SCHEME); // By default, the displayable string is the URI. $displayable_string = $uri; // A different displayable string may be chosen in case of the 'internal:' // or 'entity:' built-in schemes. if ($scheme === 'internal') { $uri_reference = explode(':', $uri, 2)[1]; // @todo '<front>' is valid input for BC reasons, may be removed by // https://www.drupal.org/node/2421941 $path = parse_url($uri, PHP_URL_PATH); if ($path === '/') { $uri_reference = '<front>' . substr($uri_reference, 1); } $displayable_string = $uri_reference; } elseif ($scheme === 'entity') { list($entity_type, $entity_id) = explode('/', substr($uri, 7), 2); // Show the 'entity:' URI as the entity autocomplete would. $entity_manager = \Drupal::entityManager(); if ($entity_manager->getDefinition($entity_type, FALSE) && ($entity = \Drupal::entityManager()->getStorage($entity_type)->load($entity_id))) { $displayable_string = EntityAutocomplete::getEntityLabels(array($entity)); } } return $displayable_string; }
/** * Returns the entity manager. * * @return \Drupal\Core\Entity\EntityManagerInterface * The entity manager service. */ protected function getEntityManager() { if (!isset($this->entityManager)) { $this->entityManager = \Drupal::entityManager(); } return $this->entityManager; }
/** * {@inheritdoc} */ protected function setUp($import_test_views = TRUE) { parent::setUp($import_test_views); $this->installEntitySchema('user'); $this->installEntitySchema('comment'); // Create the anonymous role. $this->installConfig(['user']); // Create an anonymous user. $storage = \Drupal::entityManager()->getStorage('user'); // Insert a row for the anonymous user. $storage->create(array('uid' => 0, 'name' => '', 'status' => 0))->save(); $admin_role = Role::create(['id' => 'admin', 'permissions' => ['administer comments', 'access user profiles']]); $admin_role->save(); /* @var \Drupal\user\RoleInterface $anonymous_role */ $anonymous_role = Role::load(Role::ANONYMOUS_ID); $anonymous_role->grantPermission('access comments'); $anonymous_role->save(); $this->adminUser = User::create(['name' => $this->randomMachineName(), 'roles' => [$admin_role->id()]]); $this->adminUser->save(); // Create some comments. $comment = Comment::create(['subject' => 'My comment title', 'uid' => $this->adminUser->id(), 'name' => $this->adminUser->label(), 'entity_type' => 'entity_test', 'comment_type' => 'entity_test', 'status' => 1]); $comment->save(); $comment_anonymous = Comment::create(['subject' => 'Anonymous comment title', 'uid' => 0, 'name' => 'barry', 'mail' => '*****@*****.**', 'homepage' => 'https://example.com', 'entity_type' => 'entity_test', 'comment_type' => 'entity_test', 'created' => 123456, 'status' => 1]); $comment_anonymous->save(); }
/** * Converts entity labels for entity reference fields to entity ids. * * @param string $entity_type * The type of the entity being processed. * @param string $entity_bundle * The bundle of the entity being processed. * @param array $values * An array of field values keyed by field name. * * @return array * The processed field values. * * @throws \Exception * Thrown when no entity with the given label has been found. */ public function convertEntityReferencesValues($entity_type, $entity_bundle, $values) { $definitions = \Drupal::entityManager()->getFieldDefinitions($entity_type, $entity_bundle); foreach ($definitions as $name => $definition) { if ($definition->getType() != 'entity_reference' || !array_key_exists($name, $values) || !strlen($values[$name])) { continue; } // Retrieve the entity type and bundles that can be referenced. $settings = $definition->getSettings(); $target_entity_type = $settings['target_type']; $target_entity_bundles = $settings['handler_settings']['target_bundles']; // Multi-value fields are separated by comma. $labels = explode(', ', $values[$name]); $values[$name] = []; foreach ($labels as $label) { $id = $this->getEntityIdByLabel($label, $target_entity_type, $target_entity_bundles); $bundles = implode(',', $target_entity_bundles); if (!$id) { throw new \Exception("Entity with label '{$label}' could not be found for '{$target_entity_type} ({$bundles})' to fill field '{$name}'."); } $values[$name][] = $id; } } return $values; }
/** * Tests the machine name form. */ public function testMachineNameOption() { $this->drupalGet('admin/structure/views/view/test_view'); // Add a new attachment display. $this->drupalPostForm(NULL, array(), 'Add Attachment'); // Change the machine name for the display from page_1 to test_1. $edit = array('display_id' => 'test_1'); $this->drupalPostForm('admin/structure/views/nojs/display/test_view/attachment_1/display_id', $edit, 'Apply'); $this->assertLink(t('test_1')); // Save the view, and test the new ID has been saved. $this->drupalPostForm(NULL, array(), 'Save'); $view = \Drupal::entityManager()->getStorage('view')->load('test_view'); $displays = $view->get('display'); $this->assertTrue(!empty($displays['test_1']), 'Display data found for new display ID key.'); $this->assertIdentical($displays['test_1']['id'], 'test_1', 'New display ID matches the display ID key.'); $this->assertFalse(array_key_exists('attachment_1', $displays), 'Old display ID not found.'); // Test the form validation with invalid IDs. $machine_name_edit_url = 'admin/structure/views/nojs/display/test_view/test_1/display_id'; $error_text = t('Display name must be letters, numbers, or underscores only.'); $edit = array('display_id' => 'test 1'); $this->drupalPostForm($machine_name_edit_url, $edit, 'Apply'); $this->assertText($error_text); $edit = array('display_id' => 'test_1#'); $this->drupalPostForm($machine_name_edit_url, $edit, 'Apply'); $this->assertText($error_text); // Test using an existing display ID. $edit = array('display_id' => 'default'); $this->drupalPostForm($machine_name_edit_url, $edit, 'Apply'); $this->assertText(t('Display id should be unique.')); // Test that the display ID has not been changed. $this->drupalGet('admin/structure/views/view/test_view/edit/test_1'); $this->assertLink(t('test_1')); }