Hi There,

First off - great module :) Really checking all the boxes I have on some use cases.

My question is how can one go about creating a paragraphs item programmatically (I have about 15k entries to add, so would prefer to automate it)? So far I've been trying to do this like so:

$node = node_load(...);
$item = entity_create('paragraphs_item', array('bundle' => 'bundle_name', 'field_name' => 'field_name'));
$item->setHostEntity('node', $node);
$wrapper = entity_metadata_wrapper('paragraphs_item', $item);
$wrapper->field_name->set('value');
$wrapper->save(TRUE);
node_save($node);

But it doesn't create anything - the wrapper method seems to work just fine if I'm updating a previously created paragraph item (via paragraphs_item_load).

Any input would be appreciated, been banging my head against the wall for a few hours on this :)

Comments

erik.erskine’s picture

I managed to create a paragraph and add it to an existing node like this:

$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();
ivan zugec’s picture

Status: Active » Fixed

Here's another way, copied from Field collection.

$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();

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

jkingsnorth’s picture

+1 for #1

And you can define fields in the normal way:
$paragraph->field_MY_FIELD[LANGUAGE_NONE][0]['value'] = 'Foo';

ziobudda’s picture

How can I add a paragraph to a new node never saved ?

Katie.Lacy’s picture

#5 - ziobudda
You can create a paragraph to a new node by programmatically saving a node then using the new nodes object for this new node.

See here on how to create a node programmatically

https://www.drupal.org/node/1388922

Here's an example :


function MODULE_create_my_node(){

$node = new stdClass();  // Create a new node object
$node->type = 'NODETYPE';  // Content type
$node->language = LANGUAGE_NONE;  // Or e.g. 'en' if locale is enabled
node_object_prepare($node);  //Set some default values

$node->title = 'Your node title';
$node = node_submit($node); // Prepare node for saving
node_save($node);

//  $node is now the newly added node
// Now lets create than paragraph, using Ivan Zugec example above. 

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

I hope this helps!

derMatze’s picture

Anyone knows how to do this in D8?
I think there is nothing like setHostEntity()

Update:
Just opened a new issue, so that this one can stay closed:
https://www.drupal.org/node/2707017

rli’s picture

Status: Closed (fixed) » Active

Saving fields to new paragraph or updating fields to existing paragraph didn't work for me using method in #4.
It would be great to have an example of how can I save the fields in the entity.

Thanks.

keesje’s picture

beware of $entity->save() on existing paragraphs. By default it searches for the host entity en saves that too. That might be wat you want.
Caveat in my case was deployment of workbench_moderation. The save of that host entity does not play nice with moderation states, publishing nodes that where not meant to be.

Solution:
$entity->save(TRUE);

see ParagraphsItemEntity.inc

shivachevva’s picture

velocis’s picture

Drupal Paragraphs programmatically create image fields

Was working with images in Paragraphs, found the following method for adding images programmatically worked for me.

$node = node_load(...);
$paragraph = new ParagraphsItemEntity(array('field_name' => 'paragraph_field_name', 'bundle' => 'paragraph_bundle'));
$paragraph->is_new = TRUE;
$paragraph->setHostEntity('node', $node);

// If file is already managed load it using $fid OR provide location of image
if ($fid) {
  $file_attach = file_load($fid);
}else{
  $file_temp = file_get_contents(<em>Location of your file e.g. /tmp/import</em>); 
  $file_dir = "public://directory/to/put/file/in";
  file_prepare_directory($file_dir, FILE_CREATE_DIRECTORY) // Create the directory
  $file_name = "ouput.png"
  // Save the image file, create file_managed record and return the file object
  $file_attach = file_save_data( $file_temp, $file_dir."/".$file_name , FILE_EXISTS_RENAME);
}

// Attach file object as array to image field (field setup to use 1 image)
$paragraph->field_image[LANGUAGE_NONE][0] = (array)$file_attach;

// Update some other field on the Paragraph
$paragraph->field_textfield[LANGUAGE_NONE][0]['value'] = 'text';

$paragraph->save();

Works fine with S3FS module

delacosta456’s picture

hi

Please is there no way to do this with rules .. like it was possible with field collection where you can loop in list and create an entity..

luis0076’s picture

I created a paragraph bundle called workexperience with 3 fields (field_cv_from, field_cv_to, field_cv_position) and a content type with a filed paragraph called field_workexperience.

When I use this code

function mymodule_node_presave($node) {
$paragraph = entity_create('paragraphs_item', array('field_name' => 'field_workexperience', 'bundle' => 'workexperience'));
$paragraph->is_new = TRUE;
$paragraph->setHostEntity('node', $node);
$paragraph->save(true);
$paragraph->field_cv_from['und'][0]['value'] = '2016';
$paragraph->field_cv_to['und'][0]['value'] = '2018';
$paragraph->field_cv_position['und'][0]['value'] = 'Project Manager';
}

in the node there are two paragraphs one with data an another empty. Do you help me to understand?
Thx

sgdev’s picture

@luis0076, you are saving the paragraph before adding the fields. put $paragraph->save(); at the end, not before setting the field values.

colorfulcoder’s picture

Tried the method in #11 but it doesn't work for me.
I have checked if I correctly upload my file, and it is correctly uploaded to the right location.
Also, if I check the paragraphs object afterwards (after saving and then loading it again) I can see that the fid is in the value field, and the revision field is also filled, so it seems to work there.
However, when I go to the node (user profile) that I attached the paragraph onto, I see a new paragraph with the disorder and date attached but no attached files.

This is driving me nuts, bonkers!
What the heck am I missing?!?

$user = user_load($form_state['values']['uid']);

  $account = entity_metadata_wrapper('user', $user);
  $paragraph_item = $account->field_user_after_picture->value();

  $disorder_nid = poh_disorder_get_disorder_node_from_machine_name($form_state['values']['disorder'])->nid;

  // Create the new paragraph
  $paragraph = new ParagraphsItemEntity( array(
    'field_name' => 'field_user_before_picture',
    'bundle' => 'disorder_before_picture',
    )
  );
  $paragraph->is_new = TRUE;
  $paragraph->setHostEntity('user', $user);
  $paragraph->field_disorder[LANGUAGE_NONE][0]['target_id'] = $disorder_nid;

  // I hardcoded this to make sure the empty date field was not the issue, it isn't.
  $date_field = array(
    'value' => '2020-07-24 00:00:00',
    'timezone' => 'Europe/Paris',
    'timezone_db' => 'Europe/Paris',
    'date_type' => 'datetime'
  );
  $paragraph->field_date[LANGUAGE_NONE][0] = $date_field;

  foreach ($_FILES['files']['name'] as $key => $filename) {
    if (empty($filename)) {
      continue;
    }

    $file_drupal_path = $key;
    $file_dest = 'private:///' . $user->uid . '/after';

    $file = new stdClass();
    $file->filename = basename($filename);
    $file->filepath = $filename;
    $file->filemime = mime_content_type($filename);
    $file->filesize = filesize($filename);
    $file->uid = $user->uid;
    $file->timestamp = time();

    $file = file_save_upload($file_drupal_path, array(), $file_dest, FILE_EXISTS_RENAME);

    if ($file) {
      // file_save_upload marks the file as temporary, we need to mark as permanent or it will be cleared from the database in a few hours
      $file->status = FILE_STATUS_PERMANENT;
      file_save($file);
    }

    // DONE: Upload file to private files
    // DONE: Make file managed by Drupal
    // TODO: Couple the file to the paragraph so that it shows on the user profile

    // Attach file object as array to field
    $paragraph->field_after_picture[LANGUAGE_NONE][] = (array) $file;

    // Tried this, didn't work either.
    /*$paragraph->field_after_picture[LANGUAGE_NONE][] = array(
      'fid' => $file->fid,
      'filename' => $file->filename,
      'filemime' => $file->filemime,
      'uid' => $user->uid,
      'uri' => $file->uri,
      'status' => 1
    );*/
  }
  $paragraph->save();
colorfulcoder’s picture

Ok, I figured out that I got the names of my fields mixed up. Now I have fixed that, but I get the following watchdog error:
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'field_before_picture_display' cannot be null: INSERT INTO {field_data_field_before_picture} (entity_type, entity_id, revision_id, bundle, delta, language, field_before_picture_fid, field_before_picture_display, field_before_picture_description) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8); Array ( [:db_insert_placeholder_0] => paragraphs_item [:db_insert_placeholder_1] => 57 [:db_insert_placeholder_2] => 59 [:db_insert_placeholder_3] => disorder_before_picture [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => 74 [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => ) in field_sql_storage_field_storage_write() (line 514 of /Library/WebServer/Documents/cosmetiek/webroot/modules/field/modules/field_sql_storage/field_sql_storage.module).

the name if my field is field_before_picture.

The table field_data_field_before_picture doesn't get a new entry when it should, because of this integrety constraint violation.

I'm now searching where this value (field_before_picture_display) should be set, but for the life of me I can't find it!
How did nobody else get this bug before?

colorfulcoder’s picture

I found the solution.

The solution posted in #11 is incomplete. One row of code is missing:
$file->display = '1';

This is what it should be (in context).

$file = new stdClass();
    $file->filename = basename($filename);
    $file->filepath = $filename;
    $file->filemime = mime_content_type($filename);
    $file->filesize = filesize($filename);
    $file->uid = $user->uid;
    $file->timestamp = time();

    $file = file_save_upload($file_drupal_path, array(), $file_dest, FILE_EXISTS_RENAME);

    $file->display = '1';

    if ($file) {
      // file_save_upload marks the file as temporary, we need to mark as permanent or it will be cleared from the database in a few hours
      $file->status = FILE_STATUS_PERMANENT;
      file_save($file);
    }
raaesco’s picture

How to update a paragraph fields that has been created before as a part of a node.
I don't know how to access de values in paragraph fields and even worse how to update them.
The paragraph already exists.
Any clues?
Thanks!

coffeduong’s picture

@raaesco You'll need paragraph id, then `entity_load` and finish with `->save()`
For example:

  $paragraph_item = entity_load('paragraphs_item', [$paragraph_id]);
  $paragraph_item->field_textfield[LANGUAGE_NONE][0]['value'] = 'text';
  $paragraph_item->save();
drupalninja’s picture

I am trying to add a paragraph to a node in Rules using the code in #11. I works if I run it as a PHP input in a Basic page but wont work as a part of Rules iteration. Execute PHP Action


$node = node_load([node:nid]);
$paragraph = new ParagraphsItemEntity(array('field_name' => 'field_translation', 'bundle' => 'translation_stage'));
$paragraph->is_new = TRUE;
$paragraph->field_translator2['und'][0]['target_id'] = '[list-item:field-translator:nid]';
$paragraph->setHostEntity('node', $node);
$paragraph->save(TRUE);
node_save($node);

Any suggestions

bluegeek9’s picture

Status: Active » Closed (outdated)
//www.flaticon.com/free-icons/thank-you Thank you for your contribution!

Unfortunately, Drupal 7 is End of Life and no longer supported. We strongly encourage you to upgrade to a supported version of Drupal.

Now that this issue is closed, review the contribution record.

As a contributor, attribute any organization that helped you, or if you volunteered your own time.

Maintainers, credit people who helped resolve this issue.