Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By arkepp on
Hi,
In Drupal 8 I am able to create new nodes, but I cannot figure out how to populate a field referencing taxonomy terms.
$edit_node = array(
...
'field_category' => array('x-default' => array(array('target_id' => 48, 'target_type' => 'taxonomy_term')));
...
);
$node = entity_create('node', $edit_node);
$node->save();
The node is created, but I see no traces of the terms in the database.
I have also tried replacing 'x-default' with the actual language code, and I think field_category is mostly correct because I have been debugging ContentEntityStorageBase and I can see it examining the field. But I can't figure out why the values are not getting persisted.
Can anyone give me a hint ?
Comments
Simple solution
It turns out that the langcode wrapper should not be there. Nor is the target_type needed.
'field_category' => array( array( 'target_id' => 48 ) )
I can also confirm that this works.
//Add this in the top of the file you are using.
use Drupal\node\Entity\Node;
//Where you add node.
$category_id = 1;
$node = Node::create(array(
'type' => 'Node_bundle_machine_name',
'title' => Node_title,
'langcode' => 'en',
'uid' => '1',
'status' => 1, //1 means published
'field_text' => array(
'value' => 'String of text,
),
'field_category_reference' => array(
array( 'target_id' => $category_id ),
),
));
$node->save();
'field_category' => $tid,
'field_category' => $tid,
Adding above mapping in $node array like other fields will populate term reference field.
Hope this helps.
Thanks!!
neetu
This shorter code works
This shorter code works perfectly. Thank you all :-)
How would this work if you
How would this work if you wanted to add multiple taxonomy terms?
Tagging style vocabs
I'd also be interested in how to do this for vocabs that have been configured to ...
"Create referenced entities if they don't already exist"
I know could do this in D7, but I'm hoping someone could share a quick lead for D8 so I don't have to go on spelunking exercise
Thanks!
Matt
one option (It's not elegant)
I have not found a way for that to work, but I did find that this worked great.
$cat = 'term name that you want to add';
$terms = taxonomy_term_load_multiple_by_name($cat);
$ctids = array();
if($terms == NULL) { //Create term and use
$created = _create_term($cat,'nog_quote_cats');
if($created) {
//finding term by name
$newTerm = taxonomy_term_load_multiple_by_name($cat);
foreach($newTerm as $key => $term) {
$ctids[] = $key;
}
}
}
Then add that new $ctids in the node create
function _create_term($name,$taxonomy_type) {
$term = Term::create([
'name' => $name,
'vid' => $taxonomy_type,
])->save();
return TRUE;
}