ComputedMaterialsReferences.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. $i = 0;
  44. foreach ($nids as $nid) {
  45. $this->list[$i] = $this->createItem($i, $nid);
  46. $i++;
  47. }
  48. }
  49. }
  50. }