Vin.F Vin.F - 7 months ago 120
PHP Question

drupal 8 programmatically create node can only succeeded once

I'v created a new module in Drupal 8, it is just a hello world example.
the code just like the following

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

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


and I added the following code to the content() function to create a node .
but I found that it can only create the node once, and after that no matter how many time I refresh the module page it won't be creating any more new node again.

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();


any thing I'm doing wrong here?

Answer

You forgot about caching :) Your output is just cached, and that's why your code is called only once (to be more precise, not once, but until cache is valid). Take a look here: Render API and here: Cacheability of render arrays.

To disable caching for current page request you may use the following code:

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

So, your controller method may look like the following:

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(),
  );
}