I needed to remove the default “-None-“/”-Select-” option that Drupal’s Form API adds to “select” form elements. Let’s take an example. Consider the following “select” element definition for a form:
$element = array ( '#type' => 'select', '#options' => array ( 1 => 'Very poor', 2 => 'Not that bad', 3 => 'Average', 4 => 'Good', 5 => 'Perfect', ), '#required' => TRUE, '#title' => 'Rating', );
It looks like the image on the right when rendered. Notice the additional “-Select-” option that Drupal added for data entry. I did not want that option to appear on the data entry form.
Some studying of Drupal docs and searching did not threw up anything. But I was able to achieve what I needed with some testing. Here’s what I did.
I added an ‘#after_build’ method for the form element like below:
$element = array ( '#type' => 'select', '#options' => array ( 1 => 'Very poor', 2 => 'Not that bad', 3 => 'Average', 4 => 'Good', 5 => 'Perfect', ), '#required' => TRUE, '#title' => 'Rating', '#after_build' => array('_eventbook_get_rating_widget_after_build'), );
And in the ‘#after_build’ method, unsetted the non-desired option from the ‘#options’ array:
{syntaxhighlighter brush: php;fontsize: 100; first-line: 1; }function _eventbook_get_rating_widget_after_build ($element, &$form_state) {
//Remove the default option.
unset($element[‘#options’][”]);
return ($element);
}{/syntaxhighlighter}
It was easy in the end, but would have been more useful if Drupal provided an attribute to prevent this default option from being added automatically.
thank you so much!
I’d like to put the callback function within an include file, and use module_load_include() in the form. However, doing so throws up a Call to undefined function error after pressing submit. Is there a way of doing that so it works?
Hi,
I am trying your solution, but its not coming through. I hve the following code in my hook_form_alter:
$form[‘field_tuv_interview_question’] = array (
‘#type’ => ‘select’,
‘#options’ => $options,
‘#required’ => TRUE,
‘#title’ => ‘Questions’,
‘#after_build’ => array(‘_field_tuv_interview_question_after_build’),
);
I get the select list on the form. Then I have the function :
function _field_tuv_interview_question_after_build($element, &$form_state) {
//Remove the default option.
unset($element[‘#options’][”]);
return ($element);
}
Thanks,
Viv
Thank you so much, works perfect !