How to store values to field collection or paragraphs programmatically? How do I store values to either a field collection or a paragraphs field  programmatically?

Could somebody please provide a working code example of how you do this?

I would have a field holder containing the following three fields where I want to store down my data:


field_title - (1 value text field)
field_text - (1 value text field - long)
field_sources - (unlimited no of values text field)


Thanks for helping me out.
Paragraphs and field collections are both their own entity and the fields pointing to them are just entity referenced.

So if you want to create a node with a referenced paragraph, you first create the paragraph with all the values you want, save it, then create the node and point it to the paragraph you created.

The Paragraph demo module has example code that does exactly that in paragraphs_demo_install():

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

  $paragraph3 = Paragraph::create([
    'type' =&gt; 'text',
    'field_text_demo' =&gt; 'Apart from the included Paragraph types, you can create your own simply by going to Structure -&gt; Paragraphs types.',
  ]);
  $paragraph3-&gt;save();

  // Add demo content with two paragraphs.
  $node = Node::create(array(
    'type' =&gt; 'paragraphed_content_demo',
    'title' =&gt; 'Welcome to the Paragraphs Demo module!',
    'field_paragraphs_demo' =&gt; array(
      array(
        'target_id' =&gt; $paragraph3-&gt;id(),
        'target_revision_id' =&gt; $paragraph3-&gt;getRevisionId(),
      ),
    ),
  ));
  $node-&gt;save();