0
如何在節點保存時以編程方式更改字段集合內項目的順序/權重? 任何幫助表示讚賞。謝謝。以編程方式在Drupal 7中排序字段集合
如何在節點保存時以編程方式更改字段集合內項目的順序/權重? 任何幫助表示讚賞。謝謝。以編程方式在Drupal 7中排序字段集合
已經找到答案。我正在使用hook_node_presave
,然後重新排序字段集合數組。以前我使用的是hook_node_update
,它沒有工作。
這是保存節點之前整理其任何字段的字段集合的代碼片斷:
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'];
}
對你有好處。請分享代碼 – 2014-10-22 18:32:42