• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP Entity\Node类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中Drupal\node\Entity\Node的典型用法代码示例。如果您正苦于以下问题:PHP Node类的具体用法?PHP Node怎么用?PHP Node使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Node类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: content

 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);
 }
开发者ID:augustpascual-mse,项目名称:job-searching-network,代码行数:25,代码来源:JobHistoryController.php


示例2: testNodeCounterIntegration

 /**
  * 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.");
     }
 }
开发者ID:eigentor,项目名称:tommiblog,代码行数:31,代码来源:IntegrationTest.php


示例3: mapAnalysisIssues

 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();
     }
 }
开发者ID:malcomio,项目名称:drupalytics,代码行数:8,代码来源:IssueMapper.php


示例4: assertNodeAccess

 /**
  * 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));
     }
 }
开发者ID:davidsoloman,项目名称:drupalconsole.com,代码行数:25,代码来源:NodeTestBase.php


示例5: tweetAboutArticle

 /**
  * 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;
 }
开发者ID:back-2-95,项目名称:ibloggedabout,代码行数:17,代码来源:IBloggedAbout.php


示例6: testUpdateHookN

 /**
  * 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.');
 }
开发者ID:aWEBoLabs,项目名称:taxi,代码行数:37,代码来源:LocalActionsAndTasksConvertedIntoBlocksUpdateTest.php


示例7: testFailedPageCreation

 /**
  * 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.');
 }
开发者ID:aWEBoLabs,项目名称:taxi,代码行数:31,代码来源:NodeCreationTest.php


示例8: testUpdateHookN

 /**
  * 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.');
 }
开发者ID:aWEBoLabs,项目名称:taxi,代码行数:28,代码来源:PageTitleConvertedIntoBlockUpdateTest.php


示例9: testNodeMultipleLoad

 /**
  * 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');
     }
 }
开发者ID:aWEBoLabs,项目名称:taxi,代码行数:32,代码来源:NodeLoadMultipleTest.php


示例10: testValidation

 /**
  * 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.');
 }
开发者ID:eigentor,项目名称:tommiblog,代码行数:34,代码来源:NodeValidationTest.php


示例11: setUp

 /**
  * {@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;
 }
开发者ID:nsp15,项目名称:Drupal8,代码行数:38,代码来源:NodeRevisionsTest.php


示例12: testExportWithReferences

 /**
  * 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);
 }
开发者ID:lokeoke,项目名称:d8intranet,代码行数:33,代码来源:DefaultContentManagerIntegrationTest.php


示例13: testTransliteration

  /**
   * 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'));
  }
开发者ID:eloiv,项目名称:botafoc.cat,代码行数:33,代码来源:FileFieldPathsTransliterationTest.php


示例14: submitForm

 /**
  * {@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.');
 }
开发者ID:augustpascual-mse,项目名称:job-searching-network,代码行数:30,代码来源:ApplyForm.php


示例15: submitForm

 /**
  * {@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');
 }
开发者ID:aWEBoLabs,项目名称:taxi,代码行数:37,代码来源:ZipCodeRateImportForm.php


示例16: testPathauto

  /**
   * 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'));
  }
开发者ID:eloiv,项目名称:botafoc.cat,代码行数:35,代码来源:FileFieldPathsPathautoTest.php


示例17: testWhiteListChaining

 /**
  * 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');
 }
开发者ID:318io,项目名称:318-io,代码行数:10,代码来源:TwigWhiteListTest.php


示例18: saveExpo_new

 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;
 }
开发者ID:318io,项目名称:318-io,代码行数:34,代码来源:ExpoCrud.php


示例19: nodeMarkup

  /**
   * 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;
  }
开发者ID:jkyto,项目名称:agolf,代码行数:40,代码来源:DsDevelController.php


示例20: testMenuTokens

 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');
 }
开发者ID:dev981,项目名称:gaptest,代码行数:34,代码来源:TokenMenuTest.php



注:本文中的Drupal\node\Entity\Node类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP Entity\NodeType类代码示例发布时间:2022-05-23
下一篇:
PHP node\NodeInterface类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap