public function AmazonFieldFormatter::viewElements in Amazon Product Advertisement API 8.2
Builds a renderable array for a field value.
Parameters
\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.
string $langcode: The language that should be used to render the field.
Return value
array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.
Overrides FormatterInterface::viewElements
File
- modules/
amazon_field/ src/ Plugin/ Field/ FieldFormatter/ AmazonFieldFormatter.php, line 122
Class
- AmazonFieldFormatter
- Plugin implementation of the 'amazon_field_formatter' formatter.
Namespace
Drupal\amazon_field\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$asins = [];
foreach ($items as $delta => $item) {
if (!$item
->isEmpty()) {
$asins[$item->value] = $item->value;
}
}
// Nothing to render.
if (empty($asins)) {
return $elements;
}
$associatesId = \Drupal::config('amazon.settings')
->get('associates_id');
$amazon = new Amazon($associatesId);
// Include Small and Images response groups along with any specified.
$responseGroups = [
'Small',
'Images',
];
if (!empty($this
->getSettings()['advanced']['extraResponseGroups'])) {
$responseGroups = array_merge($responseGroups, explode("\n", $this
->getSettings()['advanced']['extraResponseGroups']));
}
$results = $amazon
->lookup($asins, $responseGroups);
// No results from Amazon.
if (empty($results[0])) {
return $elements;
}
$max_age = $this
->getSetting('max_age');
$basicBuild = [
'#max_age' => $max_age,
];
// Use the correct Twig template based on the "template" specified.
switch (strtolower($this
->getSetting('template'))) {
case 'inline':
$basicBuild['#theme'] = 'amazon_inline';
break;
case 'image_small':
$basicBuild['#theme'] = 'amazon_image';
$basicBuild['#size'] = 'small';
break;
case 'image_medium':
$basicBuild['#theme'] = 'amazon_image';
$basicBuild['#size'] = 'medium';
break;
case 'image_large':
$basicBuild['#theme'] = 'amazon_image';
$basicBuild['#size'] = 'large';
break;
default:
// Unknown template specified.
return $elements;
}
// Add some template suggestions. Note these won't show up in the template
// debug code until https://www.drupal.org/node/2118743 is fixed.
$basicBuild['#bundle'] = $this->fieldDefinition
->getTargetBundle();
$basicBuild['#field'] = $this->fieldDefinition
->getName();
foreach ($results as $delta => $result) {
$elements[$delta] = $basicBuild + [
'#results' => $result,
];
}
return $elements;
}