0

I have a content type Speaker that uses an Event content type as reference. The Event has a start date and time field. There can be any number of events that a speaker speaks at, when visiting the speaker page, the events are not ordered by date, they are ordered by id. How do I programmatically change this?

I am able to get the field value and sort them by date, but I am not able to set them back to the variable.

Related Drupal API Link

use \Drupal\Component\Utility\SortArray;


function mytheme_preprocess_node__speaker_page(&$variables) {
  $node = $variables['node'];
  $entity_ids = [];
  if ($node) {
    if (isset($node->field_events)) {
      $items = $node->field_events; //entity reference
      $unsorted=array();
      foreach ($items as $item) {
        $target_id = $item->target_id;
        $field_event = $item->entity;
        //creating a new unsorted array with the target id and event date, this is used for sorting
        array_push($unsorted, array('target_id' => $target_id, 'event_date' => strtotime($field_event->field_date_of_event->value)));
      }
      //sorting
      usort($unsorted, function ($a, $b) {
        return SortArray::sortByKeyInt($a, $b, 'event_date');
      });
      //sorted ids
      $new_entity_ids = array_column($unsorted, 'target_id');

      $items_new = \Drupal\node\Entity\Node::loadMultiple($new_entity_ids);
      $variables['node']->field_events = $items_new; //this doesn't work
      //$variables['node']->set($field_name)->referencedEntities(); 
    }
  }
}
9
  • You still have to change the order in the render array for this to have an effect on the output.
    – Kevin
    Sep 24 at 13:09
  • Wouldn't it be easier to drop this logic into a field formatter?
    – Kevin
    Sep 24 at 13:34
  • That's where I would do it.
    – Jaypan
    Sep 24 at 15:46
  • 1
    The problem is you don't really want to deal with render array manipulation here, and the moment you want to show this field anywhere else, you will have to do the code again in another place. Field Formatters are re-usable.
    – Kevin
    Sep 24 at 18:35
  • 1
    Similar discussion about manipulating the referenced entity list in a field formatter including a code example: drupal.stackexchange.com/questions/294728/…
    – 4k4
    Sep 24 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.