This blog explains the process of programmatically creating nodes with multiple fields (text, image, entity reference) in Drupal 8/9 using a custom module.
Create a custom module:
Modules in Drupal are located in the /modules folder. We'll create two custom and contrib folders inside the /modules folder. Additional modules from drupal.org will be stored in the contrib folder, and our custom modules will be stored in the custom folder.
Create a .info.yml file:
Let's name our custom module "createnode". Create the folder /modules/custom/createnode. In this folder, we'll need to create a createnode.info.yml file and add the following code.
name: Create Node
type: module
description: Node is created programmatically with fields.
package: Custom
core_version_requirement: ^8.8.0 || ^9
Enable a module:
For all possible ways to enable a module click here.
Using the Manage administrative menu, navigate to the Extend page in the list of modules, search the create node module and then select its checkbox. Scroll down to the bottom of the webpage, and then click Install.
The Custom module Create Node has been enabled successfully.
Declaring a route:
The routing information is saved in createnode/createnode.routing.yml.
createnode:
path: /add/nodecreate/fields
defaults:
_controller: Drupal\createnode\Controller\PostController::newnode
requirements:
_permission: 'access content'
Adding a controller:
Create a new subfolder "modules/custom/createnode/src/Controller." Create a file called "PostController.php" in this folder with the following content:
<?php
namespace Drupal\createnode\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\File\FileSystemInterface;
use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;
class PostController extends ControllerBase {
public function newnode() {
$data = file_get_contents("/home/lakshmi/Pictures/mobile.jpeg");
$file = file_save_data($data, "public://image.png", FileSystemInterface::EXISTS_REPLACE);
$term_id = 3 ;
// Create a node object and save it.
$node = Node::create([
'type'=> 'page',
'title'=> 'Node created with fields',
'body'=> 'This is body field content',
//here field_name is a machine of the text field.
'field_name'=>'This is name of text field',
//here field_image is a machine name of the image field.
'field_image'=> [
'target_id' => $file->id(),
'alt' => 'Sample',
'title' => 'create node with image field
],
//here field_term is a machine of the entity reference field.
'field_term' => [
['target_id' => $term_id ]
],
]);
$node->save();
return [
'#title' => 'Node Creator',
'#markup' => 'Node Created Successfully.',
];
}
}
After clearing the cache, you should be able to see your customized page.
After the node is created successfully, then navigate to the /admin/content page.
Click "Node created with fields" then the output should be:
Finally, programmatically created node with text, entity reference, and image upload fields successfully.
Comments