ComputedCommerceProductReferences.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace Drupal\materio_home\Plugin\Field\FieldType;
  3. use Drupal\Core\Entity\FieldableEntityInterface;
  4. use Drupal\Core\Field\EntityReferenceFieldItemList;
  5. use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
  6. use Drupal\Core\Field\FieldItemList;
  7. use Drupal\Core\TypedData\TypedDataInterface;
  8. use Drupal\Core\Field\BaseFieldDefinition;
  9. use Drupal\Core\TypedData\ComputedItemListTrait;
  10. // https://www.drupal.org/node/2112677
  11. // https://www.cornel.co/article/entity-reference-computed-field-example-drupal
  12. // https://www.caxy.com/blog/drupal-custom-form-and-computed-fields
  13. class ComputedCommerceProductReferences extends EntityReferenceFieldItemList
  14. {
  15. use ComputedItemListTrait;
  16. /**
  17. * The entity type manager.
  18. *
  19. * @var \Drupal\Core\Entity\EntityTypeManagerInterface
  20. */
  21. protected $entityTypeManager;
  22. /**
  23. * {@inheritdoc}
  24. */
  25. public function __construct(BaseFieldDefinition $definition, $name, TypedDataInterface $parent) {
  26. parent::__construct($definition, $name, $parent);
  27. $this->entityTypeManager = \Drupal::entityTypeManager();
  28. }
  29. /**
  30. * Compute the values.
  31. */
  32. protected function computeValue() {
  33. $query = \Drupal::entityQuery('commerce_product')
  34. ->condition('status', 1)
  35. ->sort('created', 'ASC')
  36. // ->exists('field_visuel')
  37. // ->condition('type', 'article')
  38. ->range(0,12);
  39. $ids = $query->execute();
  40. $i = 0;
  41. foreach ($ids as $id) {
  42. $this->list[$i] = $this->createItem($i, $id);
  43. $i++;
  44. }
  45. }
  46. }