You are here

public function AddToCartFormatter::viewElements in Commerce Core 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/product/src/Plugin/Field/FieldFormatter/AddToCartFormatter.php, line 65

Class

AddToCartFormatter
Plugin implementation of the 'commerce_add_to_cart' formatter.

Namespace

Drupal\commerce_product\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $product = $items
    ->getEntity();
  if (!empty($product->in_preview)) {
    $elements[0]['add_to_cart_form'] = [
      '#type' => 'actions',
      [
        '#type' => 'button',
        '#value' => $this
          ->t('Add to cart'),
      ],
    ];
    return $elements;
  }
  if ($product
    ->isNew()) {
    return [];
  }
  $view_mode = $this->viewMode;

  // If the field formatter is rendered in Layout Builder, the `viewMode`
  // property will be `_custom` and the original view mode is stored in the
  // third party settings.
  // @see \Drupal\layout_builder\Plugin\Block\FieldBlock::build
  if (isset($this->thirdPartySettings['layout_builder'])) {
    $view_mode = $this->thirdPartySettings['layout_builder']['view_mode'];
  }
  $elements[0]['add_to_cart_form'] = [
    '#lazy_builder' => [
      'commerce_product.lazy_builders:addToCartForm',
      [
        $product
          ->id(),
        $view_mode,
        $this
          ->getSetting('combine'),
        $langcode,
      ],
    ],
    '#create_placeholder' => TRUE,
  ];
  return $elements;
}