View source
<?php
define('FIELD_MULTIPLE_LIMIT_ALL', -1);
function field_multiple_limit_field_formatter_settings_summary_alter(&$summary, $context) {
if ($context['field_definition']
->getFieldStorageDefinition()
->isMultiple()) {
if ($context['formatter']
->getThirdPartySetting('field_multiple_limit', 'limit_values')) {
$count = $context['formatter']
->getThirdPartySetting('field_multiple_limit', 'count');
if (!empty($count)) {
$summary[] = \Drupal::translation()
->formatPlural($count, 'Display 1 value', 'Display @count values');
}
$offset = $context['formatter']
->getThirdPartySetting('field_multiple_limit', 'offset');
if (!empty($offset)) {
$summary[] = \Drupal::translation()
->formatPlural($offset, 'Skip 1 value', 'Skip @count values');
}
}
}
}
function field_multiple_limit_field_formatter_third_party_settings_form(\Drupal\Core\Field\FormatterInterface $plugin, \Drupal\Core\Field\FieldDefinitionInterface $field_definition, $view_mode, $form, \Drupal\Core\Form\FormStateInterface $form_state) {
if ($field_definition
->getFieldStorageDefinition()
->isMultiple()) {
$element['limit_values'] = array(
'#type' => 'checkbox',
'#title' => t('Limit the number of values to display'),
'#default_value' => $plugin
->getThirdPartySetting('field_multiple_limit', 'limit_values'),
);
$element['count'] = array(
'#type' => 'number',
'#title' => t('Number of values to display'),
'#min' => 1,
'#default_value' => $plugin
->getThirdPartySetting('field_multiple_limit', 'count'),
);
$element['offset'] = array(
'#type' => 'number',
'#title' => t('Number of values to skip'),
'#min' => 0,
'#default_value' => $plugin
->getThirdPartySetting('field_multiple_limit', 'offset'),
);
return $element;
}
}
function field_multiple_limit_field_attach_view_alter(&$output, $context) {
foreach (element_children($output) as $field_name) {
$entity_type = $output[$field_name]['#entity_type'];
$bundle = $output[$field_name]['#bundle'];
$info = field_formatter_settings_get_instance_display_settings($entity_type, $field_name, $bundle, $context['view_mode']);
$limit = empty($info['field_multiple_limit']) ? FIELD_MULTIPLE_LIMIT_ALL : $info['field_multiple_limit'];
$offset = empty($info['field_multiple_limit_offset']) ? 0 : $info['field_multiple_limit_offset'];
if ($offset > 0 || $limit != FIELD_MULTIPLE_LIMIT_ALL && $output[$field_name]['#items'] > $limit) {
$element =& $output[$field_name];
$count = 1;
foreach ($element['#items'] as $delta => $item) {
if ($delta < $offset) {
$element[$delta]['#access'] = FALSE;
continue;
}
if ($limit != FIELD_MULTIPLE_LIMIT_ALL && $count > $limit) {
$element[$delta]['#access'] = FALSE;
}
$count++;
}
}
}
}