0

I need to add an exposed filter to my view in form of a select. I followed these steps.

  1. I exposed the Content: Countries (field_countries) filter to visitors
  2. I chose Grouped filters
  3. I added France with value equal to FR

I have many values to add in my list, but I have to select them from my database according to a specific condition. So my list must be dynamic.

In my module, I implemented hook_form_alter().

function projects_form_alter(&$form, &$form_state, $form_id) { 
  if ($form_id == 'views_exposed_form') {
    $all_countries = country_get_list();
    // $project_countries = Array ( [0] => FR [1] => IT )
    $new_filter = array('All' => t('All'));
    $i = 1;
    foreach ($project_countries as $key => $value) {
      $new_filter[$i] = $all_countries[$value];
      $i++;
    }
    $form['field_countries_value']['#options'] = $new_filter;
    return $form;
  }
}

This returns the list I need, but the search doesn't work anymore.

I also tried the following code.

foreach ($project_countries as $key => $value) {
  $new_filter[$key] = $all_countries[$value];
}
//$new_filter=Array('All'=>'All','FR'=>'France', 'IT'=>'ITALI')

How can I fix the code?

Thank you

  • What' type of field is field_countries? – Clive Apr 5 '18 at 9:15
  • I created a type of content project and it contains this field.. my view is for this type: project – A.Sana Apr 5 '18 at 9:26
  • And what type of field is field_countries? – Clive Apr 5 '18 at 9:33
  • field_countries is a text – A.Sana Apr 5 '18 at 9:37
  • If field_countries is a text field, then $form['field_countries_value']['#options'] doesn't have any sense. Or that, or we aren't using the same terminology. – kiamlaluno Apr 5 '18 at 10:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.