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?