1

I have a paragraph with a taxonomy reference (autocomplete) field and I want to populate it when I create programmatically a pararagraph item. I checked the option "Create referenced entities if they do not already exist" in this field.

I use this code, but I don't know how to find more informations to do that without Term::create (if it's possible) :

use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;

        foreach ($field_value as $creator_type => $creator_name) {

            $paragraph = Paragraph::create(['type' => '_zotero_ref_creators']);
            //text field
            $paragraph->set('field_nom_prenom_createur', $creator_name);
            //taxo reference field
            $paragraph->set('field_type_createurs', $creator_type);

            //$paragraph->isNew();
            $paragraph->save();

            $paragraphn_field_value = array(
              'target_id' => $paragraph->id(),
              'target_revision_id' => $paragraph->getRevisionId(),
            );

            $node_reference->set('field_liste_contrib', $paragraphn_field_value);
          }
2

First load the node already created. Second, create a paragraph like you did but for taxonomy term add "target_id" and for value choose a term id. Set the paragraph value to your field of type paragraph from node. Also you need to save the node.

    $node = Node::load($nid);    
     $paragraph = Paragraph::create([
            'type' => 'gallery_image',
            'field_type_createurs' => ['target_id' => $value],
          ]);
          $paragraph->save();

          $current[] = [
            'target_id' => $paragraph->id(),
            'target_revision_id' =>$paragraph->getRevisionId(),
          ];

   $node->set('your_field', $current);
   $node->save();

Varible $value is a term id.

Hope to help you.

0

It took awhile for this to sink in. Thinking of it as creating a paragraph entity on the node helped me with Paragraph::create. A first I was thinking of Paragraph::create as creating the paragraph type, which, of course, I had already created.

Here's some more example code that is mostly a repeat of @OPTASY's code. All the data is sanitized and, hopefully, the keys give a clear idea which fields are being referenced and when.

$node = Node::load($nid);

$current = [];
  $paragraph = Paragraph::create([
    'type' => 'my_paragraph_type',
    'field_from_my_paragraph_type' => ['target_id' => 1]
  ]);
  $paragraph->save();

$current[] = [
    'target_id' => $paragraph->id(),
    'target_revision_id' => $paragraph->getRevisionId(),
  ];

$node->set('field_from_my_content_type', $current);
$node->save();

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.