/**
  * {@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"]);
 }
  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->adminUser = $this->drupalCreateUser([
      'administer products',
      'administer stores',
      'access administration pages',
    ]);
    $this->drupalLogin($this->adminUser);

    $this->referenceField = FieldStorageConfig::loadByName('commerce_product', 'stores');
    $display = EntityFormDisplay::load('commerce_product.default.default');
    $display->setComponent('stores', [
      'type' => 'entity_select',
      'settings' => [
        'autocomplete_threshold' => 2,
      ],
    ])->save();

    $variation = $this->createEntity('commerce_product_variation', [
     'type' => 'default',
      'sku' => strtolower($this->randomMachineName()),
    ]);
    $this->product = $this->createEntity('commerce_product', [
      'type' => 'default',
      'title' => $this->randomMachineName(),
      'variations' => [$variation],
    ]);
  }
 /**
  * Asserts a display entity.
  *
  * @param string $id
  *   The entity ID.
  * @param string $component
  *   The ID of the form component.
  */
 protected function assertDisplay($id, $component_id)
 {
     $component = EntityFormDisplay::load($id)->getComponent($component_id);
     $this->assertTrue(is_array($component));
     $this->assertIdentical('comment_default', $component['type']);
     $this->assertIdentical(20, $component['weight']);
 }
 /**
  * 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');
 }
 /**
  * Asserts various aspects of a particular component of a form display.
  *
  * @param string $display_id
  *   The form display ID.
  * @param string $component_id
  *   The component ID.
  * @param string $widget_type
  *   The expected widget type.
  * @param string $weight
  *   The expected weight of the component.
  */
 protected function assertComponent($display_id, $component_id, $widget_type, $weight)
 {
     $component = EntityFormDisplay::load($display_id)->getComponent($component_id);
     $this->assertTrue(is_array($component));
     $this->assertIdentical($widget_type, $component['type']);
     $this->assertIdentical($weight, $component['weight']);
 }
 /**
  * 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'));
 }
 /**
  * Asserts a display entity.
  *
  * @param string $id
  *   The entity ID.
  */
 protected function assertDisplay($id)
 {
     $component = EntityFormDisplay::load($id)->getComponent('subject');
     $this->assertTrue(is_array($component));
     $this->assertIdentical('string_textfield', $component['type']);
     $this->assertIdentical(10, $component['weight']);
 }
 /**
  * Tests the field's entity form display settings.
  */
 public function testEntityFormDisplaySettings()
 {
     $component = EntityFormDisplay::load('user.user.default')->getComponent('user_picture');
     $this->assertIdentical('image_image', $component['type']);
     $this->assertIdentical('throbber', $component['settings']['progress_indicator']);
     $this->assertIdentical('thumbnail', $component['settings']['preview_image_style']);
 }
 /**
  * Tests comment variables migrated into an entity display.
  */
 public function testCommentEntityFormDisplay()
 {
     foreach (['page', 'article', 'story'] as $type) {
         $component = EntityFormDisplay::load('node.' . $type . '.default')->getComponent('comment');
         $this->assertIdentical('comment_default', $component['type']);
         $this->assertIdentical(20, $component['weight']);
     }
 }
 /**
  * Tests comment subject variable migrated into an entity display.
  */
 public function testCommentEntityFormDisplay()
 {
     $component = EntityFormDisplay::load('comment.comment.default')->getComponent('subject');
     $this->assertIdentical('string_textfield', $component['type']);
     $this->assertIdentical(10, $component['weight']);
     $component = EntityFormDisplay::load('comment.comment_no_subject.default')->getComponent('subject');
     $this->assertNull($component);
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->referenceField = FieldStorageConfig::loadByName('commerce_product', 'stores');
     $display = EntityFormDisplay::load('commerce_product.default.default');
     $display->setComponent('stores', ['type' => 'commerce_entity_select', 'settings' => ['autocomplete_threshold' => 2]])->save();
     $variation = $this->createEntity('commerce_product_variation', ['type' => 'default', 'sku' => strtolower($this->randomMachineName())]);
     $this->product = $this->createEntity('commerce_product', ['type' => 'default', 'title' => $this->randomMachineName(), 'variations' => [$variation]]);
 }
 /**
  * Tests the Drupal 6 vocabulary-node type association to Drupal 8 migration.
  */
 public function testVocabularyEntityFormDisplay()
 {
     // Test that the field exists.
     $component = EntityFormDisplay::load('node.page.default')->getComponent('tags');
     $this->assertIdentical('options_select', $component['type']);
     $this->assertIdentical(20, $component['weight']);
     // Test the Id map.
     $this->assertIdentical(array('node', 'article', 'default', 'tags'), Migration::load('d6_vocabulary_entity_form_display')->getIdMap()->lookupDestinationID(array(4, 'article')));
 }
 /**
  * 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']);
 }
Beispiel #14
0
 /**
  * Creates a date test field.
  */
 protected function createField()
 {
     $field_name = Unicode::strtolower($this->randomMachineName());
     $type = $this->getTestFieldType();
     $widget_type = $formatter_type = $type . '_default';
     $this->fieldStorage = FieldStorageConfig::create(['field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => $type, 'settings' => ['datetime_type' => DateRangeItem::DATETIME_TYPE_DATE]]);
     $this->fieldStorage->save();
     $this->field = FieldConfig::create(['field_storage' => $this->fieldStorage, 'bundle' => 'entity_test', 'required' => TRUE]);
     $this->field->save();
     EntityFormDisplay::load('entity_test.entity_test.default')->setComponent($field_name, ['type' => $widget_type])->save();
     $this->displayOptions = ['type' => $formatter_type, 'label' => 'hidden', 'settings' => ['format_type' => 'medium'] + $this->defaultSettings];
     EntityViewDisplay::create(['targetEntityType' => $this->field->getTargetEntityTypeId(), 'bundle' => $this->field->getTargetBundle(), 'mode' => 'full', 'status' => TRUE])->setComponent($field_name, $this->displayOptions)->save();
 }
 /**
  * Tests the Drupal 6 vocabulary-node type association to Drupal 8 migration.
  */
 public function testVocabularyEntityFormDisplay()
 {
     // Test that the field exists.
     $component = EntityFormDisplay::load('node.page.default')->getComponent('tags');
     $this->assertIdentical('options_select', $component['type']);
     $this->assertIdentical(20, $component['weight']);
     // Test the Id map.
     $this->assertIdentical(array('node', 'article', 'default', 'tags'), $this->getMigration('d6_vocabulary_entity_form_display')->getIdMap()->lookupDestinationID(array(4, 'article')));
     // Test the term widget tags setting.
     $entity_form_display = EntityFormDisplay::load('node.story.default');
     $this->assertIdentical($entity_form_display->getComponent('vocabulary_1_i_0_')['type'], 'options_select');
     $this->assertIdentical($entity_form_display->getComponent('vocabulary_2_i_1_')['type'], 'entity_reference_autocomplete_tags');
 }
 /**
  * Tests the Drupal 6 upload settings to Drupal 8 entity form display migration.
  */
 public function testUploadEntityFormDisplay()
 {
     $display = EntityFormDisplay::load('node.page.default');
     $component = $display->getComponent('upload');
     $this->assertIdentical('file_generic', $component['type']);
     $display = EntityFormDisplay::load('node.story.default');
     $component = $display->getComponent('upload');
     $this->assertIdentical('file_generic', $component['type']);
     // Assure this doesn't exist.
     $display = EntityFormDisplay::load('node.article.default');
     $component = $display->getComponent('upload');
     $this->assertTrue(is_null($component));
     $this->assertIdentical(array('node', 'page', 'default', 'upload'), Migration::load('d6_upload_entity_form_display')->getIdMap()->lookupDestinationID(array('page')));
 }
Beispiel #17
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.'));
 }
 /**
  * Tests migration of user profile fields.
  */
 public function testUserProfileEntityFormDisplay()
 {
     $display = EntityFormDisplay::load('user.user.default');
     // Test a text field.
     $component = $display->getComponent('profile_color');
     $this->assertIdentical('text_textfield', $component['type']);
     // Test a list field.
     $component = $display->getComponent('profile_bands');
     $this->assertIdentical('text_textfield', $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'));
     // Test that a checkbox field has the proper display label setting.
     $component = $display->getComponent('profile_love_migrations');
     $this->assertIdentical('boolean_checkbox', $component['type']);
     $this->assertIdentical(true, $component['settings']['display_label']);
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->drupalCreateContentType(['type' => 'article']);
     $this->adminUser = $this->drupalCreateUser(['create article content', 'edit own article content', 'administer content types', 'administer node fields']);
     $this->drupalLogin($this->adminUser);
     // Add the address field to the article content type.
     $field_storage = FieldStorageConfig::create(['field_name' => 'field_address', 'entity_type' => 'node', 'type' => 'address']);
     $field_storage->save();
     $this->field = FieldConfig::create(['field_storage' => $field_storage, 'bundle' => 'article', 'label' => 'Address']);
     $this->field->save();
     // Set article's form display.
     $this->formDisplay = EntityFormDisplay::load('node.article.default');
     if (!$this->formDisplay) {
         $this->formDisplay = EntityFormDisplay::create(['targetEntityType' => 'node', 'bundle' => 'article', 'mode' => 'default', 'status' => TRUE])->save();
     }
     $this->formDisplay->setComponent($this->field->getName(), ['type' => 'address_default', 'settings' => ['default_country' => 'US']])->save();
     $this->nodeAddUrl = 'node/add/article';
     $this->fieldConfigUrl = 'admin/structure/types/manage/article/fields/node.article.' . $this->field->getName();
     $this->countryRepository = \Drupal::service('address.country_repository');
     $this->subdivisionRepository = \Drupal::service('address.subdivision_repository');
     $this->addressFormatRepository = \Drupal::service('address.address_format_repository');
 }
  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    // Create a vocabulary.
    $this->vocabulary = $this->createVocabulary();

    // Create 11 terms, which have some sub-string in common, in a
    // non-alphabetical order, so that we will have more than 10 matches later
    // when we test the correct number of results is returned, and we can test
    // the order of the results. The location of the sub-string to match varies
    // also, since it should not be necessary to start with the sub-string to
    // match it. Save term IDs to reuse later.
    $termNames = [
      'aaa 20 bbb',
      'aaa 70 bbb',
      'aaa 10 bbb',
      'aaa 12 bbb',
      'aaa 40 bbb',
      'aaa 11 bbb',
      'aaa 30 bbb',
      'aaa 50 bbb',
      'aaa 80',
      'aaa 90',
      'bbb 60 aaa',
    ];
    foreach ($termNames as $termName) {
      $term = $this->createTerm($this->vocabulary, ['name' => $termName]);
      $this->termIds[$termName] = $term->id();
    }

    // Create a taxonomy_term_reference field on the article Content Type that
    // uses a taxonomy_autocomplete widget.
    $this->fieldName = Unicode::strtolower($this->randomMachineName());
    FieldStorageConfig::create([
      'field_name' => $this->fieldName,
      'entity_type' => 'node',
      'type' => 'entity_reference',
      'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
      'settings' => [
        'target_type' => 'taxonomy_term',
      ],
    ])->save();
    FieldConfig::create([
      'field_name' => $this->fieldName,
      'bundle' => 'article',
      'entity_type' => 'node',
      'settings' => [
        'handler' => 'default',
        'handler_settings' => [
          // Restrict selection of terms to a single vocabulary.
          'target_bundles' => [
            $this->vocabulary->id() => $this->vocabulary->id(),
          ],
        ],
      ],
    ])->save();
    EntityFormDisplay::load('node.article.default')
      ->setComponent($this->fieldName, [
        'type' => 'entity_reference_autocomplete',
      ])
      ->save();
    EntityViewDisplay::load('node.article.default')
      ->setComponent($this->fieldName, [
        'type' => 'entity_reference_label',
      ])
      ->save();

    // Create a user and then login.
    $this->adminUser = $this->drupalCreateUser(['create article content']);
    $this->drupalLogin($this->adminUser);

    // Retrieve the autocomplete url.
    $this->drupalGet('node/add/article');
    $result = $this->xpath('//input[@name="' . $this->fieldName . '[0][target_id]"]');
    $this->autocompleteUrl = $this->getAbsoluteUrl($result[0]['data-autocomplete-path']);
  }
  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    /** @var \Drupal\contact\ContactFormInterface $contact_form */
    $contact_form = $this->entity;
    // Get the original ID.
    $original_id = $contact_form->getOriginalId();
    $new_id = $contact_form->id();

    // Create the new form.
    $contact_form = $contact_form->createDuplicate();
    $contact_form->set('id', $new_id);
    $contact_form->save();

    // Clone configurable fields.
    foreach ($this->fieldManager->getFieldDefinitions('contact_message', $original_id) as $field) {
      if ($field instanceof BaseFieldDefinition) {
        continue;
      }
      if ($this->moduleHandler->moduleExists('field')) {
        if ($config = $field->getConfig($original_id)) {
          $new_config = FieldConfig::create([
            'bundle' => $contact_form->id(),
            'uuid' => NULL,
          ] + $config->toArray());
          $new_config->save();
        }
      }
    }

    // Clone the entity form display.
    $display = EntityFormDisplay::load('contact_message.' . $original_id . '.default');
    EntityFormDisplay::create([
      'bundle' => $contact_form->id(),
      'uuid' => NULL,
    ] + $display->toArray())->save();

    // Clone the entity view display.
    $display = EntityViewDisplay::load('contact_message.' . $original_id . '.default');
    EntityViewDisplay::create([
      'bundle' => $contact_form->id(),
      'uuid' => NULL,
    ] + $display->toArray())->save();

    // Redirect and show messge.
    $form_state->setRedirect('entity.contact_form.edit_form', ['contact_form' => $contact_form->id()]);
    $edit_link = $this->entity->link($this->t('Edit'));
    drupal_set_message($this->t('Contact form %label has been added.', array('%label' => $contact_form->label())));
    $this->logger('contact')->notice('Contact form %label has been added.', array('%label' => $contact_form->label(), 'link' => $edit_link));
  }
 /**
  * Test that migrated view modes can be loaded using D8 API's.
  */
 public function testWidgetSettings()
 {
     // Test the config can be loaded.
     $form_display = EntityFormDisplay::load('node.story.default');
     $this->assertIdentical(FALSE, is_null($form_display), "Form display node.story.default loaded with config.");
     // Text field.
     $component = $form_display->getComponent('field_test');
     $expected = array('weight' => 1, 'type' => 'text_textfield');
     $expected['settings'] = array('size' => 60, 'placeholder' => '');
     $expected['third_party_settings'] = array();
     $this->assertIdentical($expected, $component, 'Text field settings are correct.');
     // Integer field.
     $component = $form_display->getComponent('field_test_two');
     $expected['type'] = 'number';
     $expected['weight'] = 1;
     $expected['settings'] = array('placeholder' => '');
     $this->assertIdentical($expected, $component);
     // Float field.
     $component = $form_display->getComponent('field_test_three');
     $expected['weight'] = 2;
     $this->assertIdentical($expected, $component);
     // Email field.
     $component = $form_display->getComponent('field_test_email');
     $expected['type'] = 'email_default';
     $expected['weight'] = 6;
     $this->assertIdentical($expected, $component);
     // Link field.
     $component = $form_display->getComponent('field_test_link');
     $this->assertIdentical('link_default', $component['type']);
     $this->assertIdentical(7, $component['weight']);
     $this->assertFalse(array_filter($component['settings']));
     // File field.
     $component = $form_display->getComponent('field_test_filefield');
     $expected['type'] = 'file_generic';
     $expected['weight'] = 8;
     $expected['settings'] = array('progress_indicator' => 'bar');
     $this->assertIdentical($expected, $component);
     // Image field.
     $component = $form_display->getComponent('field_test_imagefield');
     $expected['type'] = 'image_image';
     $expected['weight'] = 9;
     $expected['settings'] = array('progress_indicator' => 'bar', 'preview_image_style' => 'thumbnail');
     $this->assertIdentical($expected, $component);
     // Phone field.
     $component = $form_display->getComponent('field_test_phone');
     $expected['type'] = 'telephone_default';
     $expected['weight'] = 13;
     $expected['settings'] = array('placeholder' => '');
     $this->assertIdentical($expected, $component);
     // Date fields.
     $component = $form_display->getComponent('field_test_date');
     $expected['type'] = 'datetime_default';
     $expected['weight'] = 10;
     $expected['settings'] = array();
     $this->assertIdentical($expected, $component);
     $component = $form_display->getComponent('field_test_datestamp');
     $expected['weight'] = 11;
     $this->assertIdentical($expected, $component);
     $component = $form_display->getComponent('field_test_datetime');
     $expected['weight'] = 12;
     $this->assertIdentical($expected, $component);
 }
 /**
  * {@inheritdoc}
  */
 public function createNewReferenceField(array $new_field_settings, ScheduledUpdateTypeInterface $scheduled_update_type)
 {
     $entity_type = $scheduled_update_type->getUpdateEntityType();
     $field_name = $new_field_settings['field_name'];
     $label = $new_field_settings['label'];
     if ($new_field_settings['cardinality'] == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
         $new_field_settings['cardinality_number'] = FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED;
     }
     $field_storage_values = ['field_name' => $field_name, 'entity_type' => $entity_type, 'type' => 'entity_reference', 'translatable' => FALSE, 'settings' => ['target_type' => 'scheduled_update'], 'cardinality' => $new_field_settings['cardinality_number']];
     FieldStorageConfig::create($field_storage_values)->save();
     $bundles = array_filter($new_field_settings['bundles']);
     foreach ($bundles as $bundle) {
         $field_values = ['field_name' => $field_name, 'entity_type' => $entity_type, 'bundle' => $bundle, 'label' => $label, 'translatable' => FALSE, 'settings' => ['handler_settings' => ['target_bundles' => [$scheduled_update_type->id()]]]];
         $field = FieldConfig::create($field_values);
         $field->save();
         /** @var EntityFormDisplay $formDisplay */
         $formDisplay = EntityFormDisplay::load("{$entity_type}.{$bundle}.default");
         $form_options = ['type' => 'inline_entity_form_complex', 'weight' => '11', 'settings' => ['override_labels' => TRUE, 'label_singular' => $label, 'label_plural' => $label . 's', 'allow_new' => TRUE, 'match_operator' => 'CONTAINS', 'allow_existing' => FALSE]];
         $formDisplay->setComponent($field_name, $form_options);
         $formDisplay->save();
     }
 }
 /**
  * Tests ability to expose line item fields on the add to cart form.
  */
 public function testExposedLineItemFields()
 {
     /** @var \Drupal\Core\Entity\Entity\EntityFormDisplay $line_item_form_display */
     $line_item_form_display = EntityFormDisplay::load('commerce_line_item.product_variation.add_to_cart');
     $line_item_form_display->setComponent('quantity', ['type' => 'number']);
     $line_item_form_display->save();
     // Get the existing product page and submit Add to cart form.
     $this->postAddToCart($this->variation->getProduct(), ['quantity[0][value]' => 3]);
     // Check if the quantity was increased for the existing line item.
     $this->cart = Order::load($this->cart->id());
     $line_items = $this->cart->getLineItems();
     /** @var \Drupal\commerce_order\Entity\LineItemInterface $line_item */
     $line_item = $line_items[0];
     $this->assertEqual($line_item->getTitle(), $this->variation->getLineItemTitle());
     $this->assertTrue($line_item->getQuantity() == 3, t('The product @product has been added to cart.', ['@product' => $line_item->getTitle()]));
 }
 /**
  * Tests the behavior of a field component for a base field.
  */
 public function testBaseFieldComponent()
 {
     $display = EntityFormDisplay::create(array('targetEntityType' => 'entity_test_base_field_display', 'bundle' => 'entity_test_base_field_display', 'mode' => 'default'));
     // Check that default options are correctly filled in.
     $formatter_settings = \Drupal::service('plugin.manager.field.widget')->getDefaultSettings('text_textfield');
     $expected = array('test_no_display' => NULL, 'test_display_configurable' => array('type' => 'text_textfield', 'settings' => $formatter_settings, 'third_party_settings' => array(), 'weight' => 10), 'test_display_non_configurable' => array('type' => 'text_textfield', 'settings' => $formatter_settings, 'third_party_settings' => array(), 'weight' => 11));
     foreach ($expected as $field_name => $options) {
         $this->assertEqual($display->getComponent($field_name), $options);
     }
     // Check that saving the display only writes data for fields whose display
     // is configurable.
     $display->save();
     $config = $this->config('core.entity_form_display.' . $display->id());
     $data = $config->get();
     $this->assertFalse(isset($data['content']['test_no_display']));
     $this->assertFalse(isset($data['hidden']['test_no_display']));
     $this->assertEqual($data['content']['test_display_configurable'], $expected['test_display_configurable']);
     $this->assertFalse(isset($data['content']['test_display_non_configurable']));
     $this->assertFalse(isset($data['hidden']['test_display_non_configurable']));
     // Check that defaults are correctly filled when loading the display.
     $display = EntityFormDisplay::load($display->id());
     foreach ($expected as $field_name => $options) {
         $this->assertEqual($display->getComponent($field_name), $options);
     }
     // Check that data manually written for fields whose display is not
     // configurable is discarded when loading the display.
     $data['content']['test_display_non_configurable'] = $expected['test_display_non_configurable'];
     $data['content']['test_display_non_configurable']['weight']++;
     $config->setData($data)->save();
     $display = EntityFormDisplay::load($display->id());
     foreach ($expected as $field_name => $options) {
         $this->assertEqual($display->getComponent($field_name), $options);
     }
 }
 /**
  * Sets the Paragraphs widget add mode.
  *
  * @param string $content_type
  *   Content type name where to set the widget mode.
  * @param string $paragraphs_field
  *   Paragraphs field to change the mode.
  * @param string $mode
  *   Mode to be set. ('dropdown', 'select' or 'button').
  */
 protected function setAddMode($content_type, $paragraphs_field, $mode)
 {
     $form_display = EntityFormDisplay::load('node.' . $content_type . '.default')->setComponent($paragraphs_field, ['type' => 'entity_reference_paragraphs', 'settings' => ['add_mode' => $mode]]);
     $form_display->save();
 }
Beispiel #27
0
 /**
  * Tests components dependencies additions.
  */
 public function testComponentDependencies()
 {
     $this->enableModules(['dblog', 'color']);
     $this->installSchema('dblog', ['watchdog']);
     $this->installEntitySchema('user');
     /** @var \Drupal\user\RoleInterface[] $roles */
     $roles = [];
     // Create two arbitrary user roles.
     for ($i = 0; $i < 2; $i++) {
         $roles[$i] = Role::create(['id' => Unicode::strtolower($this->randomMachineName()), 'label' => $this->randomString()]);
         $roles[$i]->save();
     }
     // Create a field of type 'test_field' attached to 'entity_test'.
     $field_name = Unicode::strtolower($this->randomMachineName());
     FieldStorageConfig::create(['field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => 'test_field'])->save();
     FieldConfig::create(['field_name' => $field_name, 'entity_type' => 'entity_test', 'bundle' => 'entity_test'])->save();
     // Create a new form display without components.
     /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
     $form_display = EntityFormDisplay::create(['targetEntityType' => 'entity_test', 'bundle' => 'entity_test', 'mode' => 'default']);
     $form_display->save();
     $dependencies = ['user.role.' . $roles[0]->id(), 'user.role.' . $roles[1]->id()];
     // The config object should not depend on none of the two $roles.
     $this->assertNoDependency('config', $dependencies[0], $form_display);
     $this->assertNoDependency('config', $dependencies[1], $form_display);
     // Add a widget of type 'test_field_widget'.
     $component = ['type' => 'test_field_widget', 'settings' => ['test_widget_setting' => $this->randomString(), 'role' => $roles[0]->id(), 'role2' => $roles[1]->id()], 'third_party_settings' => ['color' => ['foo' => 'bar']]];
     $form_display->setComponent($field_name, $component);
     $form_display->save();
     // Now, the form display should depend on both user roles $roles.
     $this->assertDependency('config', $dependencies[0], $form_display);
     $this->assertDependency('config', $dependencies[1], $form_display);
     // The form display should depend on 'color' module.
     $this->assertDependency('module', 'color', $form_display);
     // Delete the first user role entity.
     $roles[0]->delete();
     // Reload the form display.
     $form_display = EntityFormDisplay::load($form_display->id());
     // The display exists.
     $this->assertFalse(empty($form_display));
     // The form display should not depend on $role[0] anymore.
     $this->assertNoDependency('config', $dependencies[0], $form_display);
     // The form display should depend on 'anonymous' user role.
     $this->assertDependency('config', 'user.role.anonymous', $form_display);
     // The form display should depend on 'color' module.
     $this->assertDependency('module', 'color', $form_display);
     // Manually trigger the removal of configuration belonging to the module
     // because KernelTestBase::disableModules() is not aware of this.
     $this->container->get('config.manager')->uninstall('module', 'color');
     // Uninstall 'color' module.
     $this->disableModules(['color']);
     // Reload the form display.
     $form_display = EntityFormDisplay::load($form_display->id());
     // The display exists.
     $this->assertFalse(empty($form_display));
     // The component is still enabled.
     $this->assertNotNull($form_display->getComponent($field_name));
     // The form display should not depend on 'color' module anymore.
     $this->assertNoDependency('module', 'color', $form_display);
     // Delete the 2nd user role entity.
     $roles[1]->delete();
     // Reload the form display.
     $form_display = EntityFormDisplay::load($form_display->id());
     // The display exists.
     $this->assertFalse(empty($form_display));
     // The component has been disabled.
     $this->assertNull($form_display->getComponent($field_name));
     $this->assertTrue($form_display->get('hidden')[$field_name]);
     // The correct warning message has been logged.
     $arguments = ['@display' => (string) t('Entity form display'), '@id' => $form_display->id(), '@name' => $field_name];
     $logged = (bool) Database::getConnection()->select('watchdog', 'w')->fields('w', ['wid'])->condition('type', 'system')->condition('message', "@display '@id': Component '@name' was disabled because its settings depend on removed dependencies.")->condition('variables', serialize($arguments))->execute()->fetchAll();
     $this->assertTrue($logged);
 }
Beispiel #28
0
 /**
  * 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.'));
 }
Beispiel #29
0
  /**
   * Create a form display for a newly clone field.
   *
   * This function attempts to use same setting settings as the source field.
   *
   * @param \Drupal\scheduled_updates\ScheduledUpdateTypeInterface $scheduled_update_type
   * @param $field_name
   * @param $field_config_id
   * @param $entity_type
   * @param $definition
   *  Source field definition
   * @param $new_field_name
   */
  protected function createFormDisplay(ScheduledUpdateTypeInterface $scheduled_update_type, $field_config_id, FieldStorageDefinitionInterface $definition, $new_field_name) {
    $destination_bundle = $scheduled_update_type->id();
    $field_name = $definition->getName();
    $entity_type = $scheduled_update_type->getUpdateEntityType();
    /** @var EntityFormDisplay $destination_form_display */
    $destination_form_display = EntityFormDisplay::load("scheduled_update.$destination_bundle.default");
    if (empty($destination_form_display)) {
      $destination_form_display = EntityFormDisplay::create([
        'targetEntityType' => 'scheduled_update',
        'bundle' => $destination_bundle,
        'mode' => 'default',
        'status' => TRUE,
      ]);
    }
    $display_options = [];
    if ($field_config_id) {
      $parts = explode('.', $field_config_id);
      $source_bundle = $parts[1];
      /** @var EntityFormDisplay $source_form_display */
      $source_form_display = EntityFormDisplay::load("$entity_type.$source_bundle.default");

      $display_options = $source_form_display->getComponent($field_name);
    }
    else {
      if ($definition instanceof BaseFieldDefinition) {
        $display_options = $definition->getDisplayOptions('form');
        if (empty($display_options)) {
          if ($definition->getType()) {
            // Provide default display for base boolean fields that don't have their own form display
            $display_options = [
              'type' => 'boolean_checkbox',
              'settings' => ['display_label' => TRUE],
            ];
          }
        }
      }
    }
    if (empty($display_options)) {
      $display_options = [];
    }
    if ($destination_form_display) {
      $destination_form_display->setComponent($new_field_name, $display_options);
      $destination_form_display->save();
    }
    else {
      // Alert user if display options could not be created.
      // @todo Create default display options even none on source.
      drupal_set_message(
        $this->t(
          'Form display options could not be created for @field they will have to be created manually.',
          ['@field' => $field_name]
        ),
        'warning');
    }
  }