As we know drupal 8 use symphony, so module structure of drupal 8 is change and workflow functionality of doing thing also change. we can make Drupal 7 module procedure oriented but in drupal 8 module needs to follow object oriented MVC architecture.
In this tutorail we learn how can we create the node programmatically in drupal 8 with image upload using custom module.
Let say module name is "nodecreator"
1) To Create a module we need a nodecreator.info.yml file
name: Node Creater
type: module
description: Node created programmatically
package: Custom
core: 8.x
2) Now you can enable the module at "/admin/modules" path on your website.
3) Create a routing file nodecreator.routing.yml for menu path to call a controller function
nodecreator:
path: /add/nodecreate
defaults:
_controller: Drupal\nodecreator\Controller\PostController::newnode
requirements:
_permission: 'access content'
4) Create a controller file in module folder using this folder structure - "src/Controller/PostController.php" and add following content
<?php
namespace Drupal\nodecreator\Controller;
use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;
class PostController {
public function newnode() {
$data = file_get_contents("path/data-folder/image.png");
$file = file_save_data($data, "public://image.png", FILE_EXISTS_REPLACE);
// Create node object and save it.
$node = Node::create([
'type'=> 'article',
'title'=> 'Node By Email',
'body'=> 'This is just a content',
'field_image'=> [
'target_id' => $file->id(),
'alt' => 'Sample',
'title' => 'nodecreate Image'
],
]);
$node->save();
return array(
'#title' => 'Node Creator',
'#markup' => 'Node Created Successfully.',
);
}
}
5) Now open the path "/add/nodecreate" and your node will we created.
Note : That example is use for creating articles content with body and field_image field, if you not have that field or having different name, please change it else you will get error.
Please Comment your thoughts and feedback below and add something if you found good in anywhere to help others
Hit a like Button If you like the Post.
Many Thanks
its helpful