1

Some years ago I made a Drupal 7 site. I want to remake the site with Drupal 9.

In Drupal 7 I added nodes programmatically with this PHP code.

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$data = $_GET['d'];

AddNewNode($data);

function AddNewNode($data) {
  list($installlanguage, $playerid) = explode('|', $data);
  $node = new stdClass();
  $node->type = 'new_install';
  node_object_prepare($node);
  $node->language = LANGUAGE_NONE;
  $node->field_hm_new_installlanguage[$node->language][0]['value'] =   $installlanguage;
  $node->field_hm_new_install_playerid[$node->language][0]['value'] = $playerid;
  node_save($node);
}

The code doesn't work in Drupal 9.

I tried to search Google for drupal 9 add content programmatically, but I don't seem to get any useful result. Most links are about Drupal 8.

I also tried the following code, but I get this error.

Fatal error: Uncaught Error: Class "Drupal\node\Entity\Node" not found

use \Drupal\node\Entity\Node;

$data = $_GET['d'];
AddNewGameInstall($data);

function AddNewGameInstall($data) {
  $node = Node::create([
    'type' => 'new_game_install',
    'language' => LANGUAGE_NONE,
    'field_device_language' => $devicelanguage,
    'field_player_id' => $playerid
  ]);
  $node->save();
}

Can someone point me in the right direction?

9
  • 2
    Does this answer your question? Programmatically create nodes
    – leymannx
    Mar 22, 2021 at 21:00
  • There's not much of a difference between D8 and D9. Most of the D8 answers get constantly updated to replace deprecated code. stackoverflow.com/a/31823730/2199525
    – leymannx
    Mar 22, 2021 at 21:01
  • @leymannx Thank you for your help. I edited the code, but I'm getting an error. I guess I'm missing some initialization code.
    – Anna
    Mar 22, 2021 at 22:59
  • On what file are you adding this code?
    – No Sssweat
    Mar 23, 2021 at 9:46
  • @No Sssweat in xampp/htdocs/sitename/newgameinstall.php
    – Anna
    Mar 23, 2021 at 10:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.