In Drupal 8 (8.7.6), I would need to import several terms in a taxonomy dictionary. It is easy to create the terms at the “root” level, but when I try to create a term with a parent, the term is not created under the parent (but in the root).

Do you have any idea on how to solve the issue?

Thanks

Comments

sam711’s picture

Not sure what you mean by 'import', but something like this might help:
$term = Term::create([
  'name' => 'new_term_name',
  'vid' => 'your_taxonomy',
  'parent' => $root_term->id(),
])->save();
MircoDrupal’s picture

Dear Sam711,
thank you for your answer. I would need to use the REST Api (as explained on https://www.drupal.org/docs/8/core/modules/rest/3-post-for-creating-cont...), but if I do not find a solution soon, I will use your approach.
Best regards,

sam711’s picture

I understand now. So, following the Guzzle example, as the parent is an entity reference you could do something like this.

$serialized_entity = json_encode([
  'name' => [['value' => 'new_term_name']],
  'vid' => [['target_id' => 'your_taxonomy']],
  'parent' => [['target_id' => $root_term->id()]],
]);

MircoDrupal’s picture

I figured out the solution: it is necessary to send the parent UUID.
This is the complete JSON request:

{

        "_links": {

               "type": {

                       "href": "[Server]/rest/type/taxonomy_term/[Taxonomy Dictionary]"

               },

               "[Server]/rest/relation/taxonomy_term/[Taxonomy Dictionary]/parent": [{

                               "href": "[Server]/taxonomy/term/[ParentId]?_format=hal_json"

                       }

               ]

        },

        "vid": [{

                       "target_id": "[Taxonomy Dictionary]"

               }

        ],

        "name": [{

                       "value": "RESTtag",

                       "lang": "en"

               }

        ],

        "_embedded": {

               "[Server]/rest/relation/taxonomy_term/[Taxonomy Dictionary]/parent": [{

                               "_links": {

                                      "self": {

                                              "href": "[Server]/taxonomy/term/[ParentId]?_format=hal_json"

                                      },

                                      "type": {

                                              "href": "[Server]/rest/type/taxonomy_term/[Taxonomy Dictionary]"

                                      }

                               },

                               "uuid": [{

                                              "value": "[ParentUUID]"

                                      }

                               ]

                       }

               ]

        }

}