DomainAccessField.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace Drupal\domain_access\Plugin\views\field;
  3. use Drupal\views\ResultRow;
  4. use Drupal\views\Plugin\views\field\Field;
  5. /**
  6. * Field handler to present the link an entity on a domain.
  7. *
  8. * @ViewsField("domain_access_field")
  9. */
  10. class DomainAccessField extends Field {
  11. /**
  12. * {@inheritdoc}
  13. */
  14. public function getItems(ResultRow $values) {
  15. $items = parent::getItems($values);
  16. // Override the default link generator, which wants to send us to the entity
  17. // page, not the entity we are looking at.
  18. if (!empty($this->options['settings']['link'])) {
  19. foreach ($items as &$item) {
  20. $object = $item['raw'];
  21. $entity = $object->getEntity();
  22. $url = $entity->toUrl()->toString();
  23. $domain = $item['rendered']['#options']['entity'];
  24. $item['rendered']['#type'] = 'markup';
  25. $item['rendered']['#markup'] = '<a href="' . $domain->buildUrl($url) . '">' . $domain->label() . '</a>';
  26. }
  27. uasort($items, [$this, 'sort']);
  28. }
  29. return $items;
  30. }
  31. /**
  32. * Sort the domain list, if possible.
  33. */
  34. private function sort($a, $b) {
  35. $domainA = isset($a['rendered']['#options']['entity']) ? $a['rendered']['#options']['entity'] : 0;
  36. $domainB = isset($b['rendered']['#options']['entity']) ? $b['rendered']['#options']['entity'] : 0;
  37. if ($domainA !== 0) {
  38. return $domainA->getWeight() > $domainB->getWeight();
  39. }
  40. // We don't have a domain object so sort as best we can.
  41. return $a['rendered']['#plain_text'] > $b['rendered']['#plain_text'];
  42. }
  43. }