本文整理汇总了PHP中Drupal\node\Entity\Node类的典型用法代码示例。如果您正苦于以下问题:PHP Node类的具体用法?PHP Node怎么用?PHP Node使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Node类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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);
}
示例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.");
}
}
示例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();
}
}
示例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));
}
}
示例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;
}
示例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.');
}
示例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.');
}
示例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.');
}
示例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');
}
}
示例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.');
}
示例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;
}
示例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);
}
示例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'));
}
示例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.');
}
示例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');
}