1

In a content type I have a field of type 'entity reference', 'auto complete' widget with unlimited values.

The whole idea was to give user an option to add referenced node items but only once, Hence selected node items should be excluded for new added fields.

I altered the form to change #autocomplete_path of this field. I took care of altering path for all the added fields, But when clicking on 'Add another Item' it is not updating #autocomplete_path as it should while rebuilding the form. My code could help answer it better way.

In my form_alter

if (isset($form['field_article_test'][LANGUAGE_NONE])) {

  // Loop through all the fields to collect the default set values.
  $selected_nids = array();
  foreach ($form['field_article_test'][LANGUAGE_NONE] as $delta => $field_object) {
    if (is_numeric($delta) && !empty($form['field_article_test'][LANGUAGE_NONE][$delta]['target_id']['#default_value'])) {
      $dval = $form['field_article_test'][LANGUAGE_NONE][$delta]['target_id']['#default_value'];
      $selected_nids[] = substr($dval, (strrpos($dval, '(') + 1), -1);
    }
  }

  //dsm($selected_nids);
  if (count($selected_nids) > 0) {
    // Implode the exsting selected nids so we can pass them in autocomplete custom menu path.
    $nids_hsv = implode('-', $selected_nids);
  }
  else {

    $nids_hsv = '-';
  }
  // Loop through all added fields and get #autocomplete path updated.
  foreach ($form['field_article_test'][LANGUAGE_NONE] as $delta => $field_object) {
    if (is_numeric($delta)) {
      $form['field_article_test'][LANGUAGE_NONE][$delta]['target_id']['#autocomplete_path'] = 'sform/autocomplete/article/' . $nids_hsv;
    }
  }
}

In above code, I collect all selected nodes in variable $nids_hsv and pass to my custom auto complete menu callback so that I can exclude these nids while fetching nodes as options.

Does the form rebuilds on "Add new item" action, if so, Is this possible to update #autocomplete_path of the same field on rebuild of a form?

1 Answer 1

1

What you are trying to achieve is Selecting Unique values from Multi Value Reference field... I do agree using default widget you may run into duplicates...

I would say consider using below one of the modules which supports entity reference using which you can avoid duplicate entries while adding..

You can choose one from variety of options mentioned in above article which suggests using of

Hope one of the above works for you :-)

1
  • those seems to be correct one to be used for this situation. Thanks. :-)
    – Jeet
    Commented Apr 10, 2014 at 9:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.