dimanche 1 mai 2016

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('http://ift.tt/1N0ZEAU');
$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?




Aucun commentaire:

Enregistrer un commentaire