<?php
namespace Drupal\bacademy_core\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Url;
use Drupal\user\Entity\User;
class SubscribeController extends ControllerBase {
public function __construct(EntityTypeManager $entityTypeManager) {
$this->entityTypeManager = $entityTypeManager;
}
public function subscribe(int $id) {
$user = $this->entityTypeManager->getStorage('user')->load($id);
/** @var User $user */
$subscribed = $user->get('field_mailchimp_subscription')[0]->get('subscribe')->getValue();
if ($subscribed != "1") {
$user->set('field_mailchimp_subscription', ['subscribe' => "1"] );
$user->save();
return Url::fromRoute('entity.user.canonical', ['user' => $user->id()])->toString();
} else {
return Url::fromRoute('entity.user.canonical', ['user' => $user->id()])->toString();
}
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter