Answer the question
In order to leave comments, you need to log in
How to create a node programmatically in Drupal 8?
In general, I'm making a small script that should add content records of a certain type. It is possible to write down bare sql certainly, but it is very gemorno. How to add records using the tools of Drupal itself?
I found such examples on request "drupal 8 create node programmatically"
use Drupal\node\Entity\Node;
$node = Node::create([
// The node entity bundle.
]);
$node->save();
But writing this simply in a separate php script, which is in the root directory, I get the error "Class 'Drupal\node\Entity\Node' not found". How to use it correctly?
Answer the question
In order to leave comments, you need to log in
Use like this:
<?php
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
use Drupal\node\Entity\Node;
define('DRUPAL_DIR', '/путь/до/корня');
$autoloader = require_once DRUPAL_DIR . '/autoload.php';
$kernel = new DrupalKernel('prod', $autoloader);
$request = Request::createFromGlobals();
chdir(DRUPAL_DIR);
$response = $kernel->handle($request);
$kernel->terminate($request, $response);
$nid = 1488;
$node = Node::load($nid);
echo $node->body->value;
$php show_node_content.php
Use hook_update() or hook_install() in your module instead of the obscure file in the root directory - that would be using Drupal's own tools. But the file does not work for you, because the necessary classes are not included in it and the Drupal core is not initialized, see how index.php works for an example.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question