0

I have a custom module which uses hook_form_views_exposed_form_alter() to sort the options of a select list into alphabetical order.

This appears to work because dmp($form) shows $form['field_keywords_tid']['#options'] to be in alphabetical order, but when checking the select list the order is different.

You can see the view and the dpm() output on the dev site.

My code so far is:

function dependant_keyword_filter_form_views_exposed_form_alter(&$form, &$form_state) {
  if ($form['#id'] == 'views-exposed-form-annotated-bibliography-page') {
    foreach ($form_state['view']->filter as $field => $filter) {
      if ($filter->options['exposed']  && $filter->options['id'] == 'field_keywords_tid' ) {
        $field_id = $form['#info']['filter-field_keywords_tid']['value'];
        asort($form[$field_id]['#options']);
      }
    }
    dpm($form);
  }
}

I thought I needed to replace $form['filter-field_keywords_tid']['#options'] with the sorted array so I tried the following code after the foreach above, but this didn't work either.

$options = array('All' => '- Any -');
foreach ($form[$field_id]['#options'] as $key => $val) {
  $options[$key] = $val;
}
$form['field_keywords_tid']['#options'] = $options;

I also tried the code below found in this Drupal Answers post with the same result. dpm() output sorted but select list not.

foreach ($form_state['view']->filter as $filter) {
  if($fid = $filter->options['expose']['identifier']) {
    asort($form[$fid]['#options']);
  }
}

I'd appreciate any suggestions.

1
  • 1
    Have you tried using $form['#after_build'] or '#after_build' on the element itself. Commented Feb 19, 2015 at 11:08

1 Answer 1

2

J. Reynolds suggestion was the answer.

Creating a new function for the sort code and using $form['#after_build'] to call it resulted in the select box being sorted alphabetically.

function dependant_keyword_filter_form_views_exposed_form_alter(&$form, &$form_state){
if ($form['#id'] == 'views-exposed-form-annotated-bibliography-page') {
    $form['#after_build'][] = '_sort_alphabetically';
  }
}
function _sort_alphabetically($form, $form_state) {
        foreach ($form_state['view']->filter as $field => $filter) {
            if ($filter->options['exposed']  && $filter->options['id'] == 'field_keywords_tid' ) {
                $field_id = $form['#info']["filter-field_keywords_tid"]['value'];
                asort($form[$field_id]['#options']);
            }
        }
        return $form;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.