コード例 #1
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->drupalPlaceBlock('local_tasks_block');
     $this->drupalPlaceBlock('local_actions_block');
     $this->drupalPlaceBlock('page_title_block');
     $this->type = $this->createProfileType('test', 'Test profile', TRUE);
     $id = $this->type->id();
     $field_storage = FieldStorageConfig::create(['field_name' => 'profile_fullname', 'entity_type' => 'profile', 'type' => 'text']);
     $field_storage->save();
     $this->field = FieldConfig::create(['field_storage' => $field_storage, 'bundle' => $this->type->id(), 'label' => 'Full name']);
     $this->field->save();
     // Configure the default display.
     $this->display = EntityViewDisplay::load("profile.{$this->type->id()}.default");
     if (!$this->display) {
         $this->display = EntityViewDisplay::create(['targetEntityType' => 'profile', 'bundle' => $this->type->id(), 'mode' => 'default', 'status' => TRUE]);
         $this->display->save();
     }
     $this->display->setComponent($this->field->getName(), ['type' => 'string'])->save();
     // Configure rhe default form.
     $this->form = EntityFormDisplay::load("profile.{$this->type->id()}.default");
     if (!$this->form) {
         $this->form = EntityFormDisplay::create(['targetEntityType' => 'profile', 'bundle' => $this->type->id(), 'mode' => 'default', 'status' => TRUE]);
         $this->form->save();
     }
     $this->form->setComponent($this->field->getName(), ['type' => 'string_textfield'])->save();
     $this->checkPermissions(['administer profile types', "view own {$id} profile", "view any {$id} profile", "add own {$id} profile", "add any {$id} profile", "edit own {$id} profile", "edit any {$id} profile", "delete own {$id} profile", "delete any {$id} profile"]);
     user_role_grant_permissions(AccountInterface::AUTHENTICATED_ROLE, ['access user profiles']);
     $this->adminUser = $this->drupalCreateUser(['administer profile types', "view any {$id} profile", "add any {$id} profile", "edit any {$id} profile", "delete any {$id} profile"]);
 }
コード例 #2
0
 /**
  * Tests the Drupal 7 user picture to Drupal 8 entity display migration.
  */
 public function testUserPictureEntityDisplay()
 {
     $component = EntityViewDisplay::load('user.user.default')->getComponent('user_picture');
     $this->assertIdentical('image', $component['type']);
     $this->assertIdentical('', $component['settings']['image_style']);
     $this->assertIdentical('content', $component['settings']['image_link']);
 }
コード例 #3
0
 /**
  * Tests markup is escaped in the entity reference select and label formatter.
  */
 public function testEntityReferenceXSS()
 {
     $this->drupalCreateContentType(['type' => 'article']);
     // Create a node with markup in the title.
     $node_type_one = $this->drupalCreateContentType();
     $node = ['type' => $node_type_one->id(), 'title' => '<em>I am kitten</em>'];
     $referenced_node = $this->drupalCreateNode($node);
     $node_type_two = $this->drupalCreateContentType(['name' => '<em>bundle with markup</em>']);
     $this->drupalCreateNode(['type' => $node_type_two->id(), 'title' => 'My bundle has markup']);
     $this->createEntityReferenceField('node', 'article', 'entity_reference_test', 'Entity Reference test', 'node', 'default', ['target_bundles' => [$node_type_one->id(), $node_type_two->id()]]);
     EntityFormDisplay::load('node.article.default')->setComponent('entity_reference_test', ['type' => 'options_select'])->save();
     EntityViewDisplay::load('node.article.default')->setComponent('entity_reference_test', ['type' => 'entity_reference_label'])->save();
     // Create a node and reference the node with markup in the title.
     $this->drupalLogin($this->rootUser);
     $this->drupalGet('node/add/article');
     $this->assertEscaped($referenced_node->getTitle());
     $this->assertEscaped($node_type_two->label());
     $edit = ['title[0][value]' => $this->randomString(), 'entity_reference_test' => $referenced_node->id()];
     $this->drupalPostForm(NULL, $edit, 'Save and publish');
     $this->assertEscaped($referenced_node->getTitle());
     // Test the options_buttons type.
     EntityFormDisplay::load('node.article.default')->setComponent('entity_reference_test', ['type' => 'options_buttons'])->save();
     $this->drupalGet('node/add/article');
     $this->assertEscaped($referenced_node->getTitle());
     // options_buttons does not support optgroups.
     $this->assertNoText('bundle with markup');
 }
コード例 #4
0
 /**
  * {@inheritdoc}
  */
 public function generateFieldMetadata(FieldItemListInterface $items, $view_mode)
 {
     $entity = $items->getEntity();
     $field_name = $items->getFieldDefinition()->getName();
     // Early-return if user does not have access.
     $access = $this->accessChecker->accessEditEntityField($entity, $field_name);
     if (!$access) {
         return array('access' => FALSE);
     }
     // Early-return if no editor is available.
     $formatter_id = EntityViewDisplay::collectRenderDisplay($entity, $view_mode)->getRenderer($field_name)->getPluginId();
     $editor_id = $this->editorSelector->getEditor($formatter_id, $items);
     if (!isset($editor_id)) {
         return array('access' => FALSE);
     }
     // Gather metadata, allow the editor to add additional metadata of its own.
     $label = $items->getFieldDefinition()->getLabel();
     $editor = $this->editorManager->createInstance($editor_id);
     $metadata = array('label' => String::checkPlain($label), 'access' => TRUE, 'editor' => $editor_id, 'aria' => t('Entity @type @id, field @field', array('@type' => $entity->getEntityTypeId(), '@id' => $entity->id(), '@field' => $label)));
     $custom_metadata = $editor->getMetadata($items);
     if (count($custom_metadata)) {
         $metadata['custom'] = $custom_metadata;
     }
     return $metadata;
 }
コード例 #5
0
ファイル: ExportablesTest.php プロジェクト: neeravbm/unify-d8
 /**
  * Enables the exportables module.
  */
 function dsExportablesSetup()
 {
     /** @var $display EntityViewDisplay */
     $display = EntityViewDisplay::load('node.article.default');
     $display->delete();
     \Drupal::service('module_installer')->install(array('ds_exportables_test'));
 }
コード例 #6
0
 /**
  * Asserts a display entity.
  *
  * @param string $id
  *   The entity ID.
  * @param string $component_id
  *   The ID of the display component.
  */
 protected function assertDisplay($id, $component_id)
 {
     $component = EntityViewDisplay::load($id)->getComponent($component_id);
     $this->assertTrue(is_array($component));
     $this->assertIdentical('hidden', $component['label']);
     $this->assertIdentical('comment_default', $component['type']);
     $this->assertIdentical(20, $component['weight']);
 }
コード例 #7
0
 /**
  * Tests the Drupal 6 vocabulary-node type association to Drupal 8 migration.
  */
 public function testVocabularyEntityDisplay()
 {
     // Test that the field exists.
     $component = EntityViewDisplay::load('node.page.default')->getComponent('tags');
     $this->assertIdentical('entity_reference_label', $component['type']);
     $this->assertIdentical(20, $component['weight']);
     // Test the Id map.
     $this->assertIdentical(array('node', 'article', 'default', 'tags'), $this->getMigration('d6_vocabulary_entity_display')->getIdMap()->lookupDestinationID(array(4, 'article')));
 }
コード例 #8
0
 /**
  * Tests the dependency between ImageStyle and entity display components.
  */
 public function testEntityDisplayDependency()
 {
     // Create two image styles.
     /** @var \Drupal\image\ImageStyleInterface $style */
     $style = ImageStyle::create(['name' => 'main_style']);
     $style->save();
     /** @var \Drupal\image\ImageStyleInterface $replacement */
     $replacement = ImageStyle::create(['name' => 'replacement_style']);
     $replacement->save();
     // Create a node-type, named 'note'.
     $node_type = NodeType::create(['type' => 'note']);
     $node_type->save();
     // Create an image field and attach it to the 'note' node-type.
     FieldStorageConfig::create(['entity_type' => 'node', 'field_name' => 'sticker', 'type' => 'image'])->save();
     FieldConfig::create(['entity_type' => 'node', 'field_name' => 'sticker', 'bundle' => 'note'])->save();
     // Create the default entity view display and set the 'sticker' field to use
     // the 'main_style' images style in formatter.
     /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $view_display */
     $view_display = EntityViewDisplay::create(['targetEntityType' => 'node', 'bundle' => 'note', 'mode' => 'default', 'status' => TRUE])->setComponent('sticker', ['settings' => ['image_style' => 'main_style']]);
     $view_display->save();
     // Create the default entity form display and set the 'sticker' field to use
     // the 'main_style' images style in the widget.
     /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
     $form_display = EntityFormDisplay::create(['targetEntityType' => 'node', 'bundle' => 'note', 'mode' => 'default', 'status' => TRUE])->setComponent('sticker', ['settings' => ['preview_image_style' => 'main_style']]);
     $form_display->save();
     // Check that the entity displays exists before dependency removal.
     $this->assertNotNull(EntityViewDisplay::load($view_display->id()));
     $this->assertNotNull(EntityFormDisplay::load($form_display->id()));
     // Delete the 'main_style' image style. Before that, emulate the UI process
     // of selecting a replacement style by setting the replacement image style
     // ID in the image style storage.
     /** @var \Drupal\image\ImageStyleStorageInterface $storage */
     $storage = $this->container->get('entity.manager')->getStorage($style->getEntityTypeId());
     $storage->setReplacementId('main_style', 'replacement_style');
     $style->delete();
     // Check that the entity displays exists after dependency removal.
     $this->assertNotNull($view_display = EntityViewDisplay::load($view_display->id()));
     $this->assertNotNull($form_display = EntityFormDisplay::load($form_display->id()));
     // Check that the 'sticker' formatter component exists in both displays.
     $this->assertNotNull($formatter = $view_display->getComponent('sticker'));
     $this->assertNotNull($widget = $form_display->getComponent('sticker'));
     // Check that both displays are using now 'replacement_style' for images.
     $this->assertSame('replacement_style', $formatter['settings']['image_style']);
     $this->assertSame('replacement_style', $widget['settings']['preview_image_style']);
     // Delete the 'replacement_style' without setting a replacement image style.
     $replacement->delete();
     // The entity view and form displays exists after dependency removal.
     $this->assertNotNull($view_display = EntityViewDisplay::load($view_display->id()));
     $this->assertNotNull($form_display = EntityFormDisplay::load($form_display->id()));
     // The 'sticker' formatter component should be hidden in view display.
     $this->assertNull($view_display->getComponent('sticker'));
     $this->assertTrue($view_display->get('hidden')['sticker']);
     // The 'sticker' widget component should be active in form displays, but the
     // image preview should be disabled.
     $this->assertNotNull($widget = $form_display->getComponent('sticker'));
     $this->assertSame('', $widget['settings']['preview_image_style']);
 }
コード例 #9
0
 /**
  * Tests comment variables migrated into an entity display.
  */
 public function testCommentEntityDisplay()
 {
     foreach (['page', 'story', 'article'] as $type) {
         $component = EntityViewDisplay::load('node.' . $type . '.default')->getComponent('comment');
         $this->assertIdentical('hidden', $component['label']);
         $this->assertIdentical('comment_default', $component['type']);
         $this->assertIdentical(20, $component['weight']);
     }
 }
コード例 #10
0
ファイル: image.post_update.php プロジェクト: aWEBoLabs/taxi
/**
 * Saves the image style dependencies into form and view display entities.
 */
function image_post_update_image_style_dependencies()
{
    // Merge view and form displays. Use array_values() to avoid key collisions.
    $displays = array_merge(array_values(EntityViewDisplay::loadMultiple()), array_values(EntityFormDisplay::loadMultiple()));
    /** @var \Drupal\Core\Entity\Display\EntityDisplayInterface[] $displays */
    foreach ($displays as $display) {
        // Re-save each config entity to add missed dependencies.
        $display->save();
    }
}
コード例 #11
0
/**
 * Make responsive image formatters dependent on responsive image styles.
 */
function responsive_image_post_update_recreate_dependencies()
{
    $displays = EntityViewDisplay::loadMultiple();
    array_walk($displays, function (EntityViewDisplayInterface $entity_view_display) {
        $old_dependencies = $entity_view_display->getDependencies();
        $new_dependencies = $entity_view_display->calculateDependencies()->getDependencies();
        if ($old_dependencies !== $new_dependencies) {
            $entity_view_display->save();
        }
    });
}
コード例 #12
0
 /**
  * Tests the Drupal 6 upload settings to Drupal 8 entity display migration.
  */
 public function testUploadEntityDisplay()
 {
     $display = EntityViewDisplay::load('node.page.default');
     $component = $display->getComponent('upload');
     $this->assertIdentical('file_default', $component['type']);
     $display = EntityViewDisplay::load('node.story.default');
     $component = $display->getComponent('upload');
     $this->assertIdentical('file_default', $component['type']);
     // Assure this doesn't exist.
     $display = EntityViewDisplay::load('node.article.default');
     $component = $display->getComponent('upload');
     $this->assertTrue(is_null($component));
     $this->assertIdentical(array('node', 'page', 'default', 'upload'), $this->getMigration('d6_upload_entity_display')->getIdMap()->lookupDestinationID(array('page')));
 }
コード例 #13
0
ファイル: KernelTestBase.php プロジェクト: badelas/afroweb
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema($this->entityTypeId);
     EntityViewDisplay::create(['targetEntityType' => 'entity_test', 'bundle' => 'entity_test', 'mode' => 'default'])->save();
     FieldStorageConfig::create(['field_name' => $this->fieldName, 'entity_type' => $this->entityTypeId, 'type' => 'video_embed_field'])->save();
     FieldConfig::create(['entity_type' => $this->entityTypeId, 'field_name' => $this->fieldName, 'bundle' => $this->entityTypeId])->save();
     // Fake colorbox being enabled for the purposes of testing.
     $this->container->get('module_handler')->addModule('colorbox', NULL);
     // Use a HTTP mock which won't attempt to download anything.
     $this->container->set('http_client', new MockHttpClient());
     // Shim in a service required from the colorbox module.
     $colorbox_mock = $this->getMockBuilder('ColorboxAttachment')->setMethods(['attach'])->getMock();
     $this->container->set('colorbox.attachment', $colorbox_mock);
 }
コード例 #14
0
 /**
  * Tests image style deletion.
  */
 public function testDelete()
 {
     $this->drupalGet('admin/config/media/image-styles/manage/medium/delete');
     // Checks that the 'replacement' select element is displayed.
     $this->assertFieldByName('replacement');
     // Checks that UI messages are correct.
     $this->assertRaw(t('If this style is in use on the site, you may select another style to replace it. All images that have been generated for this style will be permanently deleted. If no replacement style is selected, the dependent configurations might need manual reconfiguration.'));
     $this->assertNoRaw(t('All images that have been generated for this style will be permanently deleted. The dependent configurations might need manual reconfiguration.'));
     // Delete 'medium' image style but replace it with 'thumbnail'. This style
     // is involved in 'node.page.default' display view and form.
     $this->drupalPostForm(NULL, ['replacement' => 'thumbnail'], t('Delete'));
     /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $view_display */
     $view_display = EntityViewDisplay::load('node.page.default');
     // Checks that the formatter setting is replaced.
     if ($this->assertNotNull($component = $view_display->getComponent('foo'))) {
         $this->assertIdentical($component['settings']['image_style'], 'thumbnail');
     }
     /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
     $form_display = EntityFormDisplay::load('node.page.default');
     // Check that the widget setting is replaced.
     if ($this->assertNotNull($component = $form_display->getComponent('foo'))) {
         $this->assertIdentical($component['settings']['preview_image_style'], 'thumbnail');
     }
     $this->drupalGet('admin/config/media/image-styles/manage/thumbnail/delete');
     // Checks that the 'replacement' select element is displayed.
     $this->assertFieldByName('replacement');
     // Checks that UI messages are correct.
     $this->assertRaw(t('If this style is in use on the site, you may select another style to replace it. All images that have been generated for this style will be permanently deleted. If no replacement style is selected, the dependent configurations might need manual reconfiguration.'));
     $this->assertNoRaw(t('All images that have been generated for this style will be permanently deleted. The dependent configurations might need manual reconfiguration.'));
     // Delete 'thumbnail' image style. Provide no replacement.
     $this->drupalPostForm(NULL, [], t('Delete'));
     $view_display = EntityViewDisplay::load('node.page.default');
     // Checks that the formatter setting is disabled.
     $this->assertNull($view_display->getComponent('foo'));
     $this->assertNotNull($view_display->get('hidden')['foo']);
     // Checks that widget setting is preserved with the image preview disabled.
     $form_display = EntityFormDisplay::load('node.page.default');
     $this->assertNotNull($widget = $form_display->getComponent('foo'));
     $this->assertIdentical($widget['settings']['preview_image_style'], '');
     // Now, there's only one image style configured on the system: 'large'.
     $this->drupalGet('admin/config/media/image-styles/manage/large/delete');
     // Checks that the 'replacement' select element is not displayed.
     $this->assertNoFieldByName('replacement');
     // Checks that UI messages are correct.
     $this->assertNoRaw(t('If this style is in use on the site, you may select another style to replace it. All images that have been generated for this style will be permanently deleted. If no replacement style is selected, the dependent configurations might need manual reconfiguration.'));
     $this->assertRaw(t('All images that have been generated for this style will be permanently deleted. The dependent configurations might need manual reconfiguration.'));
 }
コード例 #15
0
 /**
  * Tests migration of user profile fields.
  */
 public function testUserProfileFields()
 {
     $display = EntityViewDisplay::load('user.user.default');
     // Test a text field.
     $component = $display->getComponent('profile_color');
     $this->assertIdentical('text_default', $component['type']);
     // Test a list field.
     $component = $display->getComponent('profile_bands');
     $this->assertIdentical('text_default', $component['type']);
     // Test a date field.
     $component = $display->getComponent('profile_birthdate');
     $this->assertIdentical('datetime_default', $component['type']);
     // Test PROFILE_PRIVATE field is hidden.
     $this->assertNull($display->getComponent('profile_sell_address'));
     // Test PROFILE_HIDDEN field is hidden.
     $this->assertNull($display->getComponent('profile_sold_to'));
 }
コード例 #16
0
 /**
  * Tests post-update responsive_image_post_update_dependency().
  *
  * @see responsive_image_post_update_dependency()
  */
 public function testPostUpdateDependency()
 {
     // Installing the 'wide' responsive image style.
     $wide_image_style = Yaml::decode(file_get_contents(__DIR__ . '/../../../../../profiles/standard/config/optional/responsive_image.styles.wide.yml'));
     $this->config('responsive_image.styles.wide')->setData($wide_image_style)->save(TRUE);
     // Change 'field_image' formatter to a responsive image formatter.
     $options = ['type' => 'responsive_image', 'label' => 'hidden', 'settings' => ['responsive_image_style' => 'wide', 'image_link' => ''], 'third_party_settings' => []];
     $display = $this->config('core.entity_view_display.node.article.default');
     $display->set('content.field_image', $options)->save(TRUE);
     // Check that there's no dependency to 'responsive_image.styles.wide'.
     $dependencies = $display->get('dependencies.config') ?: [];
     $this->assertFalse(in_array('responsive_image.styles.wide', $dependencies));
     // Run updates.
     $this->runUpdates();
     /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $view_display */
     $view_display = EntityViewDisplay::load('node.article.default');
     $dependencies = $view_display->getDependencies() + ['config' => []];
     // Check that post-update added a 'responsive_image.styles.wide' dependency.
     $this->assertTrue(in_array('responsive_image.styles.wide', $dependencies['config']));
 }
コード例 #17
0
 /**
  * Tests view mode setting integration.
  *
  * @see comment_entity_view_display_presave()
  * @see CommentDefaultFormatter::calculateDependencies()
  */
 public function testViewMode()
 {
     $mode = Unicode::strtolower($this->randomMachineName());
     // Create a new comment view mode and a view display entity.
     EntityViewMode::create(['id' => "comment.{$mode}", 'targetEntityType' => 'comment', 'settings' => ['comment_type' => 'comment']])->save();
     EntityViewDisplay::create(['targetEntityType' => 'comment', 'bundle' => 'comment', 'mode' => $mode])->setStatus(TRUE)->save();
     // Create a comment field attached to a host 'entity_test' entity.
     FieldStorageConfig::create(['entity_type' => 'entity_test', 'type' => 'comment', 'field_name' => $field_name = Unicode::strtolower($this->randomMachineName()), 'settings' => ['comment_type' => 'comment']])->save();
     FieldConfig::create(['entity_type' => 'entity_test', 'bundle' => 'entity_test', 'field_name' => $field_name])->save();
     $component = ['type' => 'comment_default', 'settings' => ['view_mode' => $mode, 'pager_id' => 0]];
     // Create a new 'entity_test' view display on host entity that uses the
     // custom comment display in field formatter to show the field.
     EntityViewDisplay::create(['targetEntityType' => 'entity_test', 'bundle' => 'entity_test', 'mode' => 'default'])->setComponent($field_name, $component)->setStatus(TRUE)->save();
     $host_display_id = 'entity_test.entity_test.default';
     $comment_display_id = "comment.comment.{$mode}";
     // Disable the "comment.comment.$mode" display.
     EntityViewDisplay::load($comment_display_id)->setStatus(FALSE)->save();
     /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $host_display */
     $host_display = EntityViewDisplay::load($host_display_id);
     // Check that the field formatter has been disabled on host view display.
     $this->assertNull($host_display->getComponent($field_name));
     $this->assertTrue($host_display->get('hidden')[$field_name]);
     // Check that the proper warning has been logged.
     $arguments = ['@id' => $host_display_id, '@name' => $field_name, '@display' => EntityViewMode::load("comment.{$mode}")->label(), '@mode' => $mode];
     $logged = (bool) Database::getConnection()->select('watchdog')->fields('watchdog', ['wid'])->condition('type', 'system')->condition('message', "View display '@id': Comment field formatter '@name' was disabled because it is using the comment view display '@display' (@mode) that was just disabled.")->condition('variables', serialize($arguments))->execute()->fetchField();
     $this->assertTrue($logged);
     // Re-enable the comment view display.
     EntityViewDisplay::load($comment_display_id)->setStatus(TRUE)->save();
     // Re-enable the comment field formatter on host entity view display.
     EntityViewDisplay::load($host_display_id)->setComponent($field_name, $component)->save();
     // Delete the "comment.$mode" view mode.
     EntityViewMode::load("comment.{$mode}")->delete();
     // Check that the comment view display entity has been deleted too.
     $this->assertNull(EntityViewDisplay::load($comment_display_id));
     /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display */
     $host_display = EntityViewDisplay::load($host_display_id);
     // Check that the field formatter has been disabled on host view display.
     $this->assertNull($host_display->getComponent($field_name));
     $this->assertTrue($host_display->get('hidden')[$field_name]);
 }
コード例 #18
0
 /**
  * Tests integration with entity view display.
  */
 public function testEntityViewDisplayDependency()
 {
     // Create a responsive image style.
     ResponsiveImageStyle::create(['id' => 'foo', 'label' => 'Foo', 'breakpoint_group' => 'responsive_image_test_module'])->save();
     // Create an image field to be used with a responsive image formatter.
     FieldStorageConfig::create(['type' => 'image', 'entity_type' => 'entity_test', 'field_name' => 'bar'])->save();
     FieldConfig::create(['entity_type' => 'entity_test', 'bundle' => 'entity_test', 'field_name' => 'bar'])->save();
     /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display */
     $display = EntityViewDisplay::create(['targetEntityType' => 'entity_test', 'bundle' => 'entity_test', 'mode' => 'default']);
     $display->setComponent('bar', ['type' => 'responsive_image', 'label' => 'hidden', 'settings' => ['responsive_image_style' => 'foo', 'image_link' => ''], 'third_party_settings' => []])->save();
     // Check that the 'foo' field is on the display.
     $this->assertNotNull($display = EntityViewDisplay::load('entity_test.entity_test.default'));
     $this->assertTrue($display->getComponent('bar'));
     $this->assertArrayNotHasKey('bar', $display->get('hidden'));
     // Delete the responsive image style.
     ResponsiveImageStyle::load('foo')->delete();
     // Check that the view display was not deleted.
     $this->assertNotNull($display = EntityViewDisplay::load('entity_test.entity_test.default'));
     // Check that the 'foo' field was disabled.
     $this->assertNull($display->getComponent('bar'));
     $this->assertArrayHasKey('bar', $display->get('hidden'));
 }
コード例 #19
0
 /**
  * Tests the translation of the range separator.
  */
 public function testSeparatorTranslation()
 {
     // Create an entity.
     $entity = EntityTest::create(['name' => $this->randomString(), $this->fieldStorage->getName() => ['value' => '2016-09-20', 'end_value' => '2016-09-21']]);
     // Verify the untranslated separator.
     $display = EntityViewDisplay::collectRenderDisplay($entity, 'default');
     $build = $display->build($entity);
     $output = $this->container->get('renderer')->renderRoot($build);
     $this->verbose($output);
     $this->assertContains('UNTRANSLATED', (string) $output);
     // Translate the separator.
     ConfigurableLanguage::createFromLangcode('nl')->save();
     /** @var \Drupal\language\ConfigurableLanguageManagerInterface $language_manager */
     $language_manager = $this->container->get('language_manager');
     $language_manager->getLanguageConfigOverride('nl', 'core.entity_view_display.entity_test.entity_test.default')->set('content.' . $this->fieldStorage->getName() . '.settings.separator', 'NL_TRANSLATED!')->save();
     $this->container->get('language.config_factory_override')->setLanguage(new Language(['id' => 'nl']));
     $this->container->get('cache_tags.invalidator')->invalidateTags($entity->getCacheTags());
     $display = EntityViewDisplay::collectRenderDisplay($entity, 'default');
     $build = $display->build($entity);
     $output = $this->container->get('renderer')->renderRoot($build);
     $this->verbose($output);
     $this->assertContains('NL_TRANSLATED!', (string) $output);
 }
コード例 #20
0
ファイル: ForumTest.php プロジェクト: scratch/gai
 /**
  * Tests forum functionality through the admin and user interfaces.
  */
 function testForum()
 {
     //Check that the basic forum install creates a default forum topic
     $this->drupalGet('/forum');
     // Look for the "General discussion" default forum
     $this->assertRaw(t('<a href="' . Url::fromRoute('forum.page', ['taxonomy_term' => 1])->toString() . '">General discussion</a>'), "Found the default forum at the /forum listing");
     // Check the presence of expected cache tags.
     $this->assertCacheTag('config:forum.settings');
     $this->drupalGet(Url::fromRoute('forum.page', ['taxonomy_term' => 1]));
     $this->assertCacheTag('config:forum.settings');
     // Do the admin tests.
     $this->doAdminTests($this->adminUser);
     // Check display order.
     $display = EntityViewDisplay::load('node.forum.default');
     $body = $display->getComponent('body');
     $comment = $display->getComponent('comment_forum');
     $taxonomy = $display->getComponent('taxonomy_forums');
     // Assert field order is body » taxonomy » comments.
     $this->assertTrue($taxonomy['weight'] < $body['weight']);
     $this->assertTrue($body['weight'] < $comment['weight']);
     // Check form order.
     $display = EntityFormDisplay::load('node.forum.default');
     $body = $display->getComponent('body');
     $comment = $display->getComponent('comment_forum');
     $taxonomy = $display->getComponent('taxonomy_forums');
     // Assert category comes before body in order.
     $this->assertTrue($taxonomy['weight'] < $body['weight']);
     $this->generateForumTopics();
     // Login an unprivileged user to view the forum topics and generate an
     // active forum topics list.
     $this->drupalLogin($this->webUser);
     // Verify that this user is shown a message that they may not post content.
     $this->drupalGet('forum/' . $this->forum['tid']);
     $this->assertText(t('You are not allowed to post new content in the forum'), "Authenticated user without permission to post forum content is shown message in local tasks to that effect.");
     // Log in, and do basic tests for a user with permission to edit any forum
     // content.
     $this->doBasicTests($this->editAnyTopicsUser, TRUE);
     // Create a forum node authored by this user.
     $any_topics_user_node = $this->createForumTopic($this->forum, FALSE);
     // Log in, and do basic tests for a user with permission to edit only its
     // own forum content.
     $this->doBasicTests($this->editOwnTopicsUser, FALSE);
     // Create a forum node authored by this user.
     $own_topics_user_node = $this->createForumTopic($this->forum, FALSE);
     // Verify that this user cannot edit forum content authored by another user.
     $this->verifyForums($any_topics_user_node, FALSE, 403);
     // Verify that this user is shown a local task to add new forum content.
     $this->drupalGet('forum');
     $this->assertLink(t('Add new Forum topic'));
     $this->drupalGet('forum/' . $this->forum['tid']);
     $this->assertLink(t('Add new Forum topic'));
     // Login a user with permission to edit any forum content.
     $this->drupalLogin($this->editAnyTopicsUser);
     // Verify that this user can edit forum content authored by another user.
     $this->verifyForums($own_topics_user_node, TRUE);
     // Verify the topic and post counts on the forum page.
     $this->drupalGet('forum');
     // Verify row for testing forum.
     $forum_arg = array(':forum' => 'forum-list-' . $this->forum['tid']);
     // Topics cell contains number of topics and number of unread topics.
     $xpath = $this->buildXPathQuery('//tr[@id=:forum]//td[@class="forum__topics"]', $forum_arg);
     $topics = $this->xpath($xpath);
     $topics = trim($topics[0]);
     $this->assertEqual($topics, '6', 'Number of topics found.');
     // Verify the number of unread topics.
     $unread_topics = $this->container->get('forum_manager')->unreadTopics($this->forum['tid'], $this->editAnyTopicsUser->id());
     $unread_topics = \Drupal::translation()->formatPlural($unread_topics, '1 new post', '@count new posts');
     $xpath = $this->buildXPathQuery('//tr[@id=:forum]//td[@class="forum__topics"]//a', $forum_arg);
     $this->assertFieldByXPath($xpath, $unread_topics, 'Number of unread topics found.');
     // Verify that the forum name is in the unread topics text.
     $xpath = $this->buildXPathQuery('//tr[@id=:forum]//em[@class="placeholder"]', $forum_arg);
     $this->assertFieldByXpath($xpath, $this->forum['name'], 'Forum name found in unread topics text.');
     // Verify total number of posts in forum.
     $xpath = $this->buildXPathQuery('//tr[@id=:forum]//td[@class="forum__posts"]', $forum_arg);
     $this->assertFieldByXPath($xpath, '6', 'Number of posts found.');
     // Test loading multiple forum nodes on the front page.
     $this->drupalLogin($this->drupalCreateUser(array('administer content types', 'create forum content', 'post comments')));
     $this->drupalPostForm('admin/structure/types/manage/forum', array('options[promote]' => 'promote'), t('Save content type'));
     $this->createForumTopic($this->forum, FALSE);
     $this->createForumTopic($this->forum, FALSE);
     $this->drupalGet('node');
     // Test adding a comment to a forum topic.
     $node = $this->createForumTopic($this->forum, FALSE);
     $edit = array();
     $edit['comment_body[0][value]'] = $this->randomMachineName();
     $this->drupalPostForm('node/' . $node->id(), $edit, t('Save'));
     $this->assertResponse(200);
     // Test editing a forum topic that has a comment.
     $this->drupalLogin($this->editAnyTopicsUser);
     $this->drupalGet('forum/' . $this->forum['tid']);
     $this->drupalPostForm('node/' . $node->id() . '/edit', array(), t('Save'));
     $this->assertResponse(200);
     // Test the root forum page title change.
     $this->drupalGet('forum');
     $this->assertCacheTag('config:taxonomy.vocabulary.' . $this->forum['vid']);
     $this->assertTitle(t('Forums | Drupal'));
     $vocabulary = Vocabulary::load($this->forum['vid']);
     $vocabulary->set('name', 'Discussions');
     $vocabulary->save();
     $this->drupalGet('forum');
     $this->assertTitle(t('Discussions | Drupal'));
     // Test anonymous action link.
     $this->drupalLogout();
     $this->drupalGet('forum/' . $this->forum['tid']);
     $this->assertLink(t('Log in to post new content in the forum.'));
 }
コード例 #21
0
ファイル: EntityDisplayTest.php プロジェクト: isramv/camp-gdl
 /**
  * Test getDisplayModeOptions().
  */
 public function testGetDisplayModeOptions()
 {
     NodeType::create(array('type' => 'article'))->save();
     EntityViewDisplay::create(array('targetEntityType' => 'node', 'bundle' => 'article', 'mode' => 'default'))->setStatus(TRUE)->save();
     $display_teaser = EntityViewDisplay::create(array('targetEntityType' => 'node', 'bundle' => 'article', 'mode' => 'teaser'));
     $display_teaser->save();
     EntityFormDisplay::create(array('targetEntityType' => 'user', 'bundle' => 'user', 'mode' => 'default'))->setStatus(TRUE)->save();
     $form_display_teaser = EntityFormDisplay::create(array('targetEntityType' => 'user', 'bundle' => 'user', 'mode' => 'register'));
     $form_display_teaser->save();
     // Test getViewModeOptionsByBundle().
     $view_modes = \Drupal::entityManager()->getViewModeOptionsByBundle('node', 'article');
     $this->assertEqual($view_modes, array('default' => 'Default'));
     $display_teaser->setStatus(TRUE)->save();
     $view_modes = \Drupal::entityManager()->getViewModeOptionsByBundle('node', 'article');
     $this->assertEqual($view_modes, array('default' => 'Default', 'teaser' => 'Teaser'));
     // Test getFormModeOptionsByBundle().
     $form_modes = \Drupal::entityManager()->getFormModeOptionsByBundle('user', 'user');
     $this->assertEqual($form_modes, array('default' => 'Default'));
     $form_display_teaser->setStatus(TRUE)->save();
     $form_modes = \Drupal::entityManager()->getFormModeOptionsByBundle('user', 'user');
     $this->assertEqual($form_modes, array('default' => 'Default', 'register' => 'Register'));
 }
コード例 #22
0
 /**
  * Tests the rendered entity output with the test field configured to show.
  */
 public function testRenderedEntityWithField()
 {
     \Drupal::currentUser()->setAccount($this->user);
     // Show the test_field on the entity_test.entity_test.foobar view display.
     EntityViewDisplay::load('entity_test.entity_test.foobar')->setComponent('test_field', ['type' => 'string', 'label' => 'above'])->save();
     $view = Views::getView('test_field_entity_test_rendered');
     $build = ['#type' => 'view', '#name' => 'test_field_entity_test_rendered', '#view' => $view, '#display_id' => 'default'];
     $renderer = \Drupal::service('renderer');
     $renderer->renderPlain($build);
     for ($i = 1; $i <= 3; $i++) {
         $view_field = $view->style_plugin->getField($i - 1, 'rendered_entity');
         $search_result = strpos($view_field, "Test {$i}") !== FALSE;
         $this->assertTrue($search_result, "The text 'Test {$i}' found in the view.");
     }
     $this->assertConfigDependencies($view->storage);
     $this->assertCacheabilityMetadata($build);
 }
コード例 #23
0
 /**
  * Tests formatter settings.
  */
 function testFormatterUI()
 {
     $manage_fields = 'admin/structure/types/manage/' . $this->type;
     $manage_display = $manage_fields . '/display';
     // Create a field, and a node with some data for the field.
     $this->fieldUIAddNewField($manage_fields, 'test', 'Test field');
     // Get the display options (formatter and settings) that were automatically
     // assigned for the 'default' display.
     $display = entity_get_display('node', $this->type, 'default');
     $display_options = $display->getComponent('field_test');
     $format = $display_options['type'];
     $default_settings = \Drupal::service('plugin.manager.field.formatter')->getDefaultSettings($format);
     $setting_name = key($default_settings);
     $setting_value = $display_options['settings'][$setting_name];
     // Display the "Manage display" screen and check that the expected formatter
     // is selected.
     $this->drupalGet($manage_display);
     $this->assertFieldByName('fields[field_test][type]', $format, 'The expected formatter is selected.');
     $this->assertText("{$setting_name}: {$setting_value}", 'The expected summary is displayed.');
     // Check whether formatter weights are respected.
     $result = $this->xpath('//select[@id=:id]/option', array(':id' => 'edit-fields-field-test-type'));
     $options = array_map(function ($item) {
         return (string) $item->attributes()->value[0];
     }, $result);
     $expected_options = array('field_no_settings', 'field_empty_test', 'field_empty_setting', 'field_test_default', 'field_test_multiple', 'field_test_with_prepare_view', 'field_test_applicable', 'hidden');
     $this->assertEqual($options, $expected_options, 'The expected formatter ordering is respected.');
     // Change the formatter and check that the summary is updated.
     $edit = array('fields[field_test][type]' => 'field_test_multiple', 'refresh_rows' => 'field_test');
     $this->drupalPostAjaxForm(NULL, $edit, array('op' => t('Refresh')));
     $format = 'field_test_multiple';
     $default_settings = \Drupal::service('plugin.manager.field.formatter')->getDefaultSettings($format);
     $setting_name = key($default_settings);
     $setting_value = $default_settings[$setting_name];
     $this->assertFieldByName('fields[field_test][type]', $format, 'The expected formatter is selected.');
     $this->assertText("{$setting_name}: {$setting_value}", 'The expected summary is displayed.');
     // Submit the form and check that the display is updated.
     $this->drupalPostForm(NULL, array(), t('Save'));
     $display = entity_get_display('node', $this->type, 'default');
     $display_options = $display->getComponent('field_test');
     $current_format = $display_options['type'];
     $current_setting_value = $display_options['settings'][$setting_name];
     $this->assertEqual($current_format, $format, 'The formatter was updated.');
     $this->assertEqual($current_setting_value, $setting_value, 'The setting was updated.');
     // Assert that hook_field_formatter_settings_summary_alter() is called.
     $this->assertText('field_test_field_formatter_settings_summary_alter');
     // Click on the formatter settings button to open the formatter settings
     // form.
     $this->drupalPostAjaxForm(NULL, array(), "field_test_settings_edit");
     // Assert that the field added in
     // field_test_field_formatter_third_party_settings_form() is present.
     $fieldname = 'fields[field_test][settings_edit_form][third_party_settings][field_third_party_test][field_test_field_formatter_third_party_settings_form]';
     $this->assertField($fieldname, 'The field added in hook_field_formatter_third_party_settings_form() is present on the settings form.');
     $edit = array($fieldname => 'foo');
     $this->drupalPostAjaxForm(NULL, $edit, "field_test_plugin_settings_update");
     // Save the form to save the third party settings.
     $this->drupalPostForm(NULL, array(), t('Save'));
     \Drupal::entityManager()->clearCachedFieldDefinitions();
     $id = 'node.' . $this->type . '.default';
     $storage = $this->container->get('entity_type.manager')->getStorage('entity_view_display');
     $storage->resetCache([$id]);
     $display = $storage->load($id);
     $this->assertEqual($display->getRenderer('field_test')->getThirdPartySetting('field_third_party_test', 'field_test_field_formatter_third_party_settings_form'), 'foo');
     $this->assertTrue(in_array('field_third_party_test', $display->calculateDependencies()->getDependencies()['module']), 'The display has a dependency on field_third_party_test module.');
     // Confirm that the third party settings are not updated on the settings form.
     $this->drupalPostAjaxForm(NULL, array(), "field_test_settings_edit");
     $this->assertFieldByName($fieldname, '');
     // Test the empty setting formatter.
     $edit = array('fields[field_test][type]' => 'field_empty_setting');
     $this->drupalPostForm(NULL, $edit, t('Save'));
     $this->assertNoText('Default empty setting now has a value.');
     $this->assertFieldById('edit-fields-field-test-settings-edit');
     $this->drupalPostAjaxForm(NULL, array(), "field_test_settings_edit");
     $fieldname = 'fields[field_test][settings_edit_form][settings][field_empty_setting]';
     $edit = array($fieldname => 'non empty setting');
     $this->drupalPostAjaxForm(NULL, $edit, "field_test_plugin_settings_update");
     $this->assertText('Default empty setting now has a value.');
     // Test the settings form behavior. An edit button should be present since
     // there are third party settings to configure.
     $edit = array('fields[field_test][type]' => 'field_no_settings', 'refresh_rows' => 'field_test');
     $this->drupalPostAjaxForm(NULL, $edit, array('op' => t('Refresh')));
     $this->assertFieldByName('field_test_settings_edit');
     // Make sure we can save the third party settings when there are no settings available
     $this->drupalPostAjaxForm(NULL, array(), "field_test_settings_edit");
     $this->drupalPostAjaxForm(NULL, $edit, "field_test_plugin_settings_update");
     // When a module providing third-party settings to a formatter (or widget)
     // is uninstalled, the formatter remains enabled but the provided settings,
     // together with the corresponding form elements, are removed from the
     // display component.
     \Drupal::service('module_installer')->uninstall(array('field_third_party_test'));
     // Ensure the button is still there after the module has been disabled.
     $this->drupalGet($manage_display);
     $this->assertResponse(200);
     $this->assertFieldByName('field_test_settings_edit');
     // Ensure that third-party form elements are not present anymore.
     $this->drupalPostAjaxForm(NULL, array(), 'field_test_settings_edit');
     $fieldname = 'fields[field_test][settings_edit_form][third_party_settings][field_third_party_test][field_test_field_formatter_third_party_settings_form]';
     $this->assertNoField($fieldname);
     // Ensure that third-party settings were removed from the formatter.
     $display = EntityViewDisplay::load("node.{$this->type}.default");
     $component = $display->getComponent('field_test');
     $this->assertFalse(array_key_exists('field_third_party_test', $component['third_party_settings']));
 }
コード例 #24
0
 /**
  * Renders a entity_test and sets the output in the internal browser.
  *
  * @param int $id
  *   The entity_test ID to render.
  * @param string $view_mode
  *   (optional) The view mode to use for rendering. Defaults to 'full'.
  * @param bool $reset
  *   (optional) Whether to reset the entity_test controller cache. Defaults to
  *   TRUE to simplify testing.
  */
 protected function renderTestEntity($id, $view_mode = 'full', $reset = TRUE)
 {
     if ($reset) {
         \Drupal::entityManager()->getStorage('entity_test')->resetCache(array($id));
     }
     $entity = entity_load('entity_test', $id);
     $display = EntityViewDisplay::collectRenderDisplay($entity, $view_mode);
     $build = $display->build($entity);
     $output = \Drupal::service('renderer')->renderRoot($build);
     $this->setRawContent($output);
     $this->verbose($output);
 }
コード例 #25
0
 /**
  * Tests \Drupal\Core\Entity\EntityDisplayBase::onDependencyRemoval().
  */
 public function testOnDependencyRemoval()
 {
     $this->enableModules(array('field_plugins_test'));
     $field_name = 'test_field';
     // Create a field.
     $field_storage = FieldStorageConfig::create(array('field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => 'text'));
     $field_storage->save();
     $field = FieldConfig::create(array('field_storage' => $field_storage, 'bundle' => 'entity_test'));
     $field->save();
     EntityViewDisplay::create(array('targetEntityType' => 'entity_test', 'bundle' => 'entity_test', 'mode' => 'default'))->setComponent($field_name, array('type' => 'field_plugins_test_text_formatter'))->save();
     // Check the component exists and is of the correct type.
     $display = entity_get_display('entity_test', 'entity_test', 'default');
     $this->assertEqual($display->getComponent($field_name)['type'], 'field_plugins_test_text_formatter');
     // Removing the field_plugins_test module should change the component to use
     // the default formatter for test fields.
     \Drupal::service('config.manager')->uninstall('module', 'field_plugins_test');
     $display = entity_get_display('entity_test', 'entity_test', 'default');
     $this->assertEqual($display->getComponent($field_name)['type'], 'text_default');
     // Removing the text module should remove the field from the view display.
     \Drupal::service('config.manager')->uninstall('module', 'text');
     $display = entity_get_display('entity_test', 'entity_test', 'default');
     $this->assertFalse($display->getComponent($field_name));
 }
コード例 #26
0
 /**
  * Builds the render arrays for all fields of all result rows.
  *
  * The output is built using EntityViewDisplay objects to leverage
  * multiple-entity building and ensure a common code path with regular entity
  * view.
  * - Each relationship is handled by a separate EntityFieldRenderer instance,
  *   since it operates on its own set of entities. This also ensures different
  *   entity types are handled separately, as they imply different
  *   relationships.
  * - Within each relationship, the fields to render are arranged in unique
  *   sets containing each field at most once (an EntityViewDisplay can
  *   only process a field once with given display options, but a View can
  *   contain the same field several times with different display options).
  * - For each set of fields, entities are processed by bundle, so that
  *   formatters can operate on the proper field definition for the bundle.
  *
  * @param \Drupal\views\ResultRow[] $values
  *   An array of all ResultRow objects returned from the query.
  *
  * @return array
  *   A renderable array for the fields handled by this renderer.
  *
  * @see \Drupal\Core\Entity\Entity\EntityViewDisplay
  */
 protected function buildFields(array $values)
 {
     $build = [];
     if ($values && ($field_ids = $this->getRenderableFieldIds())) {
         $entity_type_id = $this->getEntityTypeId();
         // Collect the entities for the relationship, fetch the right translation,
         // and group by bundle. For each result row, the corresponding entity can
         // be obtained from any of the fields handlers, so we arbitrarily use the
         // first one.
         $entities_by_bundles = [];
         $field = $this->view->field[current($field_ids)];
         foreach ($values as $result_row) {
             $entity = $field->getEntity($result_row);
             $entities_by_bundles[$entity->bundle()][$result_row->index] = $this->getEntityTranslation($entity, $result_row);
         }
         // Determine unique sets of fields that can be processed by the same
         // display. Fields that appear several times in the View open additional
         // "overflow" displays.
         $display_sets = [];
         foreach ($field_ids as $field_id) {
             $field = $this->view->field[$field_id];
             $index = 0;
             while (isset($display_sets[$index][$field->definition['field_name']])) {
                 $index++;
             }
             $display_sets[$index][$field_id] = $field;
         }
         // For each set of fields, build the output by bundle.
         foreach ($display_sets as $display_fields) {
             foreach ($entities_by_bundles as $bundle => $bundle_entities) {
                 // Create the display, and configure the field display options.
                 $display = EntityViewDisplay::create(['targetEntityType' => $entity_type_id, 'bundle' => $bundle, 'status' => TRUE]);
                 foreach ($display_fields as $field_id => $field) {
                     $display->setComponent($field->definition['field_name'], ['type' => $field->options['type'], 'settings' => $field->options['settings']]);
                 }
                 // Let the display build the render array for the entities.
                 $display_build = $display->buildMultiple($bundle_entities);
                 // Collect the field render arrays and index them using our internal
                 // row indexes and field IDs.
                 foreach ($display_build as $row_index => $entity_build) {
                     foreach ($display_fields as $field_id => $field) {
                         $build[$row_index][$field_id] = !empty($entity_build[$field->definition['field_name']]) ? $entity_build[$field->definition['field_name']] : [];
                     }
                 }
             }
         }
     }
     return $build;
 }
コード例 #27
0
 /**
  * Tests the embedded references.
  */
 function testEmbeddedReferences()
 {
     // Create two reference fields, one to a translatable and untranslatable
     // node type, one only for a untranslatable. Only the first one should be
     // available.
     $field1 = FieldStorageConfig::create(array('field_name' => 'field1', 'entity_type' => 'node', 'type' => 'entity_reference', 'cardinality' => -1, 'settings' => array('target_type' => 'node')));
     $field1->save();
     $field2 = FieldStorageConfig::create(array('field_name' => 'field2', 'entity_type' => 'node', 'type' => 'entity_reference', 'cardinality' => -1, 'settings' => array('target_type' => 'node')));
     $field2->save();
     $this->createNodeType('untranslatable', 'Untranslatable', FALSE);
     // Create field instances on the content type.
     FieldConfig::create(array('field_storage' => $field1, 'bundle' => 'article', 'label' => 'Field 1', 'translatable' => FALSE, 'settings' => array()))->save();
     FieldConfig::create(array('field_storage' => $field1, 'bundle' => 'untranslatable', 'label' => 'Field 1', 'translatable' => FALSE, 'settings' => array()))->save();
     FieldConfig::create(array('field_storage' => $field2, 'bundle' => 'untranslatable', 'label' => 'Field 2', 'translatable' => FALSE, 'settings' => array()))->save();
     EntityViewDisplay::load('node.article.default')->setComponent('field1', ['type' => 'entity_reference_entity_view', 'settings' => ['view_mode' => 'teaser']])->save();
     $this->drupalGet('admin/tmgmt/settings');
     $checked_reference_fields = array('embedded_fields[node][field1]' => TRUE);
     $this->assertNoField('embedded_fields[node][field_image]');
     $this->assertNoField('embedded_fields[node][field_tags]');
     $this->assertNoField('embedded_fields[node][title]');
     $this->assertNoField('embedded_fields[node][uid]');
     $this->assertNoField('embedded_fields[node][field2]');
     $this->assertNoField('embedded_fields[node][type]');
     $this->drupalPostForm(NULL, $checked_reference_fields, t('Save configuration'));
     // Check if the save was successful.
     $this->assertText(t('The configuration options have been saved.'));
     $this->assertFieldChecked('edit-embedded-fields-node-field1');
     // Create translatable child node.
     $edit = ['title' => 'Child title', 'type' => 'article', 'langcode' => 'en'];
     $child_node = $this->createNode($edit);
     // Create translatable parent node.
     $edit = ['title' => 'Parent title', 'type' => 'article', 'langcode' => 'en'];
     $edit['field1'][]['target_id'] = $child_node->id();
     $parent_node = $this->createNode($edit);
     // Create a translation job.
     $job = $this->createJob('en', 'de');
     $job->translator = $this->default_translator->id();
     $job->save();
     $job_item = tmgmt_job_item_create('content', $parent_node->getEntityTypeId(), $parent_node->id(), array('tjid' => $job->id()));
     $job_item->save();
     $job->requestTranslation();
     // Visit preview page.
     $this->drupalGet(URL::fromRoute('entity.tmgmt_job_item.canonical', ['tmgmt_job_item' => $job_item->id()]));
     $this->clickLink(t('Preview'));
     // Check if parent and child nodes are translated.
     $this->assertText('de(de-ch): ' . $parent_node->getTitle());
     $this->assertText('de(de-ch): ' . $parent_node->body->value);
     $this->assertText('de(de-ch): ' . $child_node->getTitle());
     $this->assertText('de(de-ch): ' . $child_node->body->value);
 }
コード例 #28
0
ファイル: EntityViewBuilder.php プロジェクト: brstde/gap1
 /**
  * Returns an EntityViewDisplay for rendering an individual field.
  *
  * @param \Drupal\Core\Entity\EntityInterface $entity
  *   The entity.
  * @param string $field_name
  *   The field name.
  * @param string|array $display_options
  *   The display options passed to the viewField() method.
  *
  * @return \Drupal\Core\Entity\Display\EntityViewDisplayInterface
  */
 protected function getSingleFieldDisplay($entity, $field_name, $display_options)
 {
     if (is_string($display_options)) {
         // View mode: use the Display configured for the view mode.
         $view_mode = $display_options;
         $display = EntityViewDisplay::collectRenderDisplay($entity, $view_mode);
         // Hide all fields except the current one.
         foreach (array_keys($entity->getFieldDefinitions()) as $name) {
             if ($name != $field_name) {
                 $display->removeComponent($name);
             }
         }
     } else {
         // Array of custom display options: use a runtime Display for the
         // '_custom' view mode. Persist the displays created, to reduce the number
         // of objects (displays and formatter plugins) created when rendering a
         // series of fields individually for cases such as views tables.
         $entity_type_id = $entity->getEntityTypeId();
         $bundle = $entity->bundle();
         $key = $entity_type_id . ':' . $bundle . ':' . $field_name . ':' . crc32(serialize($display_options));
         if (!isset($this->singleFieldDisplays[$key])) {
             $this->singleFieldDisplays[$key] = EntityViewDisplay::create(array('targetEntityType' => $entity_type_id, 'bundle' => $bundle, 'status' => TRUE))->setComponent($field_name, $display_options);
         }
         $display = $this->singleFieldDisplays[$key];
     }
     return $display;
 }
コード例 #29
0
 /**
  * Tests CRUD for fields and fields fields with default images.
  */
 public function testDefaultImages()
 {
     $node_storage = $this->container->get('entity.manager')->getStorage('node');
     // Create files to use as the default images.
     $files = $this->drupalGetTestFiles('image');
     // Create 10 files so the default image fids are not a single value.
     for ($i = 1; $i <= 10; $i++) {
         $filename = $this->randomMachineName() . "{$i}";
         $desired_filepath = 'public://' . $filename;
         file_unmanaged_copy($files[0]->uri, $desired_filepath, FILE_EXISTS_ERROR);
         $file = File::create(['uri' => $desired_filepath, 'filename' => $filename, 'name' => $filename]);
         $file->save();
     }
     $default_images = array();
     foreach (array('field', 'field', 'field2', 'field_new', 'field_new') as $image_target) {
         $file = File::create((array) array_pop($files));
         $file->save();
         $default_images[$image_target] = $file;
     }
     // Create an image field and add an field to the article content type.
     $field_name = strtolower($this->randomMachineName());
     $storage_settings['default_image'] = array('uuid' => $default_images['field']->uuid(), 'alt' => '', 'title' => '', 'width' => 0, 'height' => 0);
     $field_settings['default_image'] = array('uuid' => $default_images['field']->uuid(), 'alt' => '', 'title' => '', 'width' => 0, 'height' => 0);
     $widget_settings = array('preview_image_style' => 'medium');
     $field = $this->createImageField($field_name, 'article', $storage_settings, $field_settings, $widget_settings);
     // The field default image id should be 2.
     $this->assertEqual($field->getSetting('default_image')['uuid'], $default_images['field']->uuid());
     // Also test \Drupal\field\Entity\FieldConfig::getSettings().
     $this->assertEqual($field->getSettings()['default_image']['uuid'], $default_images['field']->uuid());
     $field_storage = $field->getFieldStorageDefinition();
     // The field default image id should be 1.
     $this->assertEqual($field_storage->getSetting('default_image')['uuid'], $default_images['field']->uuid());
     // Also test \Drupal\field\Entity\FieldStorageConfig::getSettings().
     $this->assertEqual($field_storage->getSettings()['default_image']['uuid'], $default_images['field']->uuid());
     // Add another field with another default image to the page content type.
     $field2 = FieldConfig::create(['field_storage' => $field_storage, 'bundle' => 'page', 'label' => $field->label(), 'required' => $field->isRequired(), 'settings' => array('default_image' => array('uuid' => $default_images['field2']->uuid(), 'alt' => '', 'title' => '', 'width' => 0, 'height' => 0))]);
     $field2->save();
     $widget_settings = entity_get_form_display('node', $field->getTargetBundle(), 'default')->getComponent($field_name);
     entity_get_form_display('node', 'page', 'default')->setComponent($field_name, $widget_settings)->save();
     entity_get_display('node', 'page', 'default')->setComponent($field_name)->save();
     // Confirm the defaults are present on the article field settings form.
     $field_id = $field->id();
     $this->drupalGet("admin/structure/types/manage/article/fields/{$field_id}/storage");
     $this->assertFieldByXpath('//input[@name="settings[default_image][uuid][fids]"]', $default_images['field']->id(), format_string('Article image field default equals expected file ID of @fid.', array('@fid' => $default_images['field']->id())));
     // Confirm the defaults are present on the article field edit form.
     $this->drupalGet("admin/structure/types/manage/article/fields/{$field_id}");
     $this->assertFieldByXpath('//input[@name="settings[default_image][uuid][fids]"]', $default_images['field']->id(), format_string('Article image field field default equals expected file ID of @fid.', array('@fid' => $default_images['field']->id())));
     // Confirm the defaults are present on the page field settings form.
     $this->drupalGet("admin/structure/types/manage/page/fields/{$field_id}/storage");
     $this->assertFieldByXpath('//input[@name="settings[default_image][uuid][fids]"]', $default_images['field']->id(), format_string('Page image field default equals expected file ID of @fid.', array('@fid' => $default_images['field']->id())));
     // Confirm the defaults are present on the page field edit form.
     $field2_id = $field2->id();
     $this->drupalGet("admin/structure/types/manage/page/fields/{$field2_id}");
     $this->assertFieldByXpath('//input[@name="settings[default_image][uuid][fids]"]', $default_images['field2']->id(), format_string('Page image field field default equals expected file ID of @fid.', array('@fid' => $default_images['field2']->id())));
     // Confirm that the image default is shown for a new article node.
     $article = $this->drupalCreateNode(array('type' => 'article'));
     $article_built = $this->drupalBuildEntityView($article);
     $this->assertEqual($article_built[$field_name][0]['#item']->target_id, $default_images['field']->id(), format_string('A new article node without an image has the expected default image file ID of @fid.', array('@fid' => $default_images['field']->id())));
     // Also check that the field renders without warnings when the label is
     // hidden.
     EntityViewDisplay::load('node.article.default')->setComponent($field_name, array('label' => 'hidden', 'type' => 'image'))->save();
     $this->drupalGet('node/' . $article->id());
     // Confirm that the image default is shown for a new page node.
     $page = $this->drupalCreateNode(array('type' => 'page'));
     $page_built = $this->drupalBuildEntityView($page);
     $this->assertEqual($page_built[$field_name][0]['#item']->target_id, $default_images['field2']->id(), format_string('A new page node without an image has the expected default image file ID of @fid.', array('@fid' => $default_images['field2']->id())));
     // Upload a new default for the field storage.
     $default_image_settings = $field_storage->getSetting('default_image');
     $default_image_settings['uuid'] = $default_images['field_new']->uuid();
     $field_storage->setSetting('default_image', $default_image_settings);
     $field_storage->save();
     // Confirm that the new default is used on the article field settings form.
     $this->drupalGet("admin/structure/types/manage/article/fields/{$field_id}/storage");
     $this->assertFieldByXpath('//input[@name="settings[default_image][uuid][fids]"]', $default_images['field_new']->id(), format_string('Updated image field default equals expected file ID of @fid.', array('@fid' => $default_images['field_new']->id())));
     // Reload the nodes and confirm the field field defaults are used.
     $node_storage->resetCache(array($article->id(), $page->id()));
     $article_built = $this->drupalBuildEntityView($article = $node_storage->load($article->id()));
     $page_built = $this->drupalBuildEntityView($page = $node_storage->load($page->id()));
     $this->assertEqual($article_built[$field_name][0]['#item']->target_id, $default_images['field']->id(), format_string('An existing article node without an image has the expected default image file ID of @fid.', array('@fid' => $default_images['field']->id())));
     $this->assertEqual($page_built[$field_name][0]['#item']->target_id, $default_images['field2']->id(), format_string('An existing page node without an image has the expected default image file ID of @fid.', array('@fid' => $default_images['field2']->id())));
     // Upload a new default for the article's field field.
     $default_image_settings = $field->getSetting('default_image');
     $default_image_settings['uuid'] = $default_images['field_new']->uuid();
     $field->setSetting('default_image', $default_image_settings);
     $field->save();
     // Confirm the new field field default is used on the article field
     // admin form.
     $this->drupalGet("admin/structure/types/manage/article/fields/{$field_id}");
     $this->assertFieldByXpath('//input[@name="settings[default_image][uuid][fids]"]', $default_images['field_new']->id(), format_string('Updated article image field field default equals expected file ID of @fid.', array('@fid' => $default_images['field_new']->id())));
     // Reload the nodes.
     $node_storage->resetCache(array($article->id(), $page->id()));
     $article_built = $this->drupalBuildEntityView($article = $node_storage->load($article->id()));
     $page_built = $this->drupalBuildEntityView($page = $node_storage->load($page->id()));
     // Confirm the article uses the new default.
     $this->assertEqual($article_built[$field_name][0]['#item']->target_id, $default_images['field_new']->id(), format_string('An existing article node without an image has the expected default image file ID of @fid.', array('@fid' => $default_images['field_new']->id())));
     // Confirm the page remains unchanged.
     $this->assertEqual($page_built[$field_name][0]['#item']->target_id, $default_images['field2']->id(), format_string('An existing page node without an image has the expected default image file ID of @fid.', array('@fid' => $default_images['field2']->id())));
     // Confirm the default image is shown on the node form.
     $file = File::load($default_images['field_new']->id());
     $this->drupalGet('node/add/article');
     $this->assertRaw($file->getFilename());
     // Remove the instance default from articles.
     $default_image_settings = $field->getSetting('default_image');
     $default_image_settings['uuid'] = 0;
     $field->setSetting('default_image', $default_image_settings);
     $field->save();
     // Confirm the article field field default has been removed.
     $this->drupalGet("admin/structure/types/manage/article/fields/{$field_id}");
     $this->assertFieldByXpath('//input[@name="settings[default_image][uuid][fids]"]', '', 'Updated article image field field default has been successfully removed.');
     // Reload the nodes.
     $node_storage->resetCache(array($article->id(), $page->id()));
     $article_built = $this->drupalBuildEntityView($article = $node_storage->load($article->id()));
     $page_built = $this->drupalBuildEntityView($page = $node_storage->load($page->id()));
     // Confirm the article uses the new field (not field) default.
     $this->assertEqual($article_built[$field_name][0]['#item']->target_id, $default_images['field_new']->id(), format_string('An existing article node without an image has the expected default image file ID of @fid.', array('@fid' => $default_images['field_new']->id())));
     // Confirm the page remains unchanged.
     $this->assertEqual($page_built[$field_name][0]['#item']->target_id, $default_images['field2']->id(), format_string('An existing page node without an image has the expected default image file ID of @fid.', array('@fid' => $default_images['field2']->id())));
     $non_image = $this->drupalGetTestFiles('text');
     $this->drupalPostForm(NULL, array('files[settings_default_image_uuid]' => drupal_realpath($non_image[0]->uri)), t("Upload"));
     $this->assertText('The specified file text-0.txt could not be uploaded.');
     $this->assertText('Only files with the following extensions are allowed: png gif jpg jpeg.');
     // Confirm the default image is shown on the node form.
     $file = File::load($default_images['field_new']->id());
     $this->drupalGet('node/add/article');
     $this->assertRaw($file->getFilename());
 }
コード例 #30
0
 /**
  * Tests the file_size field formatter.
  */
 public function testFormatterFileSize()
 {
     $entity_display = EntityViewDisplay::create(['targetEntityType' => 'file', 'bundle' => 'file']);
     $entity_display->setComponent('filesize', ['type' => 'file_size']);
     $expected = ['10 bytes', '200 bytes', '39.06 KB', '7.63 MB'];
     foreach (array_values($this->files) as $i => $file) {
         $build = $entity_display->build($file);
         $this->assertEqual($expected[$i], $build['filesize'][0]['#markup']);
     }
 }