Commit f105a116 authored by Daniel Pepin's avatar Daniel Pepin
Browse files

Issue #2536510: Setup weight formatter that displays the variant weight with...

Issue #2536510: Setup weight formatter that displays the variant weight with the correct weight_unit.
parent 01473227
Loading
Loading
Loading
Loading
+1 −1
Changes for src/Entity/ShopifyProductVariant.php: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -379,7 +379,7 @@ class ShopifyProductVariant extends ContentEntityBase implements ShopifyProductV
      ))
      ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'decimal',
        'type' => 'shopify_weight',
        'weight' => -4,
      ))
      ->setDisplayOptions('form', array(
+63 −0
Changes for src/Plugin/Field/FieldFormatter/ShopifyWeightFormatter.php: 63 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?php

/**
 * @file
 */

namespace Drupal\shopify\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\NumericFormatterBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the Shopify weight formatter.
 *
 * @FieldFormatter(
 *   id = "shopify_weight",
 *   label = @Translation("Shopify Weight"),
 *   field_types = {
 *     "decimal",
 *   }
 * )
 */
class ShopifyWeightFormatter extends NumericFormatterBase {

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = array();
    foreach ($items as $delta => $item) {
      $entity = $item->getEntity();
      $output = $this->numberFormat($item->value, $entity->weight_unit->value);
      $elements[$delta] = array('#markup' => $output);
    }
    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary[] = 'Format: {{weight}}{{weight_unit}}';
    $summary[] = 'Preview: ' . $this->numberFormat(1234.1234567890, 'lb');
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function numberFormat($number, $format = '') {
    $number = number_format($number, 2);
    return $number . $format;
  }

}