ComputedShowroomsReferences.php 1.7 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. use Drupal\workflow\Entity\WorkflowManager;
  11. // https://www.drupal.org/node/2112677
  12. // https://www.cornel.co/article/entity-reference-computed-field-example-drupal
  13. // https://www.caxy.com/blog/drupal-custom-form-and-computed-fields
  14. class ComputedShowroomsReferences extends EntityReferenceFieldItemList
  15. {
  16. use ComputedItemListTrait;
  17. /**
  18. * The entity type manager.
  19. *
  20. * @var \Drupal\Core\Entity\EntityTypeManagerInterface
  21. */
  22. protected $entityTypeManager;
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function __construct(BaseFieldDefinition $definition, $name, TypedDataInterface $parent) {
  27. parent::__construct($definition, $name, $parent);
  28. $this->entityTypeManager = \Drupal::entityTypeManager();
  29. }
  30. /**
  31. * Compute the values.
  32. */
  33. protected function computeValue() {
  34. $query = \Drupal::entityQuery('taxonomy_term')
  35. ->condition('status', 1)
  36. ->condition('vid', 'showroom');
  37. // remove masqué
  38. $tids = $query->execute();
  39. shuffle($tids);
  40. foreach ($tids as $key => $tid) {
  41. $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
  42. $sid = WorkflowManager::getCurrentStateId($term, 'field_workflow');
  43. if($sid != 'workflow_visible') continue;
  44. $this->list[$key] = $this->createItem($key, $tid);
  45. }
  46. }
  47. }