2

How to create paragraphs item programmatically?

In Drupal 7 I am using the following code.

    $node = node_load($nid);
    $paragraph = new ParagraphsItemEntity(array('field_name' => 'field_name', 'bundle' => 'para_bundlename'));
    $paragraph->is_new = TRUE;
    $paragraph->field_ptest1['und'][0]['value'] = 'Foo';
    $paragraph->setHostEntity('node', $node);
    $paragraph->save();
    node_save($node);

But its not working ?

3

Yes, That was for adding the value in existing paragraph item. If you want to create new paragraph item with new value try this code.

$node = node_load(...);

$paragraph = new ParagraphsItemEntity(array('field_name' => 'name_of_field_in_node', 'bundle' => 'name_of_paragraph_bundle'));
$paragraph->is_new = TRUE;
$paragraph->setHostEntity('node', $node);
$paragraph->field1_name_in_paragraph_bundle[LANGUAGE_NONE][0]['value'] = 'Test Data';
$paragraph->field2_name_in_paragraph_bundle[LANGUAGE_NONE][0]['value'] = 'Test Data';
$paragraph->save();
  • Its same as @Shabir A, now i got it where i was wrong to setting the value. thanks sri harsha – visabhishek Jan 28 '16 at 6:18
  • 2
    How can you set the weight? – Led Feb 4 '17 at 13:05
1

I also faced similar issue this is how I got it working hope this helps.

I have got it working using entity_metadata_wrapper.

$raw_node = node_load($nid);
// Wrap it with Entity API
$node = entity_metadata_wrapper('node', $raw_node);
$raw_collection = $node->paragraph_field_name->value();
$collection = entity_metadata_wrapper('paragraphs_item', $raw_collection);
$collection->field_paragraph_item1 = "hurray";
$collection->save();
  • Its adding value in existing paragraph item. its not adding the paragraph item itself. – visabhishek Jan 28 '16 at 6:14
0

This is the code used in various places to create an entity in Drupal 7

$node = node_load(...);

$paragraph = new ParagraphsItemEntity(array('field_name' => 'name_of_field_in_node', 'bundle' => 'name_of_paragraph_bundle'));
$paragraph->is_new = TRUE;
$paragraph->setHostEntity('node', $node);
$paragraph->save();

Field collection module using the following method instead

$node = node_load(...);
$entity = entity_create('paragraphs_item', array('field_name' => 'name_of_field_in_node', 'bundle' => 'name_of_paragraph_bundle'));
$entity->setHostEntity('node', $node);
$entity->save();

Both should work fine. You code looks good to me just remove the last line.

  • I already tried with both scenario but its not working :( – visabhishek Jan 27 '16 at 14:32

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.