6

I've created a PHP program outside Drupal that inserts Terms into my Drupal installation.

define('DRUPAL_DIR', __DIR__);

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once DRUPAL_DIR . '/autoload.php';
$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();

require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';


$term = \Drupal\taxonomy\Entity\Term::create([
      'vid' => 'subject',
      'langcode' => 'en',
      'name' => 'Test af Tag',
      'description' => [
        'value' => '<p>My description.</p>',
        'format' => 'full_html',
      ],
      'weight' => -1,
      'parent' => array(0),
])->save();

var_dump($term);

My question is - how do I retrieve the newly created Term tid? The var_dump only gives a

string(9) "SAVED_NEW"

Why on earth doesn't it return the newly created Entity/Term?!?

I need it in case there will be a child Term later. I've looked at www.drupal.org/documentation and api.drupal.org. But those pages just confuses me more :-(

Thank you very much

8

Why on earth doesn't it return the newly created Entity/Term?!?

Why would it? You already have the term object, why do you need it to be chained in a return from a save method that can and does provide you with extra context??

Just use this:

$term = \Drupal\taxonomy\Entity\Term::create([
  'vid' => 'subject',
  'langcode' => 'en',
  'name' => 'Test af Tag',
  'description' => [
    'value' => '<p>My description.</p>',
    'format' => 'full_html',
  ],
  'weight' => -1,
  'parent' => array(0),
]);

$inserted_or_updated = $term->save();

$tid = $term->id();
  • Thank you very much - I learn a new important thing today. :-) – Lars Hansen Nov 26 '16 at 21:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.