二月 8, 2016 | 後端和Drupal

該如何排序Drupal Views Exposed Form Filter Element? "#weight"居然不管用

前言

Drupal 7 的 Form API是熟悉Drupal開發的人最常看的網頁,因為有互動的地方,就會有Form,而在Drupal裡面,跟Form有關的最重要的就是Drupal Form API,在Form之中,要排序只需要在每個element裡面加上“#weight”這個屬性即可進行排序,然而在Views的Exposed Form裡面,"#weight"是無法使用的

傳統做法

使用hook_form_form_id_alter($form,$form_states)這個function可以在Form產生出來前,進行更動,若是傳統要更改排序的做法將會是以下程式,通過更改每個Field的「#weight」來改動對應field的位置。
以下範例主要想要將Exposed Form三個欄位,分別是custom field 1,custom field 2,custom field 3,而排序方式想要改成1->3->2

<?php
function hellosanta_form_views_exposed_form_alter(&$form, &$form_state){
  $form['field_custom_field_1']['#weight']=-10;
  $form['field_custom_field_3']['#weight']=-8;
  $form['field_custom_field_2']['#weight']=-7;

}
?>

以上完全不管用

解決的方法

其實在Views Exposed Form Filter裡,要重新排序是需要針對Form['#info']才有辦法的,以下為範例

<?php
function hellosanta_form_views_exposed_form_alter(&$form, &$form_state){

  // 這裏是您想要把您指定的element移到的位子
  $insert_index = 2;

  $element_to_insert = array();
  $element_to_insert['filter-sort'] = array(
    'value' => 'field_custom_field_3',  //這個為你想要變動的那個欄位名稱
  );

  $form_info_top = array_slice($form['#info'], 0, $insert_index);
  $form_info_bottom = array_slice($form['#info'], $insert_index);
  $new_form_info = $form_info_top + $element_to_insert + $form_info_bottom;
  $form['#info'] = $new_form_info;

}
?>  

結論

其實Exposed Form Filter的排序問題是很常遇到的,例如今天是餐廳網頁,往往就需要做地點、分類、交通、關鍵字等等Exposed的Form Filter來給客戶,而順序會是很重要的UI之一,因此這樣的做法,可以解決日後,Exposed Form的Element順序問題,分享給大家。

使用我們的服務即表示您同意Cookie政策。了解更多