简体   繁体   English

在Drupal 7中以编程方式对字段集合进行排序

[英]Sorting Field Collection Programmatically in Drupal 7

How to change the order/weight of the items inside field collection programmatically when the node is saved? 保存节点后,如何通过编程方式更改字段集合中项目的顺序/权重? Any help is appreciated. 任何帮助表示赞赏。 Thank you. 谢谢。

Already found the answer. 已经找到答案了。 I'm using hook_node_presave and then reorder the field collection array. 我正在使用hook_node_presave ,然后对字段集合数组重新排序。 Previously I was using hook_node_update and it didn't work. 以前,我使用hook_node_update ,但是没有用。

This is a code snippet for sorting a field collection by any of its fields before saving the 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); } // field collection 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']; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM