【问题标题】:Sorting Field Collection Programmatically in Drupal 7在 Drupal 7 中以编程方式对字段集合进行排序
【发布时间】:2014-10-22 07:36:05
【问题描述】:

保存节点时如何以编程方式更改字段集合中项目的顺序/重量? 任何帮助表示赞赏。谢谢。

【问题讨论】:

    标签: drupal drupal-7 drupal-field-collection


    【解决方案1】:

    已经找到答案了。我正在使用hook_node_presave,然后重新排序字段集合数组。之前我用的是hook_node_update,但是没用。

    【讨论】:

      【解决方案2】:

      这是一个代码 sn-p,用于在保存节点之前按其任何字段对字段集合进行排序:

      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'];
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-30
        相关资源
        最近更新 更多