drupal 8以编程方式创建节点只能成功一次

时间:2016-05-01 14:06:32

标签: php web drupal drupal-modules drupal-8

我在Drupal 8中创建了一个新模块,它只是一个hello world示例。 代码就像下面的

class FirstController{
public function content(){
return array(
      '#type' => 'markup',
      '#markup' => t('G\'day.............'),
    );

// <------I added the new node code here
}
}

我将以下代码添加到content()函数中以创建节点。 但是我发现它只能创建一次节点,之后无论我刷新模块页面多少次,它都不会再创建新的节点。

use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;

// Create file object from remote URL.
$data = file_get_contents('https://www.drupal.org/files/druplicon.small_.png');
$file = file_save_data($data, 'public://druplicon.png', FILE_EXISTS_REPLACE);

// Create node object with attached file.
$node = Node::create([
  'type'        => 'article',
  'title'       => 'Druplicon test',
  'field_image' => [
    'target_id' => $file->id(),
    'alt' => 'Hello world',
    'title' => 'Goodbye world'
  ],
]);
$node->save();

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

你忘记了缓存:)你的输出只是缓存,这就是为什么你的代码只被调用一次(更确切地说,不是一次,但直到缓存有效)。看看这里:Render API和这里:Cacheability of render arrays

要禁用当前页面请求的缓存,您可以使用以下代码:

\Drupal::service('page_cache_kill_switch')->trigger();

因此,您的控制器方法可能如下所示:

public function content() {

  // Create file object from remote URL.
  $data = file_get_contents('https://www.drupal.org/files/druplicon.small_.png');
  /** @var FileInterface $file */
  $file = file_save_data($data, 'public://druplicon.png', FILE_EXISTS_RENAME);

  // Create node object with attached file.
  $node = Node::create([
    'type'        => 'article',
    'title'       => 'Druplicon test',
    'field_image' => [
      'target_id' => $file->id(),
      'alt' => 'Hello world',
      'title' => 'Goodbye world'
    ],
  ]);
  $node->save();

  \Drupal::service('page_cache_kill_switch')->trigger();

  return array(
    '#markup' => 'Something ' . rand(),
  );
}