Madhu Nair
Madhu Nair

Reputation: 436

How to get the first drop down value as none

I get the desired options from the following code, but I need to add an empty option as the first value of the returned array as '' => 'none', then the rest of values.

function dropdown() {
  return db_select('node', 'n')
    ->condition('n.type', 'abc')
    ->condition('n.status', 1)
    ->fields('n', array('nid', 'title'))
    ->orderBy('n.title', 'ASC')
    ->execute()
    ->fetchAllKeyed();
}

This, however, gives only values from the database.

Upvotes: 2

Views: 120

Answers (1)

Syscall
Syscall

Reputation: 19779

You could prepend the entry before to return the data:

function dropdown() {
  $data = db_select('node', 'n')
    ->condition('n.type', 'abc')
    ->condition('n.status', 1)
    ->fields('n', array('nid', 'title'))
    ->orderBy('n.title', 'ASC')
    ->execute()
    ->fetchAllKeyed();
  return ['' => 'none'] + $data ;
}

Possible output:

array(463) {
  ['']=>
  string(4) "none"
  [367]=>
  string(7) "Title 1"
  [63]=>
  string(7) "Title 2"
  ...
}

If there are no nodes available for your conditions, it will returns:

array(1) {
  [""]=>
  string(4) "none"
}

Upvotes: 5

Related Questions