ComputedShowroomsReferences.php 1.7 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. 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. $i=0;
  41. foreach ($tids as $tid) {
  42. $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
  43. $sid = WorkflowManager::getCurrentStateId($term, 'field_workflow');
  44. if($sid != 'workflow_visible') continue;
  45. $this->list[$i] = $this->createItem($i, $tid);
  46. $i++;
  47. }
  48. }
  49. }