I have created a image upload module based on http://www.akchauhan.com/create-image-upload-field-using-drupal-form-api/

I have added a hook_block so I can use this as a block on multiple pages. When a validation error occurs the error shows at the top of the page but I would like the error to be placed within the block. How would I do this?

Comments

j_ten_man’s picture

You will need to use javascript to do this. Instead of putting the error text out (I assume you are using form_set_error), you would want to put the error text into the drupal settings variable. and then use some javascript to output it. Here is a quick example.

HTML:

<div id="my_block">
  <form>
  ...
  </form>
</div>

PHP code:

function my_custom_form() {
  $form = array();
  ...
  $form['my_field'] = array(
    '#title' => t('My Field'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  ...
  return $form;
}

function my_custom_form_validate($form, $form_state) {
  //Grab any errors that may already be set
  //You may not want to do this because the error messages most likely 
  //relate to this form submission, but if you want to, this is how
  $errors = drupal_get_messages('error');
  if ($form_state['values']['my_field'] == 'illegal') {
    form_set_error('my_field', t('That field is illegal.'));
  }
  //I am not positive this will work her because Drupal may refresh the page. However, you could do something with the session and bring this over. I'll let you figure it out.
  drupal_add_js(array('my_custom_errors' => theme('status_messages', 'error'), 'setting');
  //Reset all of the old error messages
  foreach ($errors as $error) {
    drupal_set_message($error, 'error');
  }
}

JS Code:

Drupal.behaviors.my_custom_error_block = function(context) {
  if (Drupal.settings.my_custom_errors) {
    $('#my_block').prepend(Drupal.settings.my_custom_errors);
  }
}
nhero’s picture

thanks, I see that the errors are now in $errors.

I couldn't get your js to work so I just did this:

<?php
foreach($errors['error'] as $error) {

     drupal_add_js(array('error' => $error), 'setting');

}
 ?>

and this for the js

	 $('#foo').prepend(Drupal.settings.error);

I would like to understand what you wrote though and I was wondering if you knew where to look for a tutorial.

gpk’s picture