14

I got some difficulties setting a taxonomy for a node. Currently I am using this code.

$node = Node::create(array(
    'type' => 'detailseite',
    'title' => $data[$headlineIndex],
    'langcode' => 'de',
    'uid' => '1',
    'status' => 1,
    'field_headline' => $data[$headlineIndex],
    'field_intro' => $data[$introIndex] . $categories[$data[$categoryIndex]],
    'created' => $data[$dateIndex],
    'field_autor' => $data[$autorIndex],
    'field_teaser_text' => $data[$shortIndex],
    'field_fields' => array(),
));
$node->save();

Which works fine so far (below an image of the fields of "detailseite").

enter image description here

Everything gets set correctly and I can find the newly created nodes in the admin area that work correctly. Now I need to set 'field_meldungstyp' which is an Entity-Reference to a Taxonomy:

enter image description here

which already contains three entries:

I want to get the node(s) I created programmatically to have "field_meldungstyp" set to "Artikel" of the "Meldungstyp"-Vocabulary.

I already tried adding:

'field_meldungstyp' => array( 'tid' => 19 ),

where 19 is the tid of "Artikel" of the earlier mentioned vocabulary. And that's where I'm stuck. Also https ://www.drupal.org/node/2402811 didn't work for me. As well as

$node->field_meldungstyp[$node->language][]['tid'] = 19;

didn't work either.

simply adding

$node = Node::create(array(
    ...
    'field_meldungstyp' => 19,
    ...
));

results in crashing with the following error:

Drupal\Core\Entity\EntityStorageException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'datetime' for column 'created' at row 1: INSERT INTO {taxonomy_index} (nid, tid, status, sticky, created) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => 343 [:db_insert_placeholder_1] => 19 [:db_insert_placeholder_2] => 1 [:db_insert_placeholder_3] => 0 [:db_insert_placeholder_4] => datetime ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 770 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php). Drupal\Core\Database\Statement->execute(Array, Array) (Line: 610) Drupal\Core\Database\Connection->query('INSERT INTO {taxonomy_index} (nid, tid, status, sticky, created) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4)', Array, Array) (Line: 81) Drupal\Core\Database\Driver\mysql\Connection->query('INSERT INTO {taxonomy_index} (nid, tid, status, sticky, created) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4)', Array, Array) (Line: 32) Drupal\Core\Database\Driver\mysql\Insert->execute() (Line: 371) Drupal\Core\Database\Query\Merge->execute() (Line: 525) taxonomy_build_node_index(Object) (Line: 479) taxonomy_node_insert(Object) call_user_func_array('taxonomy_node_insert', Array) (Line: 402) Drupal\Core\Extension\ModuleHandler->invokeAll('node_insert', Array) (Line: 167) Drupal\Core\Entity\EntityStorageBase->invokeHook('insert', Object) (Line: 418) Drupal\Core\Entity\ContentEntityStorageBase->invokeHook('insert', Object) (Line: 470) Drupal\Core\Entity\EntityStorageBase->doPostSave(Object, ) (Line: 304) Drupal\Core\Entity\ContentEntityStorageBase->doPostSave(Object, ) (Line: 395) Drupal\Core\Entity\EntityStorageBase->save(Object) (Line: 761) Drupal\Core\Entity\Sql\SqlContentEntityStorage->save(Object) (Line: 364) Drupal\Core\Entity\Entity->save() (Line: 46) Drupal\awo_importer\Controller\T3ImporterController->import() call_user_func_array(Array, Array) (Line: 123) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 574) Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() call_user_func_array(Object, Array) (Line: 144) Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 64) Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57) Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 98) Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 77) Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50) Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23) Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 628) Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

5 Answers 5

14

It needs to be a nested array.

'field_meldungstyp'  => [
      ['target_id' => 12345]
    ]

Try this:

$node = Node::create(array(
    'type' => 'detailseite',
    'title' => $data[$headlineIndex],
    'langcode' => 'de',
    'uid' => '1',
    'status' => 1,
    'field_headline' => $data[$headlineIndex],
    'field_intro' => $data[$introIndex] . $categories[$data[$categoryIndex]],
    'created' => $data[$dateIndex],
    'field_autor' => $data[$autorIndex],
    'field_teaser_text' => $data[$shortIndex],
    'field_meldungstyp'  => [
      ['target_id' => 12345]
    ]
));
$node->save();
2
  • That somewhat crashes too with (I exchanged 12345 to 19 accordingly ;) )Drupal\Core\Entity\EntityStorageException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'datetime' for column 'created' at row 1: INSERT INTO {taxonomy_index} (nid, tid, status, sticky, created) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => 188 [:db_insert_placeholder_1] => 19 [:db_insert_placeholder_2] => ... in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() Oct 12, 2016 at 6:57
  • you have an error with your "created" field, it needs to be a unix timestamp. If you remove created from your array, the error will go away. Try it.
    – oknate
    Oct 12, 2016 at 11:41
16

In Drupal 7, taxonomy reference fields existed which used the pattern ['tid' => NUMBER]. These are entity reference fields. The EntityReferenceItem has the property definitions: target_id and entity. The former is a either an integer or string depending on the entity reference item's settings (basically config/content entity type).

This is also a similar question to How to set value for multivalue field in drupal 8 programmatically

So try to use the pattern

As part of Entity::create

Node::create([
  'field_meldungstyp' => [['target_id' => 19]]
]);

Using FieldableEntityInterface::set

$entity->set('field_meldungstyp', ['target_id' => 19]);

Using TypedDataInterface::setValue on the field item directly.

$entity->field_meldungstyp->setValue(['target_id' => 19]);

With magic method

$entity->field_meldungstyp->target_id = 19;

Note that this overwrites any current values of the field.

6
  • I find Content Entity documentation a bit incomplete as it is not clear how to set a field item other than the value magic method. For base fields it's a string or integer, but field items it should include the full field item list values?
    – mradcliffe
    Oct 11, 2016 at 13:38
  • Unfortunately still results in -syntax error, unexpected '=', expecting ']'- for me when I add any of those right before $node->save. Even if I change the whole thing over to something like "entity_create('node', $node)" and removing Node::create, the line results in a crash. Maybe there is something wrong with my Drupal install itself of I'm missing something. Oct 11, 2016 at 13:55
  • Did you see the syntax error in my answer? Correct it. It should be => not =. :-)
    – mradcliffe
    Oct 11, 2016 at 13:57
  • I guess I really need a break ;D (working on that the whole day already), => still gives me syntax error, unexpected '=>' (T_DOUBLE_ARROW). Oct 11, 2016 at 14:18
  • 1
    "$entity->field_meldungstyp->value = [['target_id' => 19]];". That's not correct. What you want is $entity->field_meldungstyp->target_id = 19. Note that also just providing 19 without the array works for set(), setValue() and even $node->field-meldungstyp = 19 should work for a single value field. The field type will attempt to convert it into the correct stucture automatically.
    – Berdir
    Oct 12, 2016 at 18:19
4

Here is how i did it for D8.

use Drupal\node\Entity\Node;

//To create new node
$node = Node::create(['type' => 'YOUR_CONTENT_TYPE_HERE']);

//To load a node by its ID
//$node = \Drupal\node\Entity\Node::load(NODE_ID);

$nodeTerms = [1,2,3...]; // 1,2,3 = terms IDs
$node->set('YOUR_FIELD_OF_TERMS', $nodeTerms);
$node->save();

//To create new tax

use Drupal\taxonomy\Entity\Term;

$new_term = Term::create([
    'vid' => "YOUR_VOCABULARY_MACHINE_NAME",
    'name' => "NAME_OF_YOUR_TERM",
]);
$new_term->save();
2

Another approach would be to update the node after creation, like this:

$node = Node::create(array(
    ...
));
$node->save();
$node->field_meldungstyp->target_id = 19;
$node->save();
7
  • Tried that too initally and it crashed. I'll add the output to the top. Oct 11, 2016 at 13:31
  • okey - so try target_id
    – rémy
    Oct 11, 2016 at 14:04
  • Unfortunately same results/error-message. :( Oct 11, 2016 at 14:10
  • Then I would update the field after creation (save) - updated my answer. Have you tried the nested array with the key target_id ?
    – rémy
    Oct 11, 2016 at 16:41
  • Yeah, tried it, unfortunately same error as here [link[(drupal.stackexchange.com/questions/217396/…) Oct 12, 2016 at 6:59
1

Here's how I got this working in D9:

$node = \Drupal::entityTypeManager()->getStorage('node')->create([
  'type' => 'content type',
  'title' => 'node title',
  'field_tax_ref' => ['target_id' => '3'],
]);
$node->save();

field_tax_ref is a taxonomy entity reference field.

'3' is the tid of the term I want to reference.

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.

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