View source  
  <?php
namespace Drupal\commerce_promotion;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityListBuilder;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
class PromotionListBuilder extends EntityListBuilder implements FormInterface {
  
  protected $formBuilder;
  
  protected $usage;
  
  protected $disabledEntities = [];
  
  protected $enabledEntities = [];
  
  protected $usageCounts = [];
  
  protected $hasTableDrag = TRUE;
  
  protected $limit = 25;
  
  protected $statusCondition = TRUE;
  
  public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, FormBuilderInterface $form_builder, PromotionUsageInterface $usage) {
    parent::__construct($entity_type, $storage);
    $this->formBuilder = $form_builder;
    $this->usage = $usage;
  }
  
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static($entity_type, $container
      ->get('entity_type.manager')
      ->getStorage($entity_type
      ->id()), $container
      ->get('form_builder'), $container
      ->get('commerce_promotion.usage'));
  }
  
  public function getFormId() {
    return 'commerce_promotions';
  }
  
  public function load() {
    $entity_ids = $this
      ->getEntityIds();
    $entities = $this->storage
      ->loadMultiple($entity_ids);
    
    uasort($entities, [
      $this->entityType
        ->getClass(),
      'sort',
    ]);
    
    $this->usageCounts += $this->usage
      ->loadMultiple($entities);
    return $entities;
  }
  
  protected function getEntityIds() {
    $query = $this
      ->getStorage()
      ->getQuery()
      ->accessCheck(FALSE)
      ->condition('status', $this->statusCondition)
      ->sort($this->entityType
      ->getKey('id'));
    
    if ($this->limit) {
      $query
        ->pager($this->limit);
    }
    return $query
      ->execute();
  }
  
  public function buildHeader() {
    $header['name'] = $this
      ->t('Name');
    $header['usage'] = $this
      ->t('Usage');
    $header['customer_limit'] = $this
      ->t('Per-customer limit');
    $header['start_date'] = $this
      ->t('Start date');
    $header['end_date'] = $this
      ->t('End date');
    if ($this->hasTableDrag) {
      $header['weight'] = $this
        ->t('Weight');
    }
    return $header + parent::buildHeader();
  }
  
  public function buildRow(EntityInterface $entity) {
    $current_usage = $this->usageCounts[$entity
      ->id()];
    $usage_limit = $entity
      ->getUsageLimit();
    $usage_limit = $usage_limit ?: $this
      ->t('Unlimited');
    $customer_limit = $entity
      ->getCustomerUsageLimit();
    $customer_limit = $customer_limit ?: $this
      ->t('Unlimited');
    
    $row['#attributes']['class'][] = 'draggable';
    $row['#weight'] = $entity
      ->getWeight();
    $row['name'] = $entity
      ->label();
    $row['usage'] = $current_usage . ' / ' . $usage_limit;
    $row['customer_limit'] = $customer_limit;
    $row['start_date'] = $entity
      ->getStartDate()
      ->format('M jS Y H:i:s');
    $row['end_date'] = $entity
      ->getEndDate() ? $entity
      ->getEndDate()
      ->format('M jS Y H:i:s') : '—';
    if ($this->hasTableDrag && $entity
      ->isEnabled()) {
      $row['weight'] = [
        '#type' => 'weight',
        '#title' => $this
          ->t('Weight for @title', [
          '@title' => $entity
            ->label(),
        ]),
        '#title_display' => 'invisible',
        '#default_value' => $entity
          ->getWeight(),
        '#attributes' => [
          'class' => [
            'weight',
          ],
        ],
      ];
    }
    return $row + parent::buildRow($entity);
  }
  
  public function render() {
    $build = $this->formBuilder
      ->getForm($this);
    $build['#attached']['library'][] = 'commerce_promotion/admin_list';
    return $build;
  }
  
  public function buildForm(array $form, FormStateInterface $form_state) {
    
    $this->enabledEntities = $this
      ->load();
    if (count($this->enabledEntities) <= 1) {
      $this->hasTableDrag = FALSE;
    }
    $delta = 10;
    
    $count = count($this->enabledEntities);
    if ($count > 20) {
      $delta = ceil($count / 2);
    }
    $table_header = $this
      ->buildHeader();
    $form['enabled_promotions'] = [
      '#type' => 'table',
      '#header' => $table_header,
      '#empty' => $this
        ->t('There are no enabled @label yet.', [
        '@label' => $this->entityType
          ->getPluralLabel(),
      ]),
      '#caption' => $this
        ->t('Enabled'),
    ];
    
    if ($this->limit) {
      $form['pager_enabled_promotions'] = [
        '#type' => 'pager',
        '#element' => 0,
      ];
    }
    
    $this->statusCondition = FALSE;
    $this->disabledEntities = $this
      ->load();
    $form['disabled_promotions'] = [
      '#type' => 'table',
      
      '#header' => array_diff_key($table_header, [
        'weight' => 'weight',
      ]),
      '#empty' => $this
        ->t('There are no disabled @label.', [
        '@label' => $this->entityType
          ->getPluralLabel(),
      ]),
      '#caption' => $this
        ->t('Disabled'),
    ];
    
    if ($this->limit) {
      $form['pager_disabled_promotions'] = [
        '#type' => 'pager',
        '#element' => 1,
      ];
    }
    $entities = array_merge($this->enabledEntities, $this->disabledEntities);
    foreach ($entities as $entity) {
      $row = $this
        ->buildRow($entity);
      $row['name'] = [
        '#markup' => $row['name'],
      ];
      $row['usage'] = [
        '#markup' => $row['usage'],
      ];
      $row['customer_limit'] = [
        '#markup' => $row['customer_limit'],
      ];
      $row['start_date'] = [
        '#markup' => $row['start_date'],
      ];
      $row['end_date'] = [
        '#markup' => $row['end_date'],
      ];
      if (isset($row['weight'])) {
        $row['weight']['#delta'] = $delta;
      }
      if ($entity
        ->isEnabled()) {
        $form['enabled_promotions'][$entity
          ->id()] = $row;
      }
      else {
        $form['disabled_promotions'][$entity
          ->id()] = $row;
      }
    }
    if ($this->hasTableDrag) {
      $form['enabled_promotions']['#tabledrag'][] = [
        'action' => 'order',
        'relationship' => 'sibling',
        'group' => 'weight',
      ];
      $form['actions']['#type'] = 'actions';
      $form['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Save'),
        '#button_type' => 'primary',
      ];
    }
    return $form;
  }
  
  public function validateForm(array &$form, FormStateInterface $form_state) {
    
  }
  
  public function submitForm(array &$form, FormStateInterface $form_state) {
    foreach ($form_state
      ->getValue('enabled_promotions') as $id => $value) {
      if (isset($this->enabledEntities[$id]) && $this->enabledEntities[$id]
        ->getWeight() != $value['weight']) {
        
        $this->enabledEntities[$id]
          ->setWeight($value['weight']);
        $this->enabledEntities[$id]
          ->save();
      }
    }
  }
  
  protected function getDefaultOperations(EntityInterface $entity) {
    $operations = parent::getDefaultOperations($entity);
    if ($entity
      ->access('update')) {
      $operations['coupons'] = [
        'title' => $this
          ->t('Coupons'),
        'weight' => 20,
        'url' => new Url('entity.commerce_promotion_coupon.collection', [
          'commerce_promotion' => $entity
            ->id(),
        ]),
      ];
      if (!$entity
        ->isEnabled() && $entity
        ->hasLinkTemplate('enable-form')) {
        $operations['enable'] = [
          'title' => $this
            ->t('Enable'),
          'weight' => -10,
          'url' => $this
            ->ensureDestination($entity
            ->toUrl('enable-form')),
        ];
      }
      elseif ($entity
        ->hasLinkTemplate('disable-form')) {
        $operations['disable'] = [
          'title' => $this
            ->t('Disable'),
          'weight' => 40,
          'url' => $this
            ->ensureDestination($entity
            ->toUrl('disable-form')),
        ];
      }
    }
    return $operations;
  }
}