Simplenews block submission without reloading using Ajax - Drupal 9?

Simple News Ajax submit

 

Simplenews block submission without reloading using Ajax - Drupal 8 / 9

Simplenews module:
URL: https://www.drupal.org/project/simplenews

Steps:
1. Enable the simplenews module
2. Change the form id (if you want) - Go to /admin/structure/block/manage/simplenewssubscription
3. Assign it to one region
4. Implement the below code with your custom module.

That's it simple.

Code:

Implement with in your module form alter:

  Path: /modules/custom/MODULE_NAME/
  File: MODULE_NAME.module

<?php

use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\Html;

// MODULE_NAME_form_simplenews_subscriptions_block_newsletter_alter.
// Form Id is "simplenews_subscriptions_block_newsletter"

function MODULE_NAME_form_FORM_ID_alter(&$form, FormStateInterface $form_state, $form_id) {

  $form['#prefix'] = '<div id="' . Html::getClass($form_id) . '-messages" class="result_message"></div>
<div id="subscribe-wrapper">';
  $form['#suffix'] = '</div>';

  $form['actions']['subscribe']['#ajax']  = [
    'event' => 'click',
    'method' => 'replace',
    'effect' => 'fade',
    'disable-refocus' => FALSE,
    //'wrapper' => Html::getClass($form_id) . '-messages',
    'callback' => '\Drupal\MODULE_NAME\Form\MessageFormController::setMessage',
    'progress' => [
      'type' => 'throbber',
    ],
    'options' => ['query' => ['ajax_form' => 1]],
  ];

  // Rebuild the form
  $form_state->setRebuild(TRUE);

}

Implement your form Set message:

  Path: /modules/custom/MODULE_NAME/src/Form/MessageFormController
  File Name: MessageFormController.php

<?php

/**
 * @file
 * Contains \Drupal\MODULE_NAME\Form\MessageFormController.
 */

namespace Drupal\MODULE_NAME\Form;

use Drupal\simplenews\Form\SubscriptionsFormBase;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\ReplaceCommand;


/**
 * Configure simplenews subscriptions of the logged user.
 */
 abstract class MessageFormController extends SubscriptionsFormBase {

  /**
   * The Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * {@inheritdoc}
   */
  public function __construct(MessengerInterface $messenger = NULL) {
    $this->messenger = $messenger;
  }

  public static function setMessage(array &$form, FormStateInterface $form_state) {
   
    $message = [
      '#theme' => 'status_messages',
      '#message_list' => \Drupal::messenger()->all(),
    ];
 
    // Render Messages 
    $messages = \Drupal::service('renderer')->render($message);
    $status = $messages;

    // (Optional) Do some stuff or Additional condition to identify the message contains error
    /* if (preg_match_all('/<[a-z \'"]*role=[\'"]alert[\'"][^>]*>([^<]*)/i', $messages, $matches)) {
      $status = $messages;
      $attr = '';
    } else {
      $status = strip_tags(str_replace('e-mail', 'email', $messages));
      $attr = 'data-drupal-messages';
    } */

    $response = new AjaxResponse();
    $response->addCommand(
      new HtmlCommand(
        '#simplenews-subscriptions-block-messages', // Mention the message that you want to print
        '<div '.$attr.'>' . t('@result', ['@result' => $status]) . '</div>'),
    );

    //$response->addCommand(new ReplaceCommand('#simplenews-subscriptions-block', $form));
    
    // Replace the form:
    $response->addCommand(new ReplaceCommand('#subscribe-wrapper', $form));

    // Response
    return $response;
  }

 
}

 

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
1 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.