Hi,

I'm trying to display a custom error message when no keywords had been submitted in my search field.
Actually, I'm using Views module to display a search field. The major drawback of using Views in this case is that there is no error message like "Please enter some keywords" when nothing is put in the form field.

I'm aware of some previous posts that may be related to my problem, but I am still unable to get results :

This is what I have put in my template.php :

function oiseaux_form_views_exposed_form_alter(&$form, &$form_state, $form_id){
 if ($form_state['values'] == ' ') {
    form_set_error('keys', t('Please enter some keywords.'));
  }
;}

It is not working. Drupal says: « Notice : Undefined index: values [...] »

Here are some other informations that may be useful :

  • My template is named "oiseaux"
  • The #form_id of my search form is "views_exposed_form"
  • The textfield in which we type the search keywords has the #id "edit-rechercher"
  • The custom view created to expose the search form is named "page_recherche"

Thanks in advance.

Comments

emilie.viau’s picture

Any idea about a solution for this problem? Thank you again, i'm on this case for at least 1 month.

Sam Moore’s picture

I think your template is being called when the form is first deployed, in which case $form_state will be empty, no? You could do kpr($form_state) to check, if you have Devel installed. My guess is you'll get an empty object on page load, then some values after you've tried to submit.

Anyway I think what you want is a validator, using one of the Drupal validator functions. Here's some info:
http://befused.com/drupal/form-validation

emilie.viau’s picture

Many thanks Sam for your help. Yes, I have installed Devel one month ago and noticed that $form_state was empty. I'll give a try with the resources provided. Have a great day.

emilie.viau’s picture

I finally got it to work, with this piece of code :

function oiseaux_form_views_exposed_form_alter(&$form, $form_state) {
		$form['#validate'][] = 'oiseaux_views_exposed_form_validate';}

function oiseaux_views_exposed_form_validate(&$form, &$form_state) {
	if (isset($form_state['values']['rechercher'])) {
		$fieldcontent = $form_state['values']['rechercher'];}
	
		if ($fieldcontent['rechercher'] == '') {
		form_set_error('rechercher', t('Please enter some keywords .'));}
		;}

But the major problem with Views is that the code validates when the page is loading, rather than when you click the button of the search field. Because of that, the error message for empty fields is always showing. I had to find another solution using the GET method :

function oiseaux_form_views_exposed_form_alter(&$form, $form_state) {
  
  if (isset($_GET['rechercher'])){
  	if ($_GET['rechercher'] == '') {
	  form_set_error('rechercher', t('Please enter some keywords.'));}
	  ;}
	  ;}