Search code examples
ajaxformsdrupalcallbackdrupal-7

How to access form states inside an ajax callback function


I'm working on a block module and would like to perform ajax operations on its configuration forms when a file is uploaded via a managed_file field.

So when the managed_file hidden field change (once the file is successfully uploaded), there is an ajax callback. The ajax is called like this:

function updateVideo($action){
(function ($) {
    $.ajax({
        url: '/block_video/update_video', // drupal menu path
        dataType: 'json',
        type: 'POST',
        data: { 'action' : $action },
        success: function(data){
            // @ TODO
        }
    });
})(jQuery);
}

The drupal path registered above (/block_video/update_video) call a function where I would like to retrieve the block configuration $form_state variable with its current state (not initial). Is it possible to see the current block configuration form states without using javascript directly and without a calling a page refresh?

It would be way simpler for me to just use the '#ajax' property on the managed_file, but it doesn't have it. So I added the ajax callback above by waiting for a value change on the managed_file hidden element and this part is working (using the method described here http://forum.jquery.com/topic/adding-a-change-event-on-a-hidden-field).

I should be able to retrieve the $form_state in my custom ajax callback. I would like to do it the way it's done with the FAPI [#ajax][callback] (both $form & $form_state are passed to the callback parameters - I only need the current $form_state passed to my callback or accessed in it), I couldn't figure how it's done by Drupal.


Solution

  • Alright, I fixed it soon after asking it so here the answer : I didn't find any solution to retrieve form_states outside the #ajax callback, so when the hidden field state change, I get the current form state directly from a pure jQuery ajax function.

    Off topic but kind of related : I managed others form_states inside the usual FAPI #ajax php callback, I needed to call some custom js right after, so with the method below you can trigger a second ajax callback or just a function. It's done this way :

      // Code inside the FAPI #ajax callback :
      // Trigger the function $.fn.ajaxTrigger defined in my js file.
      $commands[] = ajax_command_invoke(NULL, 'ajaxTrigger');
      return array(
        '#type' => 'ajax',
        '#commands' => $commands,
      );
    

    With this command you can call any javascript function from a Drupal 7 #ajax callback.