ComputedMaterialsReferences.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 ComputedMaterialsReferences 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('node')
  34. ->condition('status', 1)
  35. ->condition('type', 'materiau')
  36. ->exists('field_materiau_images')
  37. ->condition('field_materiau_images.%delta', 3)
  38. ->sort('created', 'DESC')
  39. ->range(0,200);
  40. $results = $query->execute();
  41. if ($results) {
  42. $nids = array_rand($results, 100);
  43. foreach ($nids as $key => $nid) {
  44. $this->list[$key] = $this->createItem($key, $nid);
  45. }
  46. }
  47. }
  48. }