1

I have made two select fields with the form api d7

and i need to make it required and the first option is null to force the user select both

i tried with #REQUIRED #EMPTY_VALUE OPTION but gives error unsupported operands

i see the validation function may help but my case have an ajax request based on the first select to get the values of the second

so i need to make it required and the first is null

the code answer

 $form['gov']=array('#title'=>'Gov','#name'=>'governorate'
,'#type'=>'select','#options'=>$options,'#ajax'=>array('callback'=>'ajax_callback',
'event'=>'change','wrapper'=>'replace'
  ,'method'=>'replace'));

 $form['city']=array("#title"=>'City',
'#name'=>'city','#type'=>'select'
,'#prefix' => '<div id="replace">',
'#suffix' => '</div>','#options'=>$op);

also the ajax request only happens one time

1
  • 1
    could you provide your code sample? Sep 26, 2012 at 11:10

2 Answers 2

2

To make the input required you need to use #required => TRUE, and if you wants to add a empty default value you need to add a value to your #options like '' => t('Please select')

See Form API Reference

2
  • i did as u mentioned and reviewed the form api and see that issue is a bug in drupal so needs help from others faced the same problem Sep 26, 2012 at 15:11
  • Your ajax_callback function returns an array? This post may help you.
    – vibaiher
    Sep 27, 2012 at 7:16
5

Add a empty value setting to the form array:

$form[$key] = array(
  ..
  '#empty_value' => '',
  ..
);

That will add a - Select - option to the list that will not pass a required validation if the user leaves it on - Select -.

Don't add an empty value to the #options array '' => t('Please select'). That will still pass a required validation if the user leaves that option selected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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