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 ++;
  }
 }
}
  • seems to be connected to drupal.stackexchange.com/questions/259218/… – 4k4 Apr 5 '18 at 21:24
  • That option is no good, I need to use the same field – drupalhgy Apr 6 '18 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. – 4k4 Apr 6 '18 at 6:54
5

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++;
    }
  }

}

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.