Hello, How do I automatically sort my collection by a date field ?

Thank you

Comments

jmuzz’s picture

Priority: Critical » Normal
bunthorne’s picture

Version: 7.x-1.0-beta5 » 7.x-1.0-beta7
Category: Support request » Feature request

I would find this helpful as well. Currently my FC table sorts by the order the items were added (the FC ID). But my items are actually performance dates/times, so I would want to be able to add additional dates/times in the middle if needed.

The workaround is to create a View block of the Field Collection items with a Contextual Filter to the Content Pages that own them, then display them in a block below the Content page.

But if some table management options could be added, such as one finds built into to Views, it would make the FC table much more useful.

Changing to Feature Request.

giupenni’s picture

+1

kiritoly’s picture

Sorting obviously may be performed at rendering time...

But if you need to set the order in the database (so the widgets will show the items already sorted), you can use this snippet for sorting the field collection items by any of its fields, before saving a node:

function your_module_node_presave($node){
  if ($node->type == 'foo') {
    // We must sort by this field collection field
    if (!empty($node->field_to_sort_by)) {
      // Get the values of the sorting field. We must load the fc items for this.
      $items = field_get_items('node', $node, 'field_to_sort_by');
      foreach ($items as $item) {
        $fc[] = field_collection_field_get_entity($item);
      }
      // fc fields on nodes only contains 'value' and 'revision_id'.
      // We temporarily add the field to sort by, 
      // for using the convenient uasort() function over the array.
      $tmp_array = $node->field_to_sort_by[LANGUAGE_NONE];
      foreach ($tmp_array as $key => $item) {
        $tmp_array[$key]['sortfield'] = $fc[$key]->field_to_sort_by[LANGUAGE_NONE][0]['value'];
      }
      // Now we sort the node's field array using uasort().
      usort($tmp_array, 'my_module_sortByField_asc');
      // unset the sorting field before updating node's field collection
      foreach ($tmp_array as $key => $item) {
        unset($tmp_array[$key]['sortfield']);
      }
      $node->field_to_sort_by[LANGUAGE_NONE] = $tmp_array;
    }
  }
}

function my_module_sortByField_asc($a, $b) {
  return $a['sortfield'] - $b['sortfield'];
}