2

I have a paragraphs field that takes a term reference.

I need to count how many terms there are for a specific vocabulary and then create that many instance of the paragraphs multiple value field for when creating a node of a certain type. Can this be done with Hook_form_alter ?

It is important that these fields are loaded when the node creation form is loaded rather than the user having to click add more

Any help would be greatly appreciated

I have tried this but when saving the node it doesn't save the new fields

function hook_form_alter(&$form, $form_state, $form_id) { if ($form_id == 'my_form') { $item = $form['field_features']['widget']['0']; // get taxonomy terms $query = \Drupal::entityQuery('taxonomy_term'); $query->condition('vid', "my_voc"); $tids = $query->execute(); $terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids); $count = count($terms); $i = '1'; foreach($terms as $term){ $form['field_features_para']['widget'][$i] = $item; $form['field_features_para']['widget'][$i]['#delta'] = $i; $form['field_features_para']['widget'][$i]['#weight'] = $i; $i ++; } } } 
3
  • seems to be connected to drupal.stackexchange.com/questions/259218/… Commented Apr 5, 2018 at 21:24
  • That option is no good, I need to use the same field Commented Apr 6, 2018 at 6:20
  • 1
    IMHO doing this on the entity is a better option. I've tried to transfer your code to an entity create hook, see the answer. Commented Apr 6, 2018 at 6:54

1 Answer 1

6

Instead of adding the multi value field items after the form is built you can try to do this on the entity before the form is built:

/** * Implements hook_ENTITY_TYPE_create() for 'node'. */ function mymodule_node_create(\Drupal\node\NodeInterface $node) { if ($node->getType() == 'my_content_type') { // get taxonomy terms $query = \Drupal::entityQuery('taxonomy_term'); $query->condition('vid', "my_voc"); $tids = $query->execute(); $terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids); $count = count($terms); $i = '1'; foreach ($terms as $term) { $paragraph = \Drupal::entityTypeManager()->getStorage('paragraph')->create([ 'title' => 'Paragraph ' . $i, 'type' => 'my_paragraph_type', // more field data ]); $node->field_features_para[] = $paragraph; $i++; } } } 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.