I have created a Views with an exposed filter and I tried to use hook_form_alter to convert it to a select list. Now, I need to set the default value as the first option whatever output in the select list. I DONT'T need to have '-Any-' as the default value which usually do. I wonder how can I achieve this. The page keep showing the below message when first visit the page not until one of the option is selected and applied.

An illegal choice has been detected. Please contact the site administrator.

Here the code in my template.php. Hope you can help me out. Thanks!

if($form_id == 'views_exposed_form' && $form['#id']=='views-exposed-form-news-page') { 

     $query = db_select('node', 'n');
     $query->fields('n', array('title'));
     $query->condition('n.type', 'news');
     $query->orderby('n.title', 'ASC');
     $result = $query->execute();

     // Get Select options 
     $options = array();  

     foreach( $result as $node ){
       $options[$node->title] = $node->title;

    // Alter the form
        $form['title_1'] = array(
         '#type' => 'select',
         //'#default_value' => ??
         '#options' => $options,
         '#title' => t('Filter By'), 

You need to add the following code to your implementation of hook_form_alter():

if (empty($form_state['input']['title_1'])) {    
  // set the first element as default value
  $form_state['input']['title_1'] = reset($options);
  • Thanks! But by assigning $option[0] to the form, it threw me "Notice: Undefined offset: 0.." I think mine is an associative array. Is there a way to get the value from the first associative array ? – Adamtan Mar 25 '15 at 14:35
  • Sure, you can $form_state['input']['title_1'] = reset($options); – quotesBro Mar 25 '15 at 21:27
  • That's exactly what I need. It works perfectly! You are awesome ! – Adamtan Mar 26 '15 at 1:03

Your Answer

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

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