If there is only one view display available for the selected view it would be nice if the element is just hidden and the only display is preselected.
For now I just fixed this by adding a new field widget and overriding the following and this seems to do the trick:
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$display_id_options = array_keys(array_filter($element['display_id']['#options'], function ($key) {
return $key !== '_none';
}, ARRAY_FILTER_USE_KEY));
// When there is only one display option,
// select it as default and hide element.
if (count($display_id_options) == 1) {
$element['display_id']['#title_display'] = 'invisible';
$element['display_id']['#attributes']['class'][] = 'visually-hidden';
$element['display_id']['#default_value'] = reset($display_id_options);
}
return $element;
}
/**
* {@inheritdoc}
*/
public function itemCurrentValues(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$values = parent::itemCurrentValues($items, $delta, $element, $form, $form_state);
if (empty($values['target_id'])) {
return $values;
}
$displays = $this->getViewDisplays($values['target_id']);
if (count($displays) != 1) {
return $values;
}
// If there is only one display available for the view,
// Always select it as default.
$display_ids = array_keys($displays);
$values['display_id'] = reset($display_ids);
return $values;
}
Let me know if I should create a patch
Comments
Comment #2
jeffschulerSee #2932381: Hide the choice for a view display if there is only one option.