ComputedCommerceProductReferences.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. foreach ($ids as $key => $id) {
  41. $this->list[$key] = $this->createItem($key, $id);
  42. }
  43. }
  44. }