ComputedShowroomsReferences.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 ComputedShowroomsReferences 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('taxonomy_term')
  34. ->condition('status', 1)
  35. ->condition('vid', 'showroom');
  36. $tids = $query->execute();
  37. shuffle($tids);
  38. $terms = entity_load_multiple('taxonomy_term', $tids);
  39. // \Drupal::logger('materio_home')->notice(print_r($nodes, true));
  40. $key = 0;
  41. foreach ($terms as $tid => $term) {
  42. // \Drupal::logger('materio_home')->notice($nid);
  43. $this->list[$key] = $this->createItem($key, $term->id());
  44. $key++;
  45. }
  46. }
  47. }