3

I have installed and enabled the simplenews module and I have a newsletter subscribtion block in my website frontpage now. I would ajaxify the subscribe's button in that block so I googled many websites about that, but I couldn't find any answer about 'How to ajaxify simplenews subscribtion form in drupal 7, any suggestion?

1

I don't know if you found your answer but I had the same problem and found a solution :

In a hook_form_alter

  if ($form_id == 'simplenews_block_form_' . variable_get('simplenews_id', 23)) {
    $form['submit']['#ajax'] = array(
      'callback' => 'simplenews_block_form_ajax_submit',
      'wrapper' => 'block-simplenews-' . variable_get('simplenews_id', 23),
      'method' => 'replace',
      'effect' => 'fade',
      'progress' => array('type' => 'none'),
    );
    $form['submit']['#executes_submit_callback'] = TRUE;
    unset($form['#submit']);
    unset($form['#validate']);
  }

And then in the ajax submit

/**
 * Ajax callback to reload the image field
 */
function simplenews_block_form_ajax_submit($form, $form_state) {
  $return = '<div id="block-simplenews-23" class="block block-simplenews first odd">';
  $return .= '<h2 class="block__title block-title">' . t('Newsletter') . '</h2>';
  $return .= render($form);
  $return .= '</div>';
  if (!valid_email_address($form_state['values']['mail'])) {
    $return .= '<section class="errors-primal">' . t('The e-mail address is not valid.') . '</section>';
    return $return;
  }
  else {
    if (module_exists('simplenews')) {
      module_load_include('inc', 'simplenews', 'views/simplenews.subscription');
      $tid = $form['#tid'];
      $account = simplenews_load_user_by_mail($form_state['values']['mail']);
      $confirm = simplenews_require_double_opt_in($tid, $account);
      $subscription = simplenews_subscribe_user($form_state['values']['mail'], $tid, $confirm, 'website');
      $return .= '<section class="confirm-primal">' . t('You have been subscribed.') . '</section>';
      return $return;
    }
  }
}

This will do a simple registration to the database in AJAX. You can adapt depending on what you exactly need.

1

Additionally to pbonnefoi answer, submit can be simpler:

/**
 * Ajax callback for simplenews
 */
function CUSTOMMODULE_simplenews_form_ajax_submit($form, &$form_state) {
  if (!valid_email_address($form_state['values']['mail'])) {
    drupal_set_message(t('The e-mail address %mail is not valid.', array('%mail' => $form_state['values']['mail'])), 'error');
  }
  else {
    module_load_include('inc', 'simplenews', 'views/simplenews.subscription');
    simplenews_block_form_submit($form, $form_state);
  }
  return render($form);
}

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.