Saturday, September 12, 2020

Drupal form option populate from loop and also make a custom form options.

 


 $q = db_select('taxonomy_term_data','term')

 ->fields('term',array('tid','name'))

 ->condition('term.vid', 10);

 $q->join('field_data_field_tag_type','tag','term.tid = tag.entity_id');

 $results = $q->execute()->fetchAll();

 $options = array();

 foreach($results as $key => $data){

   $options[$data->tid] = $data->name;

 }

 $form['field_activity']["en"]["#options"] = $options;


Now Second Example:-

$loop = db_query('SELECT id, name FROM {table}')->fetchAllKeyed();



Hook form alter for select list


function myhook_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == 'views_exposed_form'){

      $nodes = db_select('node', 'n')
        ->fields('n', array('title'))
        ->condition('type', 'news')
        ->orderBy('n.title', 'ASC')
        ->execute();
      $dropdown_array = array('' => t('-- Any --'));
      foreach ($nodes as $node) {
        $dropdown_array[$node->title] = $node->title;
      }

      // Alter form
      $form['title'] = array(     
         '#type' => 'select',
         '#default_value' => '1',        
         '#options' => $dropdown_array,
      ); 

   }//endif

}

No comments:

Post a Comment

If you have any problem please let me know.