3

I've built a form with the form API, and it's submitting via ajax via this type of thing:

  $form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'submit',
  '#ajax' => array(
      'callback' => 'handyman_form_callback',
      'method' => 'replace',
      'wrapper' => 'form-wrap',
      'effect' => 'fade'
  )
);

The problem is, if the form is returned due to validation errors the javascript applied to the form no longer works. I've read lots about the attachBehaviors function but I'm not sure where I could put this to make it work, and not sure if this is even the correct thing to do.

Any help?

  • Is that your custom javsascript applied to form ? if so, can you paste your javascript code – Dinesh Kumar Sarangapani Sep 4 '12 at 8:17
  • Yes it's just custom jQuery for calculating fields on the fly, making labels disappear on click etc... I add it using drupal_add_js at the top of my template page. Not sure showing you this is relevant though, I just need to know how to apply it again to the ajaxed form once it comes back with validation errors. – Chris Sep 4 '12 at 8:55
  • 1
    In a validation error, for is not rebuilt so your drupal_add_js won't be called again. You can attach JavaScript to your form using $form['#attach'] property. – AyeshK Aug 18 '13 at 17:14
  • @Ayesh's comment contains the answer. He should post it as an answer with a little more detail so you can accept it. Here's a reference to the relevant forms api documentation. api.drupal.org/api/drupal/… – Alfred Armstrong Jun 23 '14 at 13:21
0

you can attach custom jQuery functions in your modules every time you load content just attaching functions to the Drupal.behaviors like this:

(function($) {

  Drupal.behaviors.your_module = {

    attach: function(context, settings){
      $('#element').bind('click', function(event){
            alert('hello!');
      });
    }

  }

}

In this way, every time Drupal loads content, no matter via ajax or a page refresh, it will automatically attach the desired behaviors. Don't forget to include the js in your pages.

| improve this answer | |
0

You can put your code in the hook_validate function of your form if you are using it. Because every time when form shows validation errors then it is rebuilt by Drupal so any css or JavaScript added to the form is lost.

So you just need to include the js again to add it in the form.

function hook_banner_form()
{
drupal_add_js("javascript","inline");
//............................
//............................
//........................
}

function hook_banner_form_validate($form_state)
{
drupal_add_js("javascript","inline");
//............................
//............................
//........................
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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