You are here

function ajax_poll_form_alter in AJAX Poll 7

Same name and namespace in other branches
  1. 6 ajax_poll.module \ajax_poll_form_alter()

Implements hook_form_alter().

File

./ajax_poll.module, line 31
Enables voting on polls without reloading the page.

Code

function ajax_poll_form_alter(&$form, $form_state, $form_id) {
  if (in_array($form_id, array(
    'poll_view_voting',
    'poll_cancel_form',
  ))) {
    $form['#attached']['library'][] = array(
      'system',
      'jquery.form',
    );
    $form['#attached']['js'][] = drupal_get_path('module', 'ajax_poll') . '/ajax_poll.js';
    $node = isset($form['#node']) ? $form['#node'] : node_load($form['#nid']);
    $teaser = (int) isset($node->teaser);
    $block = (int) (!empty($form['#block']));
    $action = $form_id == 'poll_view_voting' ? 'vote' : 'cancel';
    $form['ajax_url'] = array(
      '#type' => 'hidden',
      '#value' => url('poll/ajax/' . $action . '/' . $node->nid . '/' . $teaser . '/' . $block),
    );
    $form['ajax_text'] = array(
      '#type' => 'hidden',
      '#value' => $action == 'vote' ? t('Voting...') : t('Canceling...'),
    );

    // Add the AJAX Poll class to the form.
    if (empty($form['#attributes']['class'])) {
      $form['#attributes']['class'] = array(
        'ajax-poll',
      );
    }
    else {
      $form['#attributes']['class'][] = 'ajax-poll';
    }
    $form['#attributes']['class'][] = ' ajax-' . $action;

    // Add submit handler to supress redirection on AJAX requests.
    if ($action == 'vote') {
      $form['vote']['#submit'][] = 'ajax_poll_submit';
    }
    else {
      $form['actions']['submit']['#submit'][] = 'ajax_poll_submit';
    }
  }
}