public function testRoleEntityClone() {
    $edit = [
      'label' => 'Test role for clone',
      'id' => 'test_role_for_clone',
    ];
    $this->drupalPostForm("/admin/people/roles/add", $edit, t('Save'));

    $roles = \Drupal::entityTypeManager()
      ->getStorage('user_role')
      ->loadByProperties([
        'id' => $edit['id'],
      ]);
    $role = reset($roles);

    $edit = [
      'id' => 'test_role_cloned',
      'label' => 'Test role cloned',
    ];
    $this->drupalPostForm('entity_clone/user_role/' . $role->id(), $edit, t('Clone'));

    $roles = \Drupal::entityTypeManager()
      ->getStorage('user_role')
      ->loadByProperties([
        'id' => $edit['id'],
      ]);
    $role = reset($roles);
    $this->assertTrue($role, 'Test role cloned found in database.');
  }
  public function testDateFormatEntityClone() {
    $edit = [
      'label' => 'Test date format for clone',
      'id' => 'test_date_format_for_clone',
      'date_format_pattern' => 'Y m d',
    ];
    $this->drupalPostForm("admin/config/regional/date-time/formats/add", $edit, t('Add format'));

    $date_formats = \Drupal::entityTypeManager()
      ->getStorage('date_format')
      ->loadByProperties([
        'id' => $edit['id'],
      ]);
    $date_format = reset($date_formats);

    $edit = [
      'id' => 'test_date_format_cloned',
      'label' => 'Test date format cloned',
    ];
    $this->drupalPostForm('entity_clone/date_format/' . $date_format->id(), $edit, t('Clone'));

    $date_formats = \Drupal::entityTypeManager()
      ->getStorage('date_format')
      ->loadByProperties([
        'id' => $edit['id'],
      ]);
    $date_format = reset($date_formats);
    $this->assertTrue($date_format, 'Test date format cloned found in database.');
  }
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function getParentEntity()
 {
     if (!isset($this->get('parent_type')->value) || !isset($this->get('parent_id')->value)) {
         return NULL;
     }
     return \Drupal::entityTypeManager()->getStorage($this->get('parent_type')->value)->load($this->get('parent_id')->value);
 }
 /**
  * Tests enabling moderation on an existing node-type, with content.
  */
 public function testEnablingOnExistingContent()
 {
     // Create a node type that is not moderated.
     $this->drupalLogin($this->adminUser);
     $this->createContentTypeFromUi('Not moderated', 'not_moderated');
     $this->grantUserPermissionToCreateContentOfType($this->adminUser, 'not_moderated');
     // Create content.
     $this->drupalGet('node/add/not_moderated');
     $this->drupalPostForm(NULL, ['title[0][value]' => 'Test'], t('Save and publish'));
     $this->assertText('Not moderated Test has been created.');
     // Now enable moderation state.
     $this->enableModerationThroughUi('not_moderated', ['draft', 'needs_review', 'published'], 'draft');
     // And make sure it works.
     $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['title' => 'Test']);
     if (empty($nodes)) {
         $this->fail('Could not load node with title Test');
         return;
     }
     $node = reset($nodes);
     $this->drupalGet('node/' . $node->id());
     $this->assertResponse(200);
     $this->assertLinkByHref('node/' . $node->id() . '/edit');
     $this->drupalGet('node/' . $node->id() . '/edit');
     $this->assertResponse(200);
     $this->assertRaw('Save and Create New Draft');
     $this->assertNoRaw('Save and publish');
 }
 /**
  * A node type without moderation state enabled.
  */
 public function testEnablingOnExistingContent()
 {
     $this->drupalLogin($this->adminUser);
     $this->createContentTypeFromUI('Not moderated', 'not_moderated');
     $this->grantUserPermissionToCreateContentOfType($this->adminUser, 'not_moderated');
     $this->drupalGet('node/add/not_moderated');
     $this->drupalPostForm(NULL, ['title[0][value]' => 'Test'], t('Save and publish'));
     $this->assertText('Not moderated Test has been created.');
     // Now enable moderation state.
     $this->drupalGet('admin/structure/types/manage/not_moderated/moderation');
     $this->drupalPostForm(NULL, ['enable_moderation_state' => 1, 'allowed_moderation_states[draft]' => 1, 'allowed_moderation_states[needs_review]' => 1, 'allowed_moderation_states[published]' => 1, 'default_moderation_state' => 'draft'], t('Save'));
     $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['title' => 'Test']);
     if (empty($nodes)) {
         $this->fail('Could not load node with title Test');
         return;
     }
     $node = reset($nodes);
     $this->drupalGet('node/' . $node->id());
     $this->assertResponse(200);
     $this->assertLinkByHref('node/' . $node->id() . '/edit');
     $this->drupalGet('node/' . $node->id() . '/edit');
     $this->assertResponse(200);
     $this->assertRaw('Save and Create New Draft');
     $this->assertNoRaw('Save and publish');
 }
  public function testSearchPageEntityClone() {
    $edit = [
      'label' => 'Test search page for clone',
      'id' => 'test_search_page_for_clone',
      'path' => 'test_search_page_for_clone_url',
    ];
    $this->drupalPostForm("/admin/config/search/pages/add/node_search", $edit, t('Add search page'));

    $search_pages = \Drupal::entityTypeManager()
      ->getStorage('search_page')
      ->loadByProperties([
        'id' => $edit['id'],
      ]);
    $search_page = reset($search_pages);

    $edit = [
      'id' => 'test_search_page_cloned',
      'label' => 'Test search page cloned',
    ];
    $this->drupalPostForm('entity_clone/search_page/' . $search_page->id(), $edit, t('Clone'));

    $search_pages = \Drupal::entityTypeManager()
      ->getStorage('search_page')
      ->loadByProperties([
        'id' => $edit['id'],
      ]);
    $search_page = reset($search_pages);
    $this->assertTrue($search_page, 'Test search page cloned found in database.');
  }
Example #7
0
 /**
  * Returns roles-profiles table.
  */
 public function buildRolesProfilesTable(array $roles_profiles)
 {
     $rp_table = array('#type' => 'table');
     // Prepare roles. Reverse the role order to prioritize the permissive ones.
     $roles = array_reverse(user_roles());
     $wrappers = \Drupal::service('stream_wrapper_manager')->getNames(StreamWrapperInterface::WRITE_VISIBLE);
     // Prepare profile options
     $options = array('' => '-' . $this->t('None') . '-');
     foreach (\Drupal::entityTypeManager()->getStorage('imce_profile')->loadMultiple() as $pid => $profile) {
         $options[$pid] = $profile->label();
     }
     // Build header
     $imce_url = \Drupal::url('imce.page');
     $rp_table['#header'] = array($this->t('Role'));
     $default = file_default_scheme();
     foreach ($wrappers as $scheme => $name) {
         $url = $scheme === $default ? $imce_url : $imce_url . '/' . $scheme;
         $rp_table['#header'][]['data'] = array('#markup' => '<a href="' . $url . '">' . Html::escape($name) . '</a>');
     }
     // Build rows
     foreach ($roles as $rid => $role) {
         $rp_table[$rid]['role_name'] = array('#plain_text' => $role->label());
         foreach ($wrappers as $scheme => $name) {
             $rp_table[$rid][$scheme] = array('#type' => 'select', '#options' => $options, '#default_value' => isset($roles_profiles[$rid][$scheme]) ? $roles_profiles[$rid][$scheme] : '');
         }
     }
     // Add description
     $rp_table['#prefix'] = '<h3>' . $this->t('Role-profile assignments') . '</h3>';
     $rp_table['#suffix'] = '<div class="description">' . $this->t('Assign configuration profiles to user roles for available file systems. The default file system %name is accessible at :url path.', array('%name' => $wrappers[file_default_scheme()], ':url' => $imce_url)) . '</div>';
     return $rp_table;
 }
 /**
  * {@inheritdoc}
  */
 public function completeSale($order, $login = FALSE)
 {
     // Empty that cart...
     $this->emptyCart();
     // Force the order to load from the DB instead of the entity cache.
     // @todo Remove this once uc_payment_enter() can modify order objects?
     // @todo Should we be overwriting $order with this newly-loaded db_order?
     $db_order = \Drupal::entityTypeManager()->getStorage('uc_order')->loadUnchanged($order->id());
     $order->data = $db_order->data;
     // Ensure that user creation and triggers are only run once.
     if (empty($order->data->complete_sale)) {
         $this->completeSaleAccount($order);
         // Move an order's status from "In checkout" to "Pending".
         if ($order->getStateId() == 'in_checkout') {
             $order->setStatusId(uc_order_state_default('post_checkout'));
         }
         $order->save();
         // Invoke the checkout complete trigger and hook.
         $account = $order->getOwner();
         \Drupal::moduleHandler()->invokeAll('uc_checkout_complete', array($order, $account));
         // rules_invoke_event('uc_checkout_complete', $order);
     }
     $type = $order->data->complete_sale;
     // Log in new users, if requested.
     if ($type == 'new_user' && $login && $this->currentUser->isAnonymous()) {
         $type = 'new_user_logged_in';
         user_login_finalize($order->getOwner());
     }
     $message = \Drupal::config('uc_cart.messages')->get($type);
     $message = \Drupal::token()->replace($message, array('uc_order' => $order));
     $variables['!new_username'] = isset($order->data->new_user_name) ? $order->data->new_user_name : '';
     $variables['!new_password'] = isset($order->password) ? $order->password : t('Your password');
     $message = strtr($message, $variables);
     return array('#theme' => 'uc_cart_complete_sale', '#message' => array('#markup' => $message), '#order' => $order);
 }
 /**
  * Tests the add page.
  */
 public function testForm()
 {
     $entities = [];
     $selection = [];
     for ($i = 0; $i < 2; $i++) {
         $entity = EnhancedEntity::create(['type' => 'default']);
         $entity->save();
         $entities[$entity->id()] = $entity;
         $langcode = $entity->language()->getId();
         $selection[$entity->id()][$langcode] = $langcode;
     }
     // Add the selection to the tempstore just like DeleteAction would.
     $tempstore = \Drupal::service('user.private_tempstore')->get('entity_delete_multiple_confirm');
     $tempstore->set($this->account->id(), $selection);
     $this->drupalGet('/entity_test_enhanced/delete');
     $assert = $this->assertSession();
     $assert->statusCodeEquals(200);
     $assert->elementTextContains('css', '.page-title', 'Are you sure you want to delete these items?');
     $delete_button = $this->getSession()->getPage()->findButton('Delete');
     $delete_button->click();
     $assert = $this->assertSession();
     $assert->addressEquals('/entity_test_enhanced');
     $assert->responseContains('Deleted 2 items.');
     \Drupal::entityTypeManager()->getStorage('entity_test_enhanced')->resetCache();
     $remaining_entities = EnhancedEntity::loadMultiple(array_keys($selection));
     $this->assertEmpty($remaining_entities);
 }
 /**
  * Tests the Drupal 6 taxonomy term to Drupal 8 migration.
  */
 public function testTaxonomyTerms()
 {
     $expected_results = array('1' => array('source_vid' => 1, 'vid' => 'vocabulary_1_i_0_', 'weight' => 0, 'parent' => array(0)), '2' => array('source_vid' => 2, 'vid' => 'vocabulary_2_i_1_', 'weight' => 3, 'parent' => array(0)), '3' => array('source_vid' => 2, 'vid' => 'vocabulary_2_i_1_', 'weight' => 4, 'parent' => array(2)), '4' => array('source_vid' => 3, 'vid' => 'vocabulary_3_i_2_', 'weight' => 6, 'parent' => array(0)), '5' => array('source_vid' => 3, 'vid' => 'vocabulary_3_i_2_', 'weight' => 7, 'parent' => array(4)), '6' => array('source_vid' => 3, 'vid' => 'vocabulary_3_i_2_', 'weight' => 8, 'parent' => array(4, 5)));
     $terms = Term::loadMultiple(array_keys($expected_results));
     // Find each term in the tree.
     $storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
     $vids = array_unique(array_column($expected_results, 'vid'));
     $tree_terms = [];
     foreach ($vids as $vid) {
         foreach ($storage->loadTree($vid) as $term) {
             $tree_terms[$term->tid] = $term;
         }
     }
     foreach ($expected_results as $tid => $values) {
         /** @var Term $term */
         $term = $terms[$tid];
         $this->assertIdentical("term {$tid} of vocabulary {$values['source_vid']}", $term->name->value);
         $this->assertIdentical("description of term {$tid} of vocabulary {$values['source_vid']}", $term->description->value);
         $this->assertIdentical($values['vid'], $term->vid->target_id);
         $this->assertIdentical((string) $values['weight'], $term->weight->value);
         if ($values['parent'] === array(0)) {
             $this->assertNull($term->parent->target_id);
         } else {
             $parents = array();
             foreach (\Drupal::entityManager()->getStorage('taxonomy_term')->loadParents($tid) as $parent) {
                 $parents[] = (int) $parent->id();
             }
             $this->assertIdentical($parents, $values['parent']);
         }
         $this->assertArrayHasKey($tid, $tree_terms, "Term {$tid} exists in vocabulary tree");
         $tree_term = $tree_terms[$tid];
         $this->assertEquals($values['parent'], $tree_term->parents, "Term {$tid} has correct parents in vocabulary tree");
     }
 }
  public function testFilterFormatEntityClone() {
    $edit = [
      'name' => 'Test filter format for clone',
      'format' => 'test_filter_format_for_clone',
    ];
    $this->drupalPostForm("admin/config/content/formats/add", $edit, t('Save configuration'));

    $filter_formats = \Drupal::entityTypeManager()
      ->getStorage('filter_format')
      ->loadByProperties([
        'format' => $edit['format'],
      ]);
    $filter_format = reset($filter_formats);

    $edit = [
      'id' => 'test_filter_format_cloned',
      'label' => 'Test filter format cloned',
    ];
    $this->drupalPostForm('entity_clone/filter_format/' . $filter_format->id(), $edit, t('Clone'));

    $filter_formats = \Drupal::entityTypeManager()
      ->getStorage('filter_format')
      ->loadByProperties([
        'format' => $edit['id'],
      ]);
    $filter_format = reset($filter_formats);
    $this->assertTrue($filter_format, 'Test filter format cloned found in database.');
  }
  public function testLanguageEntityClone() {
    $edit = [
      'predefined_langcode' => 'fr'
    ];
    $this->drupalPostForm("/admin/config/regional/language/add", $edit, t('Add language'));

    $languages = \Drupal::entityTypeManager()
      ->getStorage('configurable_language')
      ->loadByProperties([
        'id' => 'fr',
      ]);
    $language = reset($languages);

    $edit = [
      'id' => 'test_language_cloned',
      'label' => 'French language cloned',
    ];
    $this->drupalPostForm('entity_clone/configurable_language/' . $language->id(), $edit, t('Clone'));

    $languages = \Drupal::entityTypeManager()
      ->getStorage('configurable_language')
      ->loadByProperties([
        'id' => $edit['id'],
      ]);
    $language = reset($languages);
    $this->assertTrue($language, 'Test language cloned found in database.');
  }
 /**
  * {@inheritdoc}
  */
 public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state)
 {
     $referenced_entities = $items->referencedEntities();
     $element = parent::formElement($items, $delta, $element, $form, $form_state);
     // If this is an existing (not new item).
     if ($delta < count($referenced_entities)) {
         // Mark element as being existing, not new item.
         // Top level of the returned element must be called 'target_id',
         // so we cannot create a container.
         // Autocomplete element does some fancy processing to handle empty strings,
         // so we must use an autocomplete element not a hidden or textfield element.
         // But #states[#visible] does not seem to have an option to always hide.,
         // and autocomplete elements don't seem to accept #attributes, so we must
         // use #prefix and #suffix to add a class so that we can hide it.
         $element['#prefix'] = '<div class="er-enhanced-existing">';
         $element['#suffix'] = '</div>';
         if ($this->getSetting('preview')) {
             // Add preview.
             $element['#prefix'] = '<div class="er-enhanced-existing er-enhanced-previewing">';
             $element['#attached']['library'][] = 'ahs_er_enhanced/preview';
             $entityTypeName = $referenced_entities[$delta]->getEntityType()->id();
             $view_builder = \Drupal::entityTypeManager()->getViewBuilder($entityTypeName);
             $preview = $view_builder->view($referenced_entities[$delta], $this->getSetting('preview_view_mode'));
             $element['preview_container'] = ['#type' => 'container', '#attributes' => ['class' => ['er-enhanced-preview']], 'preview' => $preview];
             // Add a remove link to the preview.
             $element['remove'] = ['#markup' => '<a class="er-enhanced-remove" href="">' . t('Remove') . '</a>'];
             $element['#attached']['library'][] = 'ahs_er_enhanced/remove';
         }
     } else {
         $element['#prefix'] = '<div class="er-enhanced-new">';
         $element['#suffix'] = '</div>';
     }
     return $element;
 }
 /**
  * Test user registration integration.
  */
 public function testUserRegisterForm()
 {
     $id = $this->type->id();
     $field_name = $this->field->getName();
     $this->field->setRequired(TRUE);
     $this->field->save();
     // Allow registration without administrative approval and log in user
     // directly after registering.
     \Drupal::configFactory()->getEditable('user.settings')->set('register', USER_REGISTER_VISITORS)->set('verify_mail', 0)->save();
     user_role_grant_permissions(AccountInterface::AUTHENTICATED_ROLE, ['view own test profile']);
     // Verify that the additional profile field is attached and required.
     $name = $this->randomMachineName();
     $pass_raw = $this->randomMachineName();
     $edit = ['name' => $name, 'mail' => $this->randomMachineName() . '@example.com', 'pass[pass1]' => $pass_raw, 'pass[pass2]' => $pass_raw];
     $this->drupalPostForm('user/register', $edit, t('Create new account'));
     $this->assertRaw(new FormattableMarkup('@name field is required.', ['@name' => $this->field->getLabel()]));
     // Verify that we can register.
     $edit["entity_" . $id . "[{$field_name}][0][value]"] = $this->randomMachineName();
     $this->drupalPostForm(NULL, $edit, t('Create new account'));
     $this->assertText(new FormattableMarkup('Registration successful. You are now logged in.', []));
     $new_user = user_load_by_name($name);
     $this->assertTrue($new_user->isActive(), 'New account is active after registration.');
     // Verify that a new profile was created for the new user ID.
     $profile = \Drupal::entityTypeManager()->getStorage('profile')->loadByUser($new_user, $this->type->id());
     $this->assertEqual($profile->get($field_name)->value, $edit["entity_" . $id . "[{$field_name}][0][value]"], 'Field value found in loaded profile.');
     // Verify that the profile field value appears on the user account page.
     $this->drupalGet('user');
     $this->assertText($edit["entity_" . $id . "[{$field_name}][0][value]"], 'Field value found on user account page.');
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installConfig(['system']);
     $this->installConfig(['field']);
     $this->installConfig(['text']);
     $this->installConfig(['address']);
     $this->installEntitySchema('entity_test');
     ConfigurableLanguage::createFromLangcode('zh-hant')->save();
     // The address module is never installed, so the importer doesn't run
     // automatically. Instead, we manually import the address formats we need.
     $country_codes = ['AD', 'SV', 'TW', 'US', 'ZZ'];
     $importer = \Drupal::service('address.address_format_importer');
     $importer->importEntities($country_codes);
     $importer->importTranslations(['zh-hant']);
     $this->entityType = 'entity_test';
     $this->bundle = $this->entityType;
     $this->fieldName = Unicode::strtolower($this->randomMachineName());
     $field_storage = FieldStorageConfig::create(['field_name' => $this->fieldName, 'entity_type' => $this->entityType, 'type' => 'address']);
     $field_storage->save();
     $field = FieldConfig::create(['field_storage' => $field_storage, 'bundle' => $this->bundle, 'label' => $this->randomMachineName()]);
     $field->save();
     $values = ['targetEntityType' => $this->entityType, 'bundle' => $this->bundle, 'mode' => 'default', 'status' => TRUE];
     $this->display = \Drupal::entityTypeManager()->getStorage('entity_view_display')->create($values);
     $this->display->setComponent($this->fieldName, ['type' => 'address_default', 'settings' => []]);
     $this->display->save();
 }
  public function testContentEntityClone() {
    $title_key = 'title[0][value]';
    $body_key = 'body[0][value]';
    // Create node to edit.

    $edit = array();
    $edit[$title_key] = $this->randomMachineName(8);
    $edit[$body_key] = $this->randomMachineName(16);
    $this->drupalPostForm('node/add/page', $edit, t('Save and publish'));

    $nodes = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties([
        'title' => $edit[$title_key],
        'body' => $edit[$body_key],
      ]);
    $node = reset($nodes);
    $this->assertTrue($node, 'Test node for clone found in database.');

    $this->drupalPostForm('entity_clone/node/' . $node->id(), [], t('Clone'));

    $nodes = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties([
        'title' => $edit[$title_key] . ' - Cloned',
        'body' => $edit[$body_key],
      ]);
    $node = reset($nodes);
    $this->assertTrue($node, 'Test node cloned found in database.');
  }
Example #17
0
/**
 * Perform a single batch operation.
 *
 * Callback for batch_set().
 *
 * @param $MULTIPLE_PARAMS
 *   Additional parameters specific to the batch. These are specified in the
 *   array passed to batch_set().
 * @param array|\ArrayAccess $context.
 *   The batch context array, passed by reference. This contains the following
 *   properties:
 *   - 'finished': A float number between 0 and 1 informing the processing
 *     engine of the completion level for the operation. 1 (or no value
 *     explicitly set) means the operation is finished: the operation will not
 *     be called again, and execution passes to the next operation or the
 *     callback_batch_finished() implementation. Any other value causes this
 *     operation to be called again; however it should be noted that the value
 *     set here does not persist between executions of this callback: each time
 *     it is set to 1 by default by the batch system.
 *   - 'sandbox': This may be used by operations to persist data between
 *     successive calls to the current operation. Any values set in
 *     $context['sandbox'] will be there the next time this function is called
 *     for the current operation. For example, an operation may wish to store a
 *     pointer in a file or an offset for a large query. The 'sandbox' array key
 *     is not initially set when this callback is first called, which makes it
 *     useful for determining whether it is the first call of the callback or
 *     not:
 *     @code
 *       if (empty($context['sandbox'])) {
 *         // Perform set-up steps here.
 *       }
 *     @endcode
 *     The values in the sandbox are stored and updated in the database between
 *     http requests until the batch finishes processing. This avoids problems
 *     if the user navigates away from the page before the batch finishes.
 *   - 'message': A text message displayed in the progress page.
 *   - 'results': The array of results gathered so far by the batch processing.
 *     This array is highly useful for passing data between operations. After
 *     all operations have finished, this is passed to callback_batch_finished()
 *     where results may be referenced to display information to the end-user,
 *     such as how many total items were processed.
 *   It is discouraged to typehint this parameter as an array, to allow an
 *   object implement \ArrayAccess to be passed.
 */
function callback_batch_operation($MULTIPLE_PARAMS, &$context)
{
    $node_storage = \Drupal::entityTypeManager()->getStorage('node');
    $database = \Drupal::database();
    if (!isset($context['sandbox']['progress'])) {
        $context['sandbox']['progress'] = 0;
        $context['sandbox']['current_node'] = 0;
        $context['sandbox']['max'] = $database->query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
    }
    // For this example, we decide that we can safely process
    // 5 nodes at a time without a timeout.
    $limit = 5;
    // With each pass through the callback, retrieve the next group of nids.
    $result = $database->queryRange("SELECT nid FROM {node} WHERE nid > :nid ORDER BY nid ASC", 0, $limit, [':nid' => $context['sandbox']['current_node']]);
    foreach ($result as $row) {
        // Here we actually perform our processing on the current node.
        $node_storage->resetCache(array($row['nid']));
        $node = $node_storage->load($row['nid']);
        $node->value1 = $options1;
        $node->value2 = $options2;
        node_save($node);
        // Store some result for post-processing in the finished callback.
        $context['results'][] = $node->title;
        // Update our progress information.
        $context['sandbox']['progress']++;
        $context['sandbox']['current_node'] = $node->nid;
        $context['message'] = t('Now processing %node', array('%node' => $node->title));
    }
    // Inform the batch engine that we are not finished,
    // and provide an estimation of the completion level we reached.
    if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
        $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
    }
}
 /**
  * Load an entity by it's label.
  *
  * @param string $label
  *   The label of the entity to load.
  * @param string $entity_type
  *   The entity type to load.
  *
  * @return \Drupal\Core\Entity\EntityInterface
  *   A loaded entity.
  */
 protected function loadEntityByLabel($label, $entity_type = 'node')
 {
     $type_manager = \Drupal::entityTypeManager();
     $label_key = $type_manager->getDefinition($entity_type)->getKey('label');
     $entities = \Drupal::entityQuery($entity_type)->condition($label_key, $label, '=')->execute();
     return $type_manager->getStorage($entity_type)->load(array_shift($entities));
 }
  public function testBlockEntityClone() {
    $edit = [
      'settings[label]' => 'Test block for clone',
      'id' => 'test_block_for_clone',
    ];
    $this->drupalPostForm("admin/structure/block/add/local_actions_block/classy", $edit, t('Save block'));

    $blocks = \Drupal::entityTypeManager()
      ->getStorage('block')
      ->loadByProperties([
        'id' => $edit['id'],
      ]);
    $block = reset($blocks);

    $edit = [
      'id' => 'test_block_cloned',
    ];
    $this->drupalPostForm('entity_clone/block/' . $block->id(), $edit, t('Clone'));

    $blocks = \Drupal::entityTypeManager()
      ->getStorage('block')
      ->loadByProperties([
        'id' => $edit['id'],
      ]);
    $block = reset($blocks);
    $this->assertTrue($block, 'Test block cloned found in database.');
  }
 /**
  * Gets the moderation state entity linked to a content entity revision.
  *
  * @return \Drupal\content_moderation\ModerationStateInterface|null
  *   The moderation state configuration entity linked to a content entity
  *   revision.
  */
 protected function getModerationState()
 {
     $entity = $this->getEntity();
     if (!\Drupal::service('content_moderation.moderation_information')->shouldModerateEntitiesOfBundle($entity->getEntityType(), $entity->bundle())) {
         return NULL;
     }
     if ($entity->id() && $entity->getRevisionId()) {
         $revisions = \Drupal::service('entity.query')->get('content_moderation_state')->condition('content_entity_type_id', $entity->getEntityTypeId())->condition('content_entity_id', $entity->id())->condition('content_entity_revision_id', $entity->getRevisionId())->allRevisions()->sort('revision_id', 'DESC')->execute();
         if ($revision_to_load = key($revisions)) {
             /** @var \Drupal\content_moderation\ContentModerationStateInterface $content_moderation_state */
             $content_moderation_state = \Drupal::entityTypeManager()->getStorage('content_moderation_state')->loadRevision($revision_to_load);
             // Return the correct translation.
             $langcode = $entity->language()->getId();
             if (!$content_moderation_state->hasTranslation($langcode)) {
                 $content_moderation_state->addTranslation($langcode);
             }
             if ($content_moderation_state->language()->getId() !== $langcode) {
                 $content_moderation_state = $content_moderation_state->getTranslation($langcode);
             }
             return $content_moderation_state->get('moderation_state')->entity;
         }
     }
     // It is possible that the bundle does not exist at this point. For example,
     // the node type form creates a fake Node entity to get default values.
     // @see \Drupal\node\NodeTypeForm::form()
     $bundle_entity = \Drupal::entityTypeManager()->getStorage($entity->getEntityType()->getBundleEntityType())->load($entity->bundle());
     if ($bundle_entity && ($default = $bundle_entity->getThirdPartySetting('content_moderation', 'default_moderation_state'))) {
         return ModerationState::load($default);
     }
 }
 /**
  * {@inheritdoc}
  *
  * TODO: Use $langcode.
  */
 public function viewElements(FieldItemListInterface $items, $langcode)
 {
     $element = array();
     $settings = $this->getFieldSettings();
     $count = 0;
     // TODO: Is there a better way to get an accurate count of the
     // items from the FieldItemList that doesn't count blank items?
     // Possibly \Countable->count()?
     $storage = \Drupal::entityTypeManager()->getStorage('field_collection_item');
     foreach ($items as $delta => $item) {
         if ($item->value !== NULL) {
             $count++;
             $field_collection_item = $storage->loadRevision($item->revision_id);
             if ($field_collection_item->isDefaultRevision()) {
                 $links = \Drupal::l($this->fieldDefinition->getName() . ' ' . $delta, Url::FromRoute('entity.field_collection_item.canonical', array('field_collection_item' => $item->value)));
                 $links .= ' ' . $this->getEditLinks($item);
             } else {
                 $links = \Drupal::l($this->fieldDefinition->getName() . ' ' . $delta, Url::FromRoute('field_collection_item.revision_show', ['field_collection_item' => $item->value, 'field_collection_item_revision' => $item->revision_id]));
             }
             $element[$delta] = array('#markup' => $links);
         }
     }
     $cardinality = $this->fieldDefinition->getFieldStorageDefinition()->getCardinality();
     if ($cardinality == -1 || $count < $cardinality) {
         $element['#suffix'] = '<ul class="action-links action-links-field-collection-add"><li>';
         $element['#suffix'] .= $this->getAddLink($items->getEntity());
         $element['#suffix'] .= '</li></ul>';
     }
     return $element;
 }
  public function testResponsiveImageStyleEntityClone() {
    $edit = [
      'label' => 'Test responsive image style for clone',
      'id' => 'test_responsive_image_style_for_clone',
      'breakpoint_group' => 'responsive_image',
      'fallback_image_style' => 'large',
    ];
    $this->drupalPostForm("admin/config/media/responsive-image-style/add", $edit, t('Save'));

    $responsive_image_styles = \Drupal::entityTypeManager()
      ->getStorage('responsive_image_style')
      ->loadByProperties([
        'id' => $edit['id'],
      ]);
    $responsive_image_style = reset($responsive_image_styles);

    $edit = [
      'id' => 'test_responsive_image_style_cloned',
      'label' => 'Test responsive image style cloned',
    ];
    $this->drupalPostForm('entity_clone/responsive_image_style/' . $responsive_image_style->id(), $edit, t('Clone'));

    $responsive_image_styles = \Drupal::entityTypeManager()
      ->getStorage('responsive_image_style')
      ->loadByProperties([
        'id' => $edit['id'],
      ]);
    $responsive_image_style = reset($responsive_image_styles);
    $this->assertTrue($responsive_image_style, 'Test responsive image style cloned found in database.');
  }
Example #23
0
 /**
  * {@inheritdoc}
  */
 public static function valueCallback(&$element, $input, FormStateInterface $form_state)
 {
     // Process the #default_value property.
     if ($input === FALSE && isset($element['#default_value']) && $element['#process_default_value']) {
         if (is_array($element['#default_value']) && $element['#tags'] !== TRUE) {
             throw new \InvalidArgumentException('The #default_value property is an array but the form element does not allow multiple values.');
         } elseif (!empty($element['#default_value']) && !is_array($element['#default_value'])) {
             // Convert the default value into an array for easier processing in
             // static::getEntityLabels().
             $element['#default_value'] = array($element['#default_value']);
         }
         if ($element['#default_value']) {
             if (!reset($element['#default_value']) instanceof EntityInterface) {
                 throw new \InvalidArgumentException('The #default_value property has to be an entity object or an array of entity objects.');
             }
             // Extract the labels from the passed-in entity objects, taking access
             // checks into account.
             return static::getEntityLabels($element['#default_value']);
         }
     }
     // Potentially the #value is set directly, so it contains the 'target_id'
     // array structure instead of a string.
     if ($input !== FALSE && is_array($input)) {
         $entity_ids = array_map(function (array $item) {
             return $item['target_id'];
         }, $input);
         $entities = \Drupal::entityTypeManager()->getStorage($element['#target_type'])->loadMultiple($entity_ids);
         return static::getEntityLabels($entities);
     }
 }
  public function testCustomBlockEntityClone() {

    $edit = array();
    $edit['info[0][value]'] = 'Test block ready to clone';
    $edit['body[0][value]'] = $this->randomMachineName(16);
    $this->drupalPostForm('block/add/basic', $edit, t('Save'));

    $blocks = \Drupal::entityTypeManager()
      ->getStorage('block_content')
      ->loadByProperties([
        'info' => $edit['info[0][value]'],
      ]);
    $block = reset($blocks);
    $this->assertTrue($block, 'Test Block for clone found in database.');

    $this->drupalPostForm('entity_clone/block_content/' . $block->id(), [], t('Clone'));

    $blocks = \Drupal::entityTypeManager()
      ->getStorage('block_content')
      ->loadByProperties([
        'info' => $edit['info[0][value]'] . ' - Cloned',
        'body' => $edit['body[0][value]'],
      ]);
    $block = reset($blocks);
    $this->assertTrue($block, 'Test Block cloned found in database.');
  }
 /**
  * Builds a table row for overview form.
  *
  * @param \Drupal\Core\Config\Entity\ConfigEntityInterface $entity
  *   Data needed to build the list row.
  *
  * @return array
  *   A single table row for the overview.
  */
 public function overviewRow(ConfigEntityInterface $entity)
 {
     $label = $entity->label() ?: $this->t('@type: @id', array('@type' => $entity->getEntityTypeId(), '@id' => $entity->id()));
     // Get current job items for the entity to determine translation statuses.
     $source_lang = $entity->language()->getId();
     $current_job_items = tmgmt_job_item_load_latest('config', $entity->getEntityTypeId(), $entity->getConfigDependencyName(), $source_lang);
     $row['id'] = $entity->id();
     $definition = \Drupal::entityTypeManager()->getDefinition($entity->bundle());
     $row['config_id'] = $definition->getConfigPrefix() . '.' . $entity->id();
     if ($entity->hasLinkTemplate('edit-form')) {
         $row['title'] = $entity->toLink($label, 'edit-form');
     } else {
         // If the entity doesn't have a link we display a label.
         $row['title'] = $label;
     }
     // Load entity translation specific data.
     foreach (\Drupal::languageManager()->getLanguages() as $langcode => $language) {
         $translation_status = 'current';
         if ($langcode == $source_lang) {
             $translation_status = 'original';
         } elseif (!$this->isTranslated($langcode, $entity->getConfigDependencyName())) {
             $translation_status = 'missing';
         }
         // @todo Find a way to support marking configuration translations as outdated.
         $build = $this->buildTranslationStatus($translation_status, isset($current_job_items[$langcode]) ? $current_job_items[$langcode] : NULL);
         $row['langcode-' . $langcode] = ['data' => \Drupal::service('renderer')->render($build), 'class' => array('langstatus-' . $langcode)];
     }
     return $row;
 }
  public function testImageStyleEntityClone() {
    $edit = [
      'label' => 'Test image style for clone',
      'name' => 'test_image_style_for_clone',
    ];
    $this->drupalPostForm("admin/config/media/image-styles/add", $edit, t('Create new style'));

    $image_styles = \Drupal::entityTypeManager()
      ->getStorage('image_style')
      ->loadByProperties([
        'name' => $edit['name'],
      ]);
    $image_style = reset($image_styles);

    $edit = [
      'id' => 'test_iamge_style_cloned',
      'label' => 'Test image_style cloned',
    ];
    $this->drupalPostForm('entity_clone/image_style/' . $image_style->id(), $edit, t('Clone'));

    $image_styles = \Drupal::entityTypeManager()
      ->getStorage('image_style')
      ->loadByProperties([
        'name' => $edit['id'],
      ]);
    $image_style = reset($image_styles);
    $this->assertTrue($image_style, 'Test image style cloned found in database.');
  }
 /**
  * Ensures that update hook is run for rest module.
  */
 public function testUpdate()
 {
     $this->runUpdates();
     // Get particular view.
     $view = \Drupal::entityTypeManager()->getStorage('view')->load('rest_export_with_authorization');
     $displays = $view->get('display');
     $this->assertIdentical($displays['rest_export_1']['display_options']['auth']['basic_auth'], 'basic_auth', 'Basic authentication is set as authentication method.');
 }
 /**
  * {@inheritdoc}
  */
 public function setUp()
 {
     parent::setUp();
     $this->bundleStorage = \Drupal::entityTypeManager()->getStorage('features_bundle');
     $admin_user = $this->createUser(['administer site configuration', 'export configuration', 'administer modules']);
     $this->drupalLogin($admin_user);
     $this->drupalPlaceBlock('local_actions_block');
 }
 /**
  * Deletes Paragraphs datas.
  */
 public static function deleteParagraphs(&$context)
 {
     $paragraph_ids = \Drupal::entityQuery('paragraph')->range(0, 100)->execute();
     $storage = \Drupal::entityTypeManager()->getStorage('paragraph');
     if ($paragraphs = $storage->loadMultiple($paragraph_ids)) {
         $storage->delete($paragraphs);
     }
     $context['finished'] = (int) count($paragraph_ids) < 100;
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->style = ImageStyle::create(['name' => 'style_foo', 'label' => $this->randomString()]);
     $this->style->save();
     $this->replacementStyle = ImageStyle::create(['name' => 'style_bar', 'label' => $this->randomString()]);
     $this->replacementStyle->save();
     $this->entityTypeManager = \Drupal::entityTypeManager();
 }