Как аяксифицировать отправку веб-формы в Drupal 7?


Я попытался изменить рендеринг веб-формы с помощью hook_form_alter() и hook_node_view() в пользовательском модуле, чтобы я мог где-нибудь добавить "#ajax".

У кого-нибудь уже был некоторый опыт работы с webform и ajax на D6 или D7? Я предполагаю, что логика будет одинаковой для D6 и D7, тогда изменится только реализация.

Author: Jim Kirkpatrick, 2011-07-04

3 answers

Модуль Ajax работает для меня в Drupal 6.

Для Drupal 7:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
      // see if webform_client_form_ is in the form_id
      if(strstr($form_id, 'webform_client_form_')) {
        // get the nid so we can use it in the wrapper value
        $nid = $form['#node']->nid;
        // add the ajax properties to the submit button
        $form['actions']['submit']['#ajax'] = array(
          'callback' => 'mymodule_webform_js_submit',
          'wrapper' => 'webform-client-form-' . $nid,
          'method' => 'replace',
          'effect' => 'fade',
        );
      }
    }

function mymodule_webform_js_submit($form, $form_state) {
      // define the $sid variable (submission id from webform)
      $sid = $form_state['values']['details']['sid'];
      // if we have a sid then we know the form was properly submitted, otherwise, we'll just return the existing $form array
      if ($sid) {
        // first we have to load up the webform node object
        $node = node_load($form_state['values']['details']['nid']);
        // create an array up with the confirmation message, retreived from the webform node
        $confirmation = array(
          '#type' => 'markup',
          '#markup' => check_markup($node->webform['confirmation'], $node->webform['confirmation_format'], '', TRUE),
        );
        // return the confirmation message
        return $confirmation;
      }
      else {
        // return the form
        return $form;
      }
    }
 9
Author: Matthew Woodard, 2012-02-28 16:56:46

Одним из самых простых способов, если вы хотите аяксифицировать только определенную форму, будет добавление плагина формы jquery. Это довольно прямолинейно.

Добавьте приведенный ниже код в функцию предварительной обработки страницы в template.php файл.

  1. Сначала добавьте плагин jquery с кодом ниже.

    Drupal_add_js(drupal_get_path("тема", "ваша тема")."/js/jquery.form.js ");

  2. Затем добавьте приведенный ниже код, замените #your_form_ID на ваш идентификатор формы

    Drupal_add_js('

                (function($){ 
    $(document).ready(function() { 
    
                $("#your_form_ID").ajaxForm(function() { 
                    alert("Thank you for your comment!"); 
                }); 
    });     }(jQuery));;
    
           ', 'inline');
    

Это все, что вы сделали. Возможно, вы захотите рассмотреть возможность загрузки скриптов только на те страницы, которые вам нужны.

 0
Author: esafwan, 2012-02-26 21:42:33

Посмотрите, есть ли Модуль Ajax может помочь вам в этом. Смотрите документацию , а также

 -1
Author: pal4life, 2011-10-24 13:09:17