-2

I have the following code to set subscriptions to a simplenews newsletter on or off:

    $user_load = User::load($userID_current);
    $newsletter_subscriptions = [
        'newsletter1' => 'on',
        'newsletter2' => 'off',
        'newsletter3' => 'off',
        'newsletter4' => 'off',
    ];

    foreach ($newsletter_subscriptions as $system_name => $value) {

        $subscription_manager = \Drupal::service('simplenews.subscription_manager');

        $newsletter = \Drupal::entityTypeManager()
            ->getStorage('simplenews_newsletter')
            ->loadByProperties(['system_name' => $system_name]);

        if ($value == 'on') {
            $subscription_manager->subscribe($user_load, $newsletter);
        } else {
            $subscription_manager->unsubscribe($user_load, $newsletter);
        }
    }

in the $newsletter i got back NULL even though the properties exists (checked by this:

$newsletter_storage = \Drupal::entityTypeManager()->getStorage('simplenews_newsletter');
$system_names = $newsletter_storage->getQuery()
    ->execute();
foreach ($system_names as $system_name) {
    \Drupal::logger('simplenews')->info('Simplenews system name: @system_name', ['@system_name' => $system_name]);
}

whats wrong with my $newsletter? Does someone have experiences with simplenews 3?

1
  • 1
    This code does not prove at all that the property system_name exists. The array values resulting from $query->execute() are always arrays of entity IDs.
    – Hudri
    Mar 31 at 12:23

1 Answer 1

-2

It seems that chatGPT and Drupal are not best friends, so i had to find the solution the oldschool (long & painful) way. The solution was to provide the right subscribe() arguments, so i didn't need the $newsletter.

$user_load = User::load($userID_current);
$newsletter_subscriptions = [
    'newsletter1' => 'on',
    'newsletter2' => 'off',
    'newsletter3' => 'off',
    'newsletter4' => 'off',
];

foreach ($newsletter_subscriptions as $system_name => $value) {

    $subscription_manager = \Drupal::service('simplenews.subscription_manager');

    if ($value == 'on') {
        $subscription_manager->subscribe($user_load->getEmail(), $system_name);
    } else {
        $subscription_manager->unsubscribe($user_load->getEmail(), $system_name);
    }
}
1
  • There is no need to put the line initializing $subscription_manager inside foreach(). It is sufficient to initialize the variable once.
    – apaderno
    Apr 2 at 8:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.