Sometimes we need to alter or restrict some options for dropdown of entity reference field. One of the solution to use views and provide views entity reference widget, but in some cases the logic would be too complex and we will have to implement custom plugins for views. The second solution could be just replace options for dropdown widget. For this we need implement "hook_field_widget_form_alter"
/**
* Implements hook_field_widget_form_alter().
*/
function your_module_field_widget_form_alter(
if (!empty($field_definition) && $field_definition->getName() == 'fut_collection') {
$element['#options'] = _your_module_get_input_options();
}
}
/**
* Gets group collection options.
*/
function _your_module_get_input_options() {
$options = [];
// here your custom logic to get ids.
$items = Term::loadMultiple($ids);
if ($items ) {
// a default empty value.
$options['_none'] = t('- None -');
foreach ($items as $item) {
$options[$item->id()] = $item->getName();
}
}
return $options;
}
Keep in mind that you have to use the entity ids of entity type for your entity reference field. Also, if you want to provide the default value without any value, you should use this code:
$options['_none'] = t('- None -');
and not like
$options[''] = t('- None -');
In other case you can face some unexpected bugs