public function content()
 {
     $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
     $userId = $user->get('uid')->value;
     $data = array(array('job_title' => '', 'job_path' => '', 'company_name' => '', 'application_date' => ''));
     $appliedJobs = db_select('user_job_application', 'uja')->condition('uja.user_id', $userId, '=')->fields('uja', array('job_id', 'date'))->orderBy('uja.date', 'DESC')->execute()->fetchAll();
     if ($appliedJobs) {
         $x = 0;
         foreach ($appliedJobs as $appliedJob) {
             $jobNode = \Drupal\node\Entity\Node::load($appliedJob->job_id);
             $jobTitle = $jobNode->getTitle();
             $jobPathAlias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/' . $appliedJob->job_id);
             $companyNodeEntity = $jobNode->get('field_company');
             $companyNode = \Drupal\node\Entity\Node::load($companyNodeEntity->entity->id());
             $companyName = $companyNode->getTitle();
             $data[$x]['job_title'] = $jobTitle;
             $data[$x]['job_path'] = $jobPathAlias;
             $data[$x]['company_name'] = $companyName;
             $data[$x]['application_date'] = $appliedJob->date;
             $x++;
         }
     }
     $markUp = $this->createMarkUp($data);
     return array('#type' => 'markup', '#markup' => $markUp);
 }
Ejemplo n.º 2
0
 /**
  * Tests the integration of the {node_counter} table in views.
  */
 public function testNodeCounterIntegration()
 {
     $this->drupalLogin($this->webUser);
     $this->drupalGet('node/' . $this->node->id());
     // Manually calling statistics.php, simulating ajax behavior.
     // @see \Drupal\statistics\Tests\StatisticsLoggingTest::testLogging().
     global $base_url;
     $stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
     $client = \Drupal::service('http_client_factory')->fromOptions(['config/curl', array(CURLOPT_TIMEOUT => 10)]);
     $client->post($stats_path, array('form_params' => array('nid' => $this->node->id())));
     $this->drupalGet('test_statistics_integration');
     $expected = statistics_get($this->node->id());
     // Convert the timestamp to year, to match the expected output of the date
     // handler.
     $expected['timestamp'] = date('Y', $expected['timestamp']);
     foreach ($expected as $field => $value) {
         $xpath = "//div[contains(@class, views-field-{$field})]/span[@class = 'field-content']";
         $this->assertFieldByXpath($xpath, $value, "The {$field} output matches the expected.");
     }
     $this->drupalLogout();
     $this->drupalLogin($this->deniedUser);
     $this->drupalGet('test_statistics_integration');
     $this->assertResponse(200);
     foreach ($expected as $field => $value) {
         $xpath = "//div[contains(@class, views-field-{$field})]/span[@class = 'field-content']";
         $this->assertNoFieldByXpath($xpath, $value, "The {$field} output is not displayed.");
     }
 }
Ejemplo n.º 3
0
 public function mapAnalysisIssues(Node $entity, array $results)
 {
     $nid = $entity->id();
     foreach ($results as $issue_entity) {
         /** @var EntityInterface $issue_entity */
         $this->connection->insert('code_analyzer_project_issues')->fields(array('nid' => $nid, 'inid' => $issue_entity->id()))->execute();
     }
 }
 /**
  * Asserts that node access correctly grants or denies access.
  *
  * @param array $ops
  *   An associative array of the expected node access grants for the node
  *   and account, with each key as the name of an operation (e.g. 'view',
  *   'delete') and each value a Boolean indicating whether access to that
  *   operation should be granted.
  * @param \Drupal\node\Entity\Node $node
  *   The node object to check.
  * @param \Drupal\Core\Session\AccountInterface $account
  *   The user account for which to check access.
  * @param string|null $langcode
  *   (optional) The language code indicating which translation of the node
  *   to check. If NULL, the untranslated (fallback) access is checked.
  */
 function assertNodeAccess(array $ops, $node, AccountInterface $account, $langcode = NULL)
 {
     foreach ($ops as $op => $result) {
         if (empty($langcode)) {
             $langcode = $node->prepareLangcode();
         }
         $this->assertEqual($result, $this->accessHandler->access($node, $op, $langcode, $account), $this->nodeAccessAssertMessage($op, $result, $langcode));
     }
 }
Ejemplo n.º 5
0
 /**
  * Post a Tweet about article node
  *
  * @param Node $node Node
  * @return array $statuses Result of posting a Tweet
  */
 public function tweetAboutArticle(Node $node)
 {
     // Set absolute URL to the node
     $url = $node->url('canonical', ['absolute' => true]);
     //$node->get('tags');
     $tweet = $this->createTweet($node->getTitle(), $url);
     // $statuses = $this->getApi()->post("statuses/update", ["status" => $tweet]);
     //print_r($statuses); exit;
     $statuses = [];
     return $statuses;
 }
Ejemplo n.º 6
0
 /**
  * Test that hook_entity_field_access() is called.
  */
 function testFieldAccess()
 {
     // Assert the text is visible.
     $this->drupalGet('node/' . $this->node->id());
     $this->assertText($this->testViewFieldValue);
     // Assert the text is not visible for anonymous users.
     // The field_test module implements hook_entity_field_access() which will
     // specifically target the 'test_view_field' field.
     $this->drupalLogout();
     $this->drupalGet('node/' . $this->node->id());
     $this->assertNoText($this->testViewFieldValue);
 }
 /**
  * Tests that local actions/tasks are being converted into blocks.
  */
 public function testUpdateHookN()
 {
     $this->runUpdates();
     /** @var \Drupal\block\BlockInterface $block_storage */
     $block_storage = \Drupal::entityManager()->getStorage('block');
     /* @var \Drupal\block\BlockInterface[] $help_blocks */
     $help_blocks = $block_storage->loadByProperties(['theme' => 'bartik', 'region' => 'help']);
     $this->assertRaw('Because your site has custom theme(s) installed, we had to set local actions and tasks blocks into the content region. Please manually review the block configurations and remove the removed variables from your templates.');
     // Disable maintenance mode.
     // @todo Can be removed once maintenance mode is automatically turned off
     // after updates in https://www.drupal.org/node/2435135.
     \Drupal::state()->set('system.maintenance_mode', FALSE);
     // We finished updating so we can log in the user now.
     $this->drupalLogin($this->rootUser);
     $page = Node::create(['type' => 'page', 'title' => 'Page node']);
     $page->save();
     // Ensures that blocks inside help region has been moved to content region.
     foreach ($help_blocks as $block) {
         $new_block = $block_storage->load($block->id());
         $this->assertEqual($new_block->getRegion(), 'content');
     }
     // Local tasks are visible on the node page.
     $this->drupalGet('node/' . $page->id());
     $this->assertText(t('Edit'));
     // Local actions are visible on the content listing page.
     $this->drupalGet('admin/content');
     $action_link = $this->cssSelect('.action-links');
     $this->assertTrue($action_link);
     $this->drupalGet('admin/structure/block/list/seven');
     /** @var \Drupal\Core\Config\StorageInterface $config_storage */
     $config_storage = \Drupal::service('config.storage');
     $this->assertTrue($config_storage->exists('block.block.test_theme_local_tasks'), 'Local task block has been created for the custom theme.');
     $this->assertTrue($config_storage->exists('block.block.test_theme_local_actions'), 'Local action block has been created for the custom theme.');
 }
Ejemplo n.º 8
0
 /**
  * Verifies that a transaction rolls back the failed creation.
  */
 function testFailedPageCreation()
 {
     // Create a node.
     $edit = array('uid' => $this->loggedInUser->id(), 'name' => $this->loggedInUser->name, 'type' => 'page', 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'title' => 'testing_transaction_exception');
     try {
         // An exception is generated by node_test_exception_node_insert() if the
         // title is 'testing_transaction_exception'.
         Node::create($edit)->save();
         $this->fail(t('Expected exception has not been thrown.'));
     } catch (\Exception $e) {
         $this->pass(t('Expected exception has been thrown.'));
     }
     if (Database::getConnection()->supportsTransactions()) {
         // Check that the node does not exist in the database.
         $node = $this->drupalGetNodeByTitle($edit['title']);
         $this->assertFalse($node, 'Transactions supported, and node not found in database.');
     } else {
         // Check that the node exists in the database.
         $node = $this->drupalGetNodeByTitle($edit['title']);
         $this->assertTrue($node, 'Transactions not supported, and node found in database.');
         // Check that the failed rollback was logged.
         $records = static::getWatchdogIdsForFailedExplicitRollback();
         $this->assertTrue(count($records) > 0, 'Transactions not supported, and rollback error logged to watchdog.');
     }
     // Check that the rollback error was logged.
     $records = static::getWatchdogIdsForTestExceptionRollback();
     $this->assertTrue(count($records) > 0, 'Rollback explanatory error logged to watchdog.');
 }
 /**
  * Tests that page title is being converted into a block.
  */
 public function testUpdateHookN()
 {
     $this->runUpdates();
     /** @var \Drupal\block\BlockInterface $block_storage */
     $block_storage = \Drupal::entityManager()->getStorage('block');
     $this->assertRaw('Because your site has custom theme(s) installed, we have placed the page title block in the content region. Please manually review the block configuration and remove the page title variables from your page templates.');
     // Disable maintenance mode.
     // @todo Can be removed once maintenance mode is automatically turned off
     // after updates in https://www.drupal.org/node/2435135.
     \Drupal::state()->set('system.maintenance_mode', FALSE);
     // We finished updating so we can log in the user now.
     $this->drupalLogin($this->rootUser);
     $page = Node::create(['type' => 'page', 'title' => 'Page node']);
     $page->save();
     // Page title is visible on the home page.
     $this->drupalGet('/node');
     $this->assertRaw('page-title');
     // Page title is visible on a node page.
     $this->drupalGet('node/' . $page->id());
     $this->assertRaw('page-title');
     $this->drupalGet('admin/structure/block/list/bartik');
     /** @var \Drupal\Core\Config\StorageInterface $config_storage */
     $config_storage = \Drupal::service('config.storage');
     $this->assertTrue($config_storage->exists('block.block.test_theme_page_title'), 'Page title block has been created for the custom theme.');
 }
Ejemplo n.º 10
0
 /**
  * Creates four nodes and ensures that they are loaded correctly.
  */
 function testNodeMultipleLoad()
 {
     $node1 = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
     $node2 = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
     $node3 = $this->drupalCreateNode(array('type' => 'article', 'promote' => 0));
     $node4 = $this->drupalCreateNode(array('type' => 'page', 'promote' => 0));
     // Confirm that promoted nodes appear in the default node listing.
     $this->drupalGet('node');
     $this->assertText($node1->label(), 'Node title appears on the default listing.');
     $this->assertText($node2->label(), 'Node title appears on the default listing.');
     $this->assertNoText($node3->label(), 'Node title does not appear in the default listing.');
     $this->assertNoText($node4->label(), 'Node title does not appear in the default listing.');
     // Load nodes with only a condition. Nodes 3 and 4 will be loaded.
     $nodes = entity_load_multiple_by_properties('node', array('promote' => 0));
     $this->assertEqual($node3->label(), $nodes[$node3->id()]->label(), 'Node was loaded.');
     $this->assertEqual($node4->label(), $nodes[$node4->id()]->label(), 'Node was loaded.');
     $count = count($nodes);
     $this->assertTrue($count == 2, format_string('@count nodes loaded.', array('@count' => $count)));
     // Load nodes by nid. Nodes 1, 2 and 4 will be loaded.
     $nodes = Node::loadMultiple(array(1, 2, 4));
     $count = count($nodes);
     $this->assertTrue(count($nodes) == 3, format_string('@count nodes loaded', array('@count' => $count)));
     $this->assertTrue(isset($nodes[$node1->id()]), 'Node is correctly keyed in the array');
     $this->assertTrue(isset($nodes[$node2->id()]), 'Node is correctly keyed in the array');
     $this->assertTrue(isset($nodes[$node4->id()]), 'Node is correctly keyed in the array');
     foreach ($nodes as $node) {
         $this->assertTrue(is_object($node), 'Node is an object');
     }
 }
Ejemplo n.º 11
0
 /**
  * Tests the node validation constraints.
  */
 public function testValidation()
 {
     $this->createUser();
     $node = Node::create(['type' => 'page', 'title' => 'test', 'uid' => 1]);
     $violations = $node->validate();
     $this->assertEqual(count($violations), 0, 'No violations when validating a default node.');
     $node->set('title', $this->randomString(256));
     $violations = $node->validate();
     $this->assertEqual(count($violations), 1, 'Violation found when title is too long.');
     $this->assertEqual($violations[0]->getPropertyPath(), 'title.0.value');
     $this->assertEqual($violations[0]->getMessage(), '<em class="placeholder">Title</em>: may not be longer than 255 characters.');
     $node->set('title', NULL);
     $violations = $node->validate();
     $this->assertEqual(count($violations), 1, 'Violation found when title is not set.');
     $this->assertEqual($violations[0]->getPropertyPath(), 'title');
     $this->assertEqual($violations[0]->getMessage(), 'This value should not be null.');
     $node->set('title', '');
     $violations = $node->validate();
     $this->assertEqual(count($violations), 1, 'Violation found when title is set to an empty string.');
     $this->assertEqual($violations[0]->getPropertyPath(), 'title');
     // Make the title valid again.
     $node->set('title', $this->randomString());
     // Save the node so that it gets an ID and a changed date.
     $node->save();
     // Set the changed date to something in the far past.
     $node->set('changed', 433918800);
     $violations = $node->validate();
     $this->assertEqual(count($violations), 1, 'Violation found when changed date is before the last changed date.');
     $this->assertEqual($violations[0]->getPropertyPath(), '');
     $this->assertEqual($violations[0]->getMessage(), 'The content has either been modified by another user, or you have already submitted modifications. As a result, your changes cannot be saved.');
 }
Ejemplo n.º 12
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     ConfigurableLanguage::createFromLangcode('it')->save();
     /** @var \Drupal\content_translation\ContentTranslationManagerInterface $manager */
     $manager = \Drupal::service('content_translation.manager');
     $manager->setEnabled('node', 'article', TRUE);
     // Create and log in user.
     $web_user = $this->drupalCreateUser(array('view page revisions', 'revert page revisions', 'delete page revisions', 'edit any page content', 'delete any page content', 'translate any entity'));
     $this->drupalLogin($web_user);
     // Create initial node.
     $node = $this->drupalCreateNode();
     $settings = get_object_vars($node);
     $settings['revision'] = 1;
     $settings['isDefaultRevision'] = TRUE;
     $nodes = array();
     $logs = array();
     // Get original node.
     $nodes[] = clone $node;
     // Create three revisions.
     $revision_count = 3;
     for ($i = 0; $i < $revision_count; $i++) {
         $logs[] = $node->revision_log = $this->randomMachineName(32);
         // Create revision with a random title and body and update variables.
         $node->title = $this->randomMachineName();
         $node->body = array('value' => $this->randomMachineName(32), 'format' => filter_default_format());
         $node->setNewRevision();
         $node->save();
         $node = Node::load($node->id());
         // Make sure we get revision information.
         $nodes[] = clone $node;
     }
     $this->nodes = $nodes;
     $this->revisionLogs = $logs;
 }
 /**
  * Tests exportContentWithReferences().
  */
 public function testExportWithReferences()
 {
     \Drupal::service('module_installer')->install(['node', 'default_content']);
     \Drupal::service('router.builder')->rebuild();
     $this->defaultContentManager = \Drupal::service('default_content.manager');
     $user = User::create(['name' => 'my username']);
     $user->save();
     // Reload the user to get the proper casted values from the DB.
     $user = User::load($user->id());
     $node_type = NodeType::create(['type' => 'test']);
     $node_type->save();
     $node = Node::create(['type' => $node_type->id(), 'title' => 'test node', 'uid' => $user->id()]);
     $node->save();
     // Reload the node to get the proper casted values from the DB.
     $node = Node::load($node->id());
     /** @var \Symfony\Component\Serializer\Serializer $serializer */
     $serializer = \Drupal::service('serializer');
     \Drupal::service('rest.link_manager')->setLinkDomain(DefaultContentManager::LINK_DOMAIN);
     $expected_node = $serializer->serialize($node, 'hal_json', ['json_encode_options' => JSON_PRETTY_PRINT]);
     $expected_user = $serializer->serialize($user, 'hal_json', ['json_encode_options' => JSON_PRETTY_PRINT]);
     $exported_by_entity_type = $this->defaultContentManager->exportContentWithReferences('node', $node->id());
     // Ensure that the node type is not tryed to be exported.
     $this->assertEqual(array_keys($exported_by_entity_type), ['node', 'user']);
     // Ensure the right UUIDs are exported.
     $this->assertEqual([$node->uuid()], array_keys($exported_by_entity_type['node']));
     $this->assertEqual([$user->uuid()], array_keys($exported_by_entity_type['user']));
     // Compare the actual serialized data.
     $this->assertEqual(reset($exported_by_entity_type['node']), $expected_node);
     $this->assertEqual(reset($exported_by_entity_type['user']), $expected_user);
 }
  /**
   * Test Transliteration cleanup in File (Field) Paths.
   */
  public function testTransliteration() {
    // Create a File field.
    $field_name = Unicode::strtolower($this->randomMachineName());

    $third_party_settings['filefield_paths']['file_path']['value'] = 'node/[node:title]';
    $third_party_settings['filefield_paths']['file_path']['options']['transliterate'] = TRUE;
    $third_party_settings['filefield_paths']['file_name']['value'] = '[node:title].[file:ffp-extension-original]';
    $third_party_settings['filefield_paths']['file_name']['options']['transliterate'] = TRUE;

    $this->createFileField($field_name, 'node', $this->contentType, [], [], $third_party_settings);

    // Create a node with a test file.
    /** @var \Drupal\file\Entity\File $test_file */
    $test_file = $this->getTestFile('text');
    $edit['title[0][value]'] = 'тест';

    $edit['files[' . $field_name . '_0]'] = \Drupal::service('file_system')
      ->realpath($test_file->getFileUri());
    $this->drupalPostForm("node/add/{$this->contentType}", $edit, $this->t('Save and publish'));

    // Get created Node ID.
    $matches = [];
    preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
    $nid = $matches[1];

    // Ensure that file path/name have been processed correctly by
    // Transliteration.
    $node = Node::load($nid);
    $this->assertEqual($node->{$field_name}[0]->entity->getFileUri(), "public://node/test/test.txt", $this->t('File path/name has been processed correctly by Transliteration'));
  }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     //TODO v2 Send Email via Cron not on Submit
     $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
     $username = $user->get('name')->value;
     $userId = $user->get('uid')->value;
     $mailManager = \Drupal::service('plugin.manager.mail');
     $jobNode = \Drupal::routeMatch()->getParameter('node');
     $jobNodeTitle = $jobNode->getTitle();
     $companyNodeEntity = $jobNode->get('field_company');
     $companyNode = \Drupal\node\Entity\Node::load($companyNodeEntity->entity->id());
     $companyEmail = $companyNode->field_email->value;
     $resumeFileId = $form_state->getValue('resume');
     $resumeFile = db_select('file_managed', 'f')->condition('f.fid', $resumeFileId, '=')->fields('f', array('uri'))->execute()->fetchField();
     $atttachment = array('filepath' => $resumeFile);
     $module = 'job_mailer';
     $key = 'apply_job';
     $params['job_title'] = $jobNodeTitle;
     $params['message'] = "<html>\n           <p>Please see attached resume for user: {$username}\n           </html>";
     $params['attachment'] = $atttachment;
     $langcode = \Drupal::currentUser()->getPreferredLangcode();
     $send = true;
     $reply = \Drupal::config('system.site')->get('mail');
     $result = $mailManager->mail($module, $key, $companyEmail, $langcode, $params, $reply, $send);
     db_insert('user_job_application')->fields(array('job_id' => $jobNode->id(), 'user_id' => $userId, 'date' => date('Y-m-d H:i:s')))->execute();
     drupal_set_message('Your application has been sent.');
 }
Ejemplo n.º 16
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $html_raw = $this->curl_get($form_state->getValue('url'));
     $pattern = '/<div\\s*?class="k-grid-content">.*?<tbody[^>]*>(.*?)<\\/tbody>/msi';
     if (!preg_match($pattern, $html_raw, $matches)) {
         return;
     }
     $pattern = '/<a\\s*href="\\/codigo-postal-([^"]*)">/msi';
     if (!preg_match_all($pattern, $matches[1], $zipcodes_raw)) {
         return;
     }
     $zipcodes = array();
     foreach ($zipcodes_raw[1] as $zipcode_raw) {
         $zipcodes[$zipcode_raw] = $zipcode_raw;
     }
     ksort($zipcodes);
     // Build Pairs
     $state = $form_state->getValue('state');
     $city = $form_state->getValue('city');
     $zipcodesb = $zipcodes;
     $zipcodes_count = 0;
     foreach ($zipcodes as $zipcode_start) {
         foreach ($zipcodesb as $zipcode_end) {
             // Validate we don't already have it.
             if (\Drupal\zipcoderate\Controller\ZipCodeRateController::getRateNode(63175, 63175, false)) {
                 continue;
             }
             $zipcodes_count++;
             $node = \Drupal\node\Entity\Node::create(['title' => "{$city} {$state} - [{$zipcode_start} - {$zipcode_end}]", 'type' => 'rate', 'field_zipcode_start' => $zipcode_start, 'field_zipcode_end' => $zipcode_end, 'field_state' => $state, 'field_city' => $city]);
             $node->save();
         }
     }
     drupal_set_message(t('@zipcodes_count ZipCodes were Imported', array('@zipcodes_count' => $zipcodes_count)), 'status');
 }
  /**
   * Test Pathauto cleanup in File (Field) Paths.
   */
  public function testPathauto() {
    // Create a File field.
    $field_name = Unicode::strtolower($this->randomMachineName());

    $third_party_settings['filefield_paths']['file_path']['value'] = 'node/[node:title]';
    $third_party_settings['filefield_paths']['file_path']['options']['pathauto'] = TRUE;
    $third_party_settings['filefield_paths']['file_name']['value'] = '[node:title].[file:ffp-extension-original]';
    $third_party_settings['filefield_paths']['file_name']['options']['pathauto'] = TRUE;

    $this->createFileField($field_name, 'node', $this->contentType, [], [], $third_party_settings);

    // Create a node with a test file.
    /** @var \Drupal\file\Entity\File $test_file */
    $test_file = $this->getTestFile('text');
    $edit['title[0][value]'] = $this->randomString() . ' ' . $this->randomString();

    $edit['files[' . $field_name . '_0]'] = \Drupal::service('file_system')
      ->realpath($test_file->getFileUri());
    $this->drupalPostForm("node/add/{$this->contentType}", $edit, $this->t('Save and publish'));

    // Ensure that file path/name have been processed correctly by Pathauto.
    /** @var \Drupal\node\Entity\Node $node */
    $node = Node::load(1);

    $parts = explode('/', $node->getTitle());
    foreach ($parts as &$part) {
      $part = \Drupal::service('pathauto.alias_cleaner')->cleanString($part);
    }
    $title = implode('/', $parts);

    $this->assertEqual($node->{$field_name}[0]->entity->getFileUri(), "public://node/{$title}/{$title}.txt", $this->t('File path/name has been processed correctly by Pathauto'));
  }
Ejemplo n.º 18
0
 /**
  * Tests white-listing of methods doesn't interfere with chaining.
  */
 public function testWhiteListChaining()
 {
     $node = Node::create(['type' => 'page', 'title' => 'Some node mmk', 'status' => 1, 'field_term' => $this->term->id()]);
     $node->save();
     $this->setRawContent(twig_render_template(drupal_get_path('theme', 'test_theme') . '/templates/node.html.twig', ['node' => $node]));
     $this->assertText('Sometimes people are just jerks');
 }
Ejemplo n.º 19
0
 public static function saveExpo_new($d)
 {
     $viewhash = self::_gen_hash('field_viewhash');
     $edithash = self::_gen_hash('field_edithash');
     //$node->field_image->setValue([
     //'target_id' => $file->id(),
     //]);
     $node_values = array('type' => 'expo', 'title' => $d['title'], 'langcode' => 'und', 'uid' => '1', 'status' => 1, 'field_edithash' => ['value' => $edithash], 'field_viewhash' => ['value' => $viewhash], 'field_authoremail' => ['value' => $d['email']], 'field_author_plain' => ['value' => $d['author']], 'field_public' => ['value' => $d['public']], 'field_showinfront' => ['value' => $d['showinfront']], 'field_hide' => ['value' => $d['hide']], 'field_highlight' => ['value' => $d['highlight']], 'field_weight' => ['value' => $d['weight']], 'path' => '/p/' . $viewhash);
     if (is_array($d['body'])) {
         $node_values['field_body'] = $d['body'];
     } else {
         $node_values['field_body'] = ['format' => 'rich_html_base', 'value' => $d['body']];
     }
     if ($d['featuredimage']) {
         if (is_array($d['featuredimage'])) {
             $node_values['field_featuredimage'] = $d['featuredimage'];
         }
     }
     $node = Node::create($node_values);
     $node->save();
     foreach ($d['collitems'] as $item) {
         $collitem = ['field_name' => 'field_collitem'];
         $collitem['field_target'] = array('value' => $item['target']);
         if ($item['annotation']) {
             $collitem['field_annotation'] = $item['annotation'];
         }
         $fcitem = FieldCollectionItem::create($collitem);
         $fcitem->setHostEntity($node, false);
         $node->{$fcitem->bundle()}[] = array('field_collection_item' => $fcitem);
         $fcitem->save(true);
     }
     $node->save();
     return $node;
 }
Ejemplo n.º 20
0
  /**
   * Lists all instances of fields on any views.
   *
   * @return array
   *   The Views fields report page.
   */
  public function nodeMarkup($node, $key = 'default') {
    $node = Node::load($node);

    $builded_entity = entity_view($node, $key);
    $markup = drupal_render($builded_entity);

    $links = array();
    $links['default'] = array(
      'title' => 'Default',
      'url' => Url::fromRoute('ds_devel.markup', array('node' => $node->id())),
    );
    $view_modes = \Drupal::entityManager()->getViewModes('node');
    foreach ($view_modes as $id => $info) {
      if (!empty($info['status'])) {
        $links[] = array(
          'title' => $info['label'],
          'url' => Url::fromRoute('ds_devel.markup_view_mode', array('node' => $node->id(), 'key' => $id)),
        );
      }
    }

    $build['links'] = array(
      '#theme' => 'links',
      '#links' => $links,
      '#prefix' => '<div>',
      '#suffix' => '</div><hr />',
    );
    $build['markup'] = [
      '#markup' => '<code><pre>' . Html::escape($markup) . '</pre></code>',
      '#allowed_tags' => ['code', 'pre'],
    ];

    return $build;
  }
Ejemplo n.º 21
0
 function testMenuTokens()
 {
     // Add a menu.
     $menu = entity_create('menu', array('id' => 'main-menu', 'label' => 'Main menu', 'description' => 'The <em>Main</em> menu is used on many sites to show the major sections of the site, often in a top navigation bar.'));
     $menu->save();
     // Add a root link.
     /** @var \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent $root_link */
     $root_link = entity_create('menu_link_content', array('link' => ['uri' => 'internal:/admin'], 'title' => 'Administration', 'menu_name' => 'main-menu'));
     $root_link->save();
     // Add another link with the root link as the parent.
     /** @var \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent $parent_link */
     $parent_link = entity_create('menu_link_content', array('link' => ['uri' => 'internal:/admin/config'], 'title' => 'Configuration', 'menu_name' => 'main-menu', 'parent' => $root_link->getPluginId()));
     $parent_link->save();
     // Test menu link tokens.
     $tokens = array('id' => $parent_link->getPluginId(), 'title' => 'Configuration', 'menu' => 'Main menu', 'menu:name' => 'Main menu', 'menu:machine-name' => $menu->id(), 'menu:description' => 'The <em>Main</em> menu is used on many sites to show the major sections of the site, often in a top navigation bar.', 'menu:menu-link-count' => '2', 'menu:edit-url' => \Drupal::url('entity.menu.edit_form', ['menu' => 'main-menu'], array('absolute' => TRUE)), 'url' => \Drupal::url('system.admin_config', [], array('absolute' => TRUE)), 'url:absolute' => \Drupal::url('system.admin_config', [], array('absolute' => TRUE)), 'url:relative' => \Drupal::url('system.admin_config', [], array('absolute' => FALSE)), 'url:path' => 'admin/config', 'url:alias' => 'admin/config', 'edit-url' => \Drupal::url('entity.menu_link_content.canonical', ['menu_link_content' => $parent_link->id()], array('absolute' => TRUE)), 'parent' => 'Administration', 'parent:id' => $root_link->getPluginId(), 'parent:title' => 'Administration', 'parent:menu' => 'Main menu', 'parent:parent' => NULL, 'parents' => 'Administration', 'parents:count' => 1, 'parents:keys' => $root_link->getPluginId(), 'root' => 'Administration', 'root:id' => $root_link->getPluginId(), 'root:parent' => NULL, 'root:root' => NULL);
     $this->assertTokens('menu-link', array('menu-link' => $parent_link), $tokens);
     // Add a node.
     $node = $this->drupalCreateNode();
     // Allow main menu for this node type.
     //$this->config('menu.entity.node.' . $node->getType())->set('available_menus', array('main-menu'))->save();
     // Add a node menu link.
     /** @var \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent $node_link */
     $node_link = entity_create('menu_link_content', array('link' => ['uri' => 'entity:node/' . $node->id()], 'title' => 'Node link', 'parent' => $parent_link->getPluginId(), 'menu_name' => 'main-menu'));
     $node_link->save();
     // Test [node:menu] tokens.
     $tokens = array('menu-link' => 'Node link', 'menu-link:id' => $node_link->getPluginId(), 'menu-link:title' => 'Node link', 'menu-link:menu' => 'Main menu', 'menu-link:url' => $node->url('canonical', ['absolute' => TRUE]), 'menu-link:url:path' => 'node/' . $node->id(), 'menu-link:edit-url' => $node_link->url('edit-form', ['absolute' => TRUE]), 'menu-link:parent' => 'Configuration', 'menu-link:parent:id' => $parent_link->getPluginId(), 'menu-link:parents' => 'Administration, Configuration', 'menu-link:parents:count' => 2, 'menu-link:parents:keys' => $root_link->getPluginId() . ', ' . $parent_link->getPluginId(), 'menu-link:root' => 'Administration', 'menu-link:root:id' => $root_link->getPluginId());
     $this->assertTokens('node', array('node' => $node), $tokens);
     // Reload the node which will not have $node->menu defined and re-test.
     $loaded_node = Node::load($node->id());
     $this->assertTokens('node', array('node' => $loaded_node), $tokens);
     // Regression test for http://drupal.org/node/1317926 to ensure the
     // original node object is not changed when calling menu_node_prepare().
     $this->assertTrue(!isset($loaded_node->menu), t('The $node->menu property was not modified during token replacement.'), 'Regression');
 }
 /**
  * Tests that the autocomplete input element appears and the creation of a new
  * entity.
  */
 public function testAutoCreate()
 {
     $this->drupalGet('node/add/' . $this->referencingType);
     $this->assertFieldByXPath('//input[@id="edit-test-field-0-target-id" and contains(@class, "form-autocomplete")]', NULL, 'The autocomplete input element appears.');
     $new_title = $this->randomMachineName();
     // Assert referenced node does not exist.
     $base_query = \Drupal::entityQuery('node');
     $base_query->condition('type', $this->referencedType)->condition('title', $new_title);
     $query = clone $base_query;
     $result = $query->execute();
     $this->assertFalse($result, 'Referenced node does not exist yet.');
     $edit = array('title[0][value]' => $this->randomMachineName(), 'test_field[0][target_id]' => $new_title);
     $this->drupalPostForm("node/add/{$this->referencingType}", $edit, 'Save');
     // Assert referenced node was created.
     $query = clone $base_query;
     $result = $query->execute();
     $this->assertTrue($result, 'Referenced node was created.');
     $referenced_nid = key($result);
     $referenced_node = Node::load($referenced_nid);
     // Assert the referenced node is associated with referencing node.
     $result = \Drupal::entityQuery('node')->condition('type', $this->referencingType)->execute();
     $referencing_nid = key($result);
     $referencing_node = Node::load($referencing_nid);
     $this->assertEqual($referenced_nid, $referencing_node->test_field->target_id, 'Newly created node is referenced from the referencing node.');
     // Now try to view the node and check that the referenced node is shown.
     $this->drupalGet('node/' . $referencing_node->id());
     $this->assertText($referencing_node->label(), 'Referencing node label found.');
     $this->assertText($referenced_node->label(), 'Referenced node label found.');
 }
Ejemplo n.º 23
0
 /**
  * Tests the node summary length functionality.
  */
 public function testSummaryLength()
 {
     /** @var \Drupal\Core\Render\RendererInterface $renderer */
     $renderer = $this->container->get('renderer');
     // Create a node to view.
     $settings = array('body' => array(array('value' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam vitae arcu at leo cursus laoreet. Curabitur dui tortor, adipiscing malesuada tempor in, bibendum ac diam. Cras non tellus a libero pellentesque condimentum. What is a Drupalism? Suspendisse ac lacus libero. Ut non est vel nisl faucibus interdum nec sed leo. Pellentesque sem risus, vulputate eu semper eget, auctor in libero. Ut fermentum est vitae metus convallis scelerisque. Phasellus pellentesque rhoncus tellus, eu dignissim purus posuere id. Quisque eu fringilla ligula. Morbi ullamcorper, lorem et mattis egestas, tortor neque pretium velit, eget eleifend odio turpis eu purus. Donec vitae metus quis leo pretium tincidunt a pulvinar sem. Morbi adipiscing laoreet mauris vel placerat. Nullam elementum, nisl sit amet scelerisque malesuada, dolor nunc hendrerit quam, eu ultrices erat est in orci. Curabitur feugiat egestas nisl sed accumsan.')), 'promote' => 1);
     $node = $this->drupalCreateNode($settings);
     $this->assertTrue(Node::load($node->id()), 'Node created.');
     // Render the node as a teaser.
     $content = $this->drupalBuildEntityView($node, 'teaser');
     $this->assertTrue(strlen($content['body'][0]['#markup']) < 600, 'Teaser is less than 600 characters long.');
     $this->setRawContent($renderer->renderRoot($content));
     // The string 'What is a Drupalism?' is between the 200th and 600th
     // characters of the node body, so it should be included if the summary is
     // 600 characters long.
     $expected = 'What is a Drupalism?';
     $this->assertRaw($expected);
     // Change the teaser length for "Basic page" content type.
     $display = entity_get_display('node', $node->getType(), 'teaser');
     $display_options = $display->getComponent('body');
     $display_options['settings']['trim_length'] = 200;
     $display->setComponent('body', $display_options)->save();
     // Render the node as a teaser again and check that the summary is now only
     // 200 characters in length and so does not include 'What is a Drupalism?'.
     $content = $this->drupalBuildEntityView($node, 'teaser');
     $this->assertTrue(strlen($content['body'][0]['#markup']) < 200, 'Teaser is less than 200 characters long.');
     $this->setRawContent($renderer->renderRoot($content));
     $this->assertText($node->label());
     $this->assertNoRaw($expected);
 }
Ejemplo n.º 24
0
 /**
  * Create an overview of webform content.
  */
 public function contentOverview()
 {
     // @todo This needs to be removed and the view webform_webforms used instead.
     $query = db_select('webform', 'w');
     $query->join('node', 'n', 'w.nid = n.nid');
     $query->fields('n');
     $nodes = $query->execute()->fetchAllAssoc('nid');
     module_load_include('inc', 'webform', 'includes/webform.admin');
     $header = array(t('Title'), array('data' => t('View'), 'colspan' => '4'), array('data' => t('Operations'), 'colspan' => '3'));
     $rows = array();
     if (!empty($nodes)) {
         foreach ($nodes as $node) {
             $node = Node::load($node->nid);
             $rows[] = array(\Drupal::l($node->getTitle(), Url::fromRoute('entity.node.canonical', ['node' => $node->id()])), t('Submissions'), t('Analysis'), t('Table'), t('Download'), $node->access('update') ? \Drupal::l(t('Edit'), Url::fromRoute('entity.node.edit_form', ['node' => $node->id()])) : '', t('Components'), t('Clear'));
         }
     }
     if (empty($nodes)) {
         $webform_types = webform_node_types();
         if (empty($webform_types)) {
             $message = t('Webform is currently not enabled on any content types.') . ' ' . t('Visit the <a href="!url">Webform settings</a> page and enable Webform on at least one content type.', array('!url' => Url::fromRoute('webform.settings')->toString()));
         } else {
             $webform_type_list = webform_admin_type_list();
             $message = t('There are currently no webforms on your site. Create a !types piece of content.', array('!types' => $webform_type_list));
         }
         $rows[] = array(array('data' => $message, 'colspan' => 7));
     }
     $table = array('#type' => 'table', '#header' => $header, '#rows' => $rows);
     return $table;
 }
Ejemplo n.º 25
0
 public function createICal($nid)
 {
     $node = \Drupal\node\Entity\Node::load($nid);
     $eventdate = $node->get('field_event_date')->getValue();
     $title = $node->get('title')->getValue();
     $title = $title[0]['value'];
     $startdate = $eventdate[0]['value'];
     $enddate = $eventdate[1]['value'];
     if (empty($enddate)) {
         $enddate = $startdate;
     }
     $startdate = self::convertDateToICal($startdate);
     $enddate = self::convertDateToICal($enddate);
     $filecontents = self::buildICSFile($startdate, $enddate, $title, $nid);
     // open raw memory as file so no temp files needed, you might run out of memory though
     $file = fopen('php://memory', 'w');
     fwrite($file, $filecontents);
     // reset the file pointer to the start of the file
     rewind($file);
     // tell the browser it's going to be a calendar file
     header('Content-Type: text/calendar; charset=utf-8');
     // tell the browser we want to save it instead of displaying it
     header('Content-Disposition: attachment; filename="calendar.ics";');
     header('Cache-Control: store, no-cache, must-revalidate, post-check=0, pre-check=0');
     // make php send the generated file to the browser
     fpassthru($file);
     exit;
     /*
     	return array(
     		'#type' => 'markup',
     		'#markup' => $this->t('Hello, ical World!<pre>' . $filecontents . "</pre>"),
     	);
     */
 }
Ejemplo n.º 26
0
 /**
  * Test node migration from Drupal 6 to 8.
  */
 public function testNode()
 {
     $node = Node::load(1);
     $this->assertIdentical('1', $node->id(), 'Node 1 loaded.');
     $this->assertIdentical('und', $node->langcode->value);
     $this->assertIdentical('test', $node->body->value);
     $this->assertIdentical('test', $node->body->summary);
     $this->assertIdentical('filtered_html', $node->body->format);
     $this->assertIdentical('story', $node->getType(), 'Node has the correct bundle.');
     $this->assertIdentical('Test title', $node->getTitle(), 'Node has the correct title.');
     $this->assertIdentical('1388271197', $node->getCreatedTime(), 'Node has the correct created time.');
     $this->assertIdentical(FALSE, $node->isSticky());
     $this->assertIdentical('1', $node->getOwnerId());
     $this->assertIdentical('1420861423', $node->getRevisionCreationTime());
     /** @var \Drupal\node\NodeInterface $node_revision */
     $node_revision = \Drupal::entityManager()->getStorage('node')->loadRevision(1);
     $this->assertIdentical('Test title', $node_revision->getTitle());
     $this->assertIdentical('1', $node_revision->getRevisionAuthor()->id(), 'Node revision has the correct user');
     // This is empty on the first revision.
     $this->assertIdentical(NULL, $node_revision->revision_log->value);
     // Test that we can re-import using the EntityContentBase destination.
     $connection = Database::getConnection('default', 'migrate');
     $connection->update('node_revisions')->fields(array('title' => 'New node title', 'format' => 2))->condition('vid', 1)->execute();
     $connection->delete('content_field_test_two')->condition('delta', 1)->execute();
     $migration = Migration::load('d6_node__story');
     $this->executeMigration($migration);
     $node = Node::load(1);
     $this->assertIdentical('New node title', $node->getTitle());
     // Test a multi-column fields are correctly upgraded.
     $this->assertIdentical('test', $node->body->value);
     $this->assertIdentical('full_html', $node->body->format);
 }
 /**
  * Assert sorting by field and property.
  */
 public function testSort()
 {
     // Add text field to entity, to sort by.
     entity_create('field_storage_config', array('field_name' => 'field_text', 'entity_type' => 'node', 'type' => 'text', 'entity_types' => array('node')))->save();
     entity_create('field_config', array('label' => 'Text Field', 'field_name' => 'field_text', 'entity_type' => 'node', 'bundle' => 'article', 'settings' => array(), 'required' => FALSE))->save();
     // Build a set of test data.
     $node_values = array('published1' => array('type' => 'article', 'status' => 1, 'title' => 'Node published1 (<&>)', 'uid' => 1, 'field_text' => array(array('value' => 1))), 'published2' => array('type' => 'article', 'status' => 1, 'title' => 'Node published2 (<&>)', 'uid' => 1, 'field_text' => array(array('value' => 2))));
     $nodes = array();
     $node_labels = array();
     foreach ($node_values as $key => $values) {
         $node = Node::create($values);
         $node->save();
         $nodes[$key] = $node;
         $node_labels[$key] = SafeMarkup::checkPlain($node->label());
     }
     $selection_options = array('target_type' => 'node', 'handler' => 'default', 'handler_settings' => array('target_bundles' => array(), 'sort' => array('field' => 'field_text.value', 'direction' => 'DESC')));
     $handler = $this->container->get('plugin.manager.entity_reference_selection')->getInstance($selection_options);
     // Not only assert the result, but make sure the keys are sorted as
     // expected.
     $result = $handler->getReferenceableEntities();
     $expected_result = array($nodes['published2']->id() => $node_labels['published2'], $nodes['published1']->id() => $node_labels['published1']);
     $this->assertIdentical($result['article'], $expected_result, 'Query sorted by field returned expected values.');
     // Assert sort by base field.
     $selection_options['handler_settings']['sort'] = array('field' => 'nid', 'direction' => 'ASC');
     $handler = $this->container->get('plugin.manager.entity_reference_selection')->getInstance($selection_options);
     $result = $handler->getReferenceableEntities();
     $expected_result = array($nodes['published1']->id() => $node_labels['published1'], $nodes['published2']->id() => $node_labels['published2']);
     $this->assertIdentical($result['article'], $expected_result, 'Query sorted by property returned expected values.');
 }
Ejemplo n.º 28
0
 /**
  * Tests if statistics.js is loaded when content is not printed.
  */
 public function testAttached()
 {
     $node = Node::create(['type' => 'page', 'title' => 'Page node', 'body' => 'body text']);
     $node->save();
     $this->drupalGet('node/' . $node->id());
     $this->assertRaw('core/modules/statistics/statistics.js', 'Statistics library is available');
 }
Ejemplo n.º 29
0
 /**
  * {@inheritdoc}
  */
 public function nodeDelete($node)
 {
     $node = $node instanceof NodeInterface ? $node : Node::load($node->nid);
     if ($node instanceof NodeInterface) {
         $node->delete();
     }
 }
 /**
  * Tests that default values are correctly translated to UUIDs in config.
  */
 function testEntityReferenceDefaultValue()
 {
     // Create a node to be referenced.
     $referenced_node = $this->drupalCreateNode(array('type' => 'referenced_content'));
     $field_name = Unicode::strtolower($this->randomMachineName());
     $field_storage = FieldStorageConfig::create(array('field_name' => $field_name, 'entity_type' => 'node', 'type' => 'entity_reference', 'settings' => array('target_type' => 'node')));
     $field_storage->save();
     $field = FieldConfig::create(['field_storage' => $field_storage, 'bundle' => 'reference_content', 'settings' => array('handler' => 'default', 'handler_settings' => array('target_bundles' => array('referenced_content'), 'sort' => array('field' => '_none')))]);
     $field->save();
     // Set created node as default_value.
     $field_edit = array('default_value_input[' . $field_name . '][0][target_id]' => $referenced_node->getTitle() . ' (' . $referenced_node->id() . ')');
     $this->drupalPostForm('admin/structure/types/manage/reference_content/fields/node.reference_content.' . $field_name, $field_edit, t('Save settings'));
     // Check that default value is selected in default value form.
     $this->drupalGet('admin/structure/types/manage/reference_content/fields/node.reference_content.' . $field_name);
     $this->assertRaw('name="default_value_input[' . $field_name . '][0][target_id]" value="' . $referenced_node->getTitle() . ' (' . $referenced_node->id() . ')', 'The default value is selected in instance settings page');
     // Check if the ID has been converted to UUID in config entity.
     $config_entity = $this->config('field.field.node.reference_content.' . $field_name)->get();
     $this->assertTrue(isset($config_entity['default_value'][0]['target_uuid']), 'Default value contains target_uuid property');
     $this->assertEqual($config_entity['default_value'][0]['target_uuid'], $referenced_node->uuid(), 'Content uuid and config entity uuid are the same');
     // Ensure the configuration has the expected dependency on the entity that
     // is being used a default value.
     $this->assertEqual(array($referenced_node->getConfigDependencyName()), $config_entity['dependencies']['content']);
     // Clear field definitions cache in order to avoid stale cache values.
     \Drupal::entityManager()->clearCachedFieldDefinitions();
     // Create a new node to check that UUID has been converted to numeric ID.
     $new_node = Node::create(['type' => 'reference_content']);
     $this->assertEqual($new_node->get($field_name)->offsetGet(0)->target_id, $referenced_node->id());
     // Ensure that the entity reference config schemas are correct.
     $field_config = $this->config('field.field.node.reference_content.' . $field_name);
     $this->assertConfigSchema(\Drupal::service('config.typed'), $field_config->getName(), $field_config->get());
     $field_storage_config = $this->config('field.storage.node.' . $field_name);
     $this->assertConfigSchema(\Drupal::service('config.typed'), $field_storage_config->getName(), $field_storage_config->get());
 }