Subscription block throws exception if unique_id is not set (when rendered via Twig Tweak or programmatically)

Created on 17 April 2025, about 2 months ago

Problem/Motivation

When rendering the Simplenews subscription block programmatically (e.g., using {{ drupal_block('simplenews_subscription_block') }} in Twig Tweak or custom code), the following exception occurs:

Exception: Unique ID must be set with setUniqueId. in Drupal\simplenews\Form\SubscriptionsBlockForm->getFormId()

This happens because the block configuration's unique_id is empty by default, and the block's build() method does not generate one unless the block is placed and configured via the UI.

Steps to reproduce

  1. Add `{{ drupal_block('simplenews_subscription_block') }}` to a Twig template (e.g., via Twig Tweak).
  2. Visit the page.
  3. Observe the error.

The block should auto-generate a unique ID if none is set, so it works out-of-the-box in programmatic or Twig Tweak use.

Proposed resolution

Update SimplenewsSubscriptionBlock::build() to generate a UUID if unique_id is empty, e.g.:

$unique_id = !empty($this->configuration['unique_id']) ? $this->configuration['unique_id'] : $this->uuid->generate();
$form_object = $this->entityTypeManager->getFormObject('simplenews_subscriber', 'block')
  ->setUniqueId($unique_id)
  // ...

Workaround:

Manually supply a unique ID in the Twig Tweak call:

{{ drupal_block('simplenews_subscription_block', { unique_id: 'footer_newsletter' }) }}

Or place the block via the UI.

Patch:

A patch is attached that implements the fix.

🐛 Bug report
Status

Active

Version

4.1

Component

Code

Created by

🇰🇬Kyrgyzstan dan_metille

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024