using yii2. User model activeRecorder and NewsletterSubcriber activeRecorder. NewsletterSubscriber works with User:
code
class User extends ActiveRecord implements IdentityInterface, IpRateLimitInterface
{
// Newsletter subscription
const SUBSCRIPTION_INACTIVE = 9;
const SUBSCRIPTION_ACTIVE = 10;
public function rules(): array
{
return [
['subscription', 'default', 'value' => self::SUBSCRIPTION_INACTIVE],
['subscription', 'in', 'range' => [self::SUBSCRIPTION_INACTIVE, self::SUBSCRIPTION_ACTIVE]],
];
}
}
and
code
class NewsletterSubscriber extends ActiveRecord
{
const STATUS_DELETED = 0;
const STATUS_INACTIVE = 9;
const STATUS_ACTIVE = 10;
public function rules(): array
{
return [
['status', 'default', 'value' => self::STATUS_INACTIVE],
['status', 'in', 'range' => [self::STATUS_DELETED, self::STATUS_INACTIVE, self::STATUS_ACTIVE]],
];
}
public function isSubscriber(string $email): NewsletterSubscriber|false
{
$subscriber = self::find()->where(['email' => $email, 'status' => self::STATUS_ACTIVE])->one();
return $subscriber ?: false;
}
public function getSubscriberByEmail(string $email): ?self
{
return self::find()->where(['email' => $email])->one();
}
public function upsertSubscriber(string $email, int $status, ?int $userId = null): bool
{
$subscriber = self::find()->where(['email' => $email])->one();
if ($subscriber === null)
{
return $this->createSubscriber($email, $status, $userId);
}
else
{
return $this->updateSubscriber($email, $status, $userId);
}
}
protected function createSubscriber(string $email, int $status, ?int $userId = null): bool
{
$transaction = \Yii::$app->db->beginTransaction();
try
{
$user = null;
// If user exist...
if ($userId !== null)
{
$user = User::findOne($userId);
// User must exist if userId provided
if (!$user)
{
return false;
}
// Sync user subscription to $status if different
if ($user->subscription !== $status)
{
$user->subscription = $status;
if (!$user->save(false, ['subscription']))
{
throw new YiiDbException('Failed to save user data to database.');
}
}
}
// Check if subscriber already exists — fail if it does
$subscriber = self::find()->where(['email' => $email])->one();
// Subscriber exists, creation fails
if ($subscriber !== null)
{
return false;
}
// Create new subscriber
$subscriber = new self();
$subscriber->email = $email;
$subscriber->generateSubscriberToken();
// Use User subscription if User exists, else passed $status
$subscriber->status = $user ? $user->subscription : $status;
// If $userId is not null and user exist and ids match...
if ($user !== null && $userId === $user->id)
{
$subscriber->user_id = $userId;
}
// This could include 'user_id' or not, depending on if they existed or not...
if (!$subscriber->save(false))
{
throw new YiiDbException('Failed to save user subscriber data to database.');
}
// If all saves are successful, commit the transaction.
$transaction->commit();
return true;
}
catch (\Throwable $e)
{
// An error occurred; roll back the transaction.
$transaction->rollBack();
// Use the ExceptionLogger to handle and log the exception.
ExceptionLogger::log($e, 'newsletter_create_subscriber_model_error_');
}
return false;
}
protected function updateSubscriber(string $email, int $status, ?int $userId = null): bool
{
$transaction = \Yii::$app->db->beginTransaction();
try
{
$user = null;
// If user exist...
if ($userId !== null)
{
$user = User::findOne($userId);
// User must exist if userId provided
if (!$user)
{
return false;
}
// Sync user subscription to $status if different
if ($user->subscription !== $status)
{
$user->subscription = $status;
if (!$user->save(false, ['subscription']))
{
throw new YiiDbException('Failed to save user data to database.');
}
}
}
// Check if subscriber already exists — fail if it does not
$subscriber = self::find()->where(['email' => $email])->one();
// Subscriber missing — update fails
if ($subscriber === null)
{
return false;
}
// Sync subscriber status with User subscription if User exists
if ($user !== null && $subscriber->status !== $user->subscription)
{
$subscriber->status = $user->subscription;
}
elseif ($subscriber->status !== $status)
{
$subscriber->status = $status;
}
// Link user_id if missing and valid
if ($subscriber->user_id === null && $user !== null && $userId === $user->id)
{
$subscriber->user_id = $userId;
}
// This could include 'user_id' or not, depending on if they existed or not...
if (!$subscriber->save(false))
{
throw new YiiDbException('Failed to save subscriber data to database.');
}
// If all saves are successful, commit the transaction.
$transaction->commit();
return true;
}
catch (\Throwable $e)
{
// An error occurred; roll back the transaction.
$transaction->rollBack();
// Use the ExceptionLogger to handle and log the exception.
ExceptionLogger::log($e, 'newsletter_update_subscriber_model_error_');
}
return false;
}
}
User $user->subscription trumps the newsletter subscriber models status, if user exists, if not we fallback to newsletter subscriber only.
Trying to create a account setting that turns on and off this feature:
code
namespace app\models\forms;
use Yii;
use yii\base\Model;
use yii\base\InvalidArgumentException as YiiBaseInvalidArgumentException;
use yii\base\Exception as YiiBaseException;
use yii\db\Exception as YiiDbException;
use app\models\User;
use app\models\NewsletterSubscriber;
use app\helpers\ExceptionLogger;
class AccountNewsletterForm extends Model
{
public int $subscription;
// @var app\models\User
private ?User $_user = null;
// @var NewsletterSubscriber $_subscriber
private ?NewsletterSubscriber $_subscriber = null;
public function __construct(int $id, array $config = [])
{
$this->_user = User::findIdentity($id);
if (!$this->_user)
{
$msg = \Yii::t('app', 'Unable to find account.');
throw new YiiBaseInvalidArgumentException($msg);
}
$this->subscription = $this->_user->subscription;
parent::__construct($config);
}
public function rules()
{
return [
['subscription', 'integer'],
// Subscription: Inactive(9), Active(10)
['subscription', 'in', 'range' => [9, 10]],
];
}
public function process(): bool
{
try
{
$model = new NewsletterSubscriber();
// upsertSubscriber(string $email, int $status, ?int $userId = null): bool
$subscriber = $model->upsertSubscriber(
$this->_user->email,
$this->_user->subscription,
$this->_user->id
);
if (!$subscriber)
{
throw new YiiBaseException('Failed to update subscription data to the database.');
}
// Set account Subscription
$this->_user->subscription = ($this->subscription == 10) ? 9 : 10;
// Use 'false' to skip validation as model is already validated.
if (!$this->_user->save(false, ['subscription']))
{
throw new YiiDbException("Failed to save user data to the database.");
}
return true;
}
catch (\Throwable $e)
{
// Use the ExceptionLogger to handle and log the exception.
ExceptionLogger::log($e, 'account_newsletter_form_error_');
}
return false;
}
}
account controller:
code
class AccountController extends SeoController
{
public function actionSettings(): Response|string
{
$user = $this->findModel($this->_userId);
$modelNewsletter = new AccountNewsletterForm($user->id);
return $this->render('settings', [
'modelNewsletter' => $modelNewsletter,
]);
}
public function actionNewsletter(): Response|string
{
$user = $this->findModel($this->_userId);
try
{
$model = new AccountNewsletterForm($user->id);
}
catch (YiiBaseInvalidArgumentException $e)
{
throw new YiiWebBadRequestHttpException($e->getMessage());
}
$request = \Yii::$app->request;
if ($request->isPost)
{
if ($model->load($request->post()) && $model->validate())
{
if ($model->process())
{
$msg = \Yii::t(
'app',
'<h4 class="alert-heading">Email Address Changed</h4>
<p>Your newsletter subscription has been successfully updated.</p>'
);
\Yii::$app->session->setFlash('success', $msg);
return $this->redirect(['account/settings']);
}
else
{
\Yii::$app->session->setFlash('error', ErrorMessageHelper::unexpectedError());
return $this->redirect(['account/settings']);
}
}
}
return $this->redirect(['account/settings']);
}
Looking at your current implementation, I can see several issues and mismatches in your AccountNewsletterForm::process() method and in your view logic that are causing inconsistencies:
Problem analysis
1. Inverting subscription value logic in AccountNewsletterForm::process
Your form subscription value is:
9 for inactive (unsubscribed) and
10 for active (subscribed)
In the process method, after successfully doing the newsletter subscriber upsert, you have this line:
This inverts the subscription, so if the user currently is subscribed (10), you forcibly set it to unsubscribed (9), and vice versa, regardless of what was requested. This means a user trying to "subscribe" gets unsubscribed and one trying to "unsubscribe" gets subscribed.
2. The upsertSubscriber is called with $this->_user->subscription
But $this->_user->subscription is the current subscription status — before user submitted the form, so you update the subscriber status with the old value.
You never use the newly submitted $this->subscription value to update the subscription state.
3. Form attribute subscriptions and View button text are inconsistent
This is swapped — if currently subscribed, the button should say "unsubscribe" instead of "subscribe", and if unsubscribed, the button should say "subscribe".
Do I have to have a hidden input for tihs to work?
Assistant
Yes, you do need the hidden input for this approach to work properly.
Why?
The form must include an input named subscription with the value that you want to submit to the server.
Since you only have a submit button, and it's not a checkbox or select input, you must store the current "intended" subscription state somewhere in the form data.
The hidden input serves this purpose; the button’s click handler toggles its value before submitting.
Without the hidden input, the form submits no subscription attribute, so on the server side $this->subscription would be empty or default, and your subscription update won't behave as expected.
What if you don’t want a hidden input?
You can implement this toggling differently, for example:
Use a checkbox that directly posts subscription = 10 when checked, 9 when unchecked.
Use two separate buttons, one for "subscribe" sending subscription=10, one for "unsubscribe" sending subscription=9.
Use JavaScript to add a query param or form data dynamically—but still you need to post the subscription value somehow.
I dont want to change the layout code and would prefer the statusTextandbuttonText to change like this, but with the suggested fixes
Assistant
Got it! You want to keep your layout and structure mostly as-is, but fix the logic so:
$statusText shows current subscription ("subscribed" or "unsubscribed")
$buttonText shows the action the user will perform by clicking (the opposite state: if subscribed, show "unsubscribe"; if unsubscribed, show "subscribe")
The form submits the correct new subscription value (the toggled one)
No JS, or minimal changes, using a hidden input
How to fix your code with minimal layout changes
You need to submit the toggled subscription status, so you actually want the hidden input subscription with the new value (not the current one).
Your current code outputs the hidden input with the old/current subscription value:
This outputs the hidden input with the value $modelNewsletter->subscription which is current state, but you want the opposite.
Solution: Set the hidden input value to the toggled subscription value before rendering
You can do this right before rendering the hidden input, for example:
php
<?php
// Calculate currently subscribed or not
$currentStatus = $modelNewsletter->subscription;
// Status text - current subscription
$statusText = ($currentStatus == User::SUBSCRIPTION_ACTIVE)
? \Yii::t('app', 'subscribed')
: \Yii::t('app', 'unsubscribed');
// Button text - show action opposite to current status
$buttonText = ($currentStatus == User::SUBSCRIPTION_ACTIVE)
? \Yii::t('app', 'unsubscribe')
: \Yii::t('app', 'subscribe');
// Calculate toggled value to send in hidden input
$toggledValue = ($currentStatus == User::SUBSCRIPTION_ACTIVE)
? User::SUBSCRIPTION_INACTIVE
: User::SUBSCRIPTION_ACTIVE;
// Set the toggled value explicitly in the form model attribute
// so that the hidden input contains the new value.
$modelNewsletter->subscription = $toggledValue;
echo Html::activeHiddenInput($modelNewsletter, 'subscription');
?>
User
this needs to be yii::t(): "You are currently from our newsletter."
Assistant
Certainly! To make the entire sentence translatable using Yii::t(), including the dynamic <b> wrapped $statusText, you can do this:
php
<p class="subscription-status">
<?= Yii::t('app', 'You are currently <b>{status}</b> from our newsletter.', [
'status' => Html::encode($statusText),
]) ?>
</p>
Explanation:
The entire string is wrapped in Yii::t()
{status} is a placeholder substituted with the encoded status text
This allows translators to reposition the placeholder and formatting if needed
Html::encode() ensures the injected $statusText is safe for output
That way translators can adjust the whole phrase naturally in other languages while preserving the HTML formatting.
User
now what if i wanted to add the vanilla js to this:
3. Add this vanilla JS below the form to toggle the hidden input value on button click:
php
<?php
$js = <<<JS
document.addEventListener('DOMContentLoaded', function() {
var btn = document.querySelector('#account-newsletter button[name="subscribe-button"]');
var input = document.getElementById('accountnewsletterform-subscription');
btn.addEventListener('click', function(event) {
// Toggle value between 10 and 9
if (input.value === '10') {
input.value = '9';
// Optionally change button text here if desired, e.g.:
// btn.textContent = 'Subscribe';
} else {
input.value = '10';
// btn.textContent = 'Unsubscribe';
}
});
});
JS;
$this->registerJs($js);
?>
Not yet included in a published release.
The user expects to click the button to toggle the status, so text says what action will happen, not what the current status is.
What should happen:
When the form loads:
The subscription model attribute is set to User's current subscription status (9 or 10).
On form submit:
The submitted subscription attribute (presumably from a checkbox/button toggle) reflects what the user wants to set.
The process method updates both User and NewsletterSubscriber records accordingly.
The button text should be the opposite of the current status:
If user is subscribed (10), button label is "unsubscribe"
If user is unsubscribed (9), button label is "subscribe"
Inside process(), you use the submitted status ($this->subscription), not the old one from $this->_user->subscription.
How to fix your code
1. Fix AccountNewsletterForm::process method
Here is a fixed version of process(), with comments:
php
public function process(): bool
{
try
{
$model = new NewsletterSubscriber();
// Use the submitted subscription status, not the old user subscription
$subscriberUpdated = $model->upsertSubscriber(
$this->_user->email,
$this->subscription, // <-- Use $this->subscription here
$this->_user->id
);
if (!$subscriberUpdated)
{
throw new YiiBaseException('Failed to update subscription data in the database.');
}
// Update the User subscription to the submitted status
$this->_user->subscription = $this->subscription;
// Skip validation because the form validated already
if (!$this->_user->save(false, ['subscription']))
{
throw new YiiDbException("Failed to save user data to the database.");
}
return true;
}
catch (\Throwable $e)
{
ExceptionLogger::log($e, 'account_newsletter_form_error_');
}
return false;
}
Notice:
We don't toggle or invert the value; we save the submitted value directly.
The form submission contains subscription=9 or subscription=10, so we update accordingly.
2. Fix your form (view) submit button and hidden input
You need to send the requested subscription status as the form input.
You can do this with a hidden field and the button toggling the value on each click.
For example, add a hidden input subscription and JavaScript to toggle the value when the button is clicked:
subscription form attribute is a hidden input field.
The button just submits the form; before submit, the JS toggles the hidden field value to the opposite subscription state, i.e., user toggles subscription on/off.
This way, the submitted value is the desired new state.
3. Fix your view's status text and initial hidden input value
Make sure that subscription is set correctly and matches the current user subscription:
php
<!-- Show status text -->
<?php
$statusText = ($modelNewsletter->subscription == User::SUBSCRIPTION_ACTIVE)
? \Yii::t('app', 'subscribed')
: \Yii::t('app', 'unsubscribed');
?>
<p class="subscription-status">
<?= \Yii::t('app', 'You are currently <b>{status}</b> from our newsletter.', ['status' => Html::encode($statusText)]) ?>
</p>
In the form, Html::activeHiddenInput() outputs the input with the current subscription value, initially 9 or 10.
Summary of changes
process() method: use $this->subscription instead of $this->_user->subscription. Don't invert toggling in code.
Form input: add a hidden input to capture the subscription state to be updated.
JS toggle: when user presses the button, JS toggles the hidden field value from 9↔10.
Button label: indicate the next action, i.e., if subscribed, label "unsubscribe". If unsubscribed, label "subscribe".
Additional notes
Alternatively, you can use a checkbox for subscribing/unsubscribing, but since you have only two states, toggle button + hidden input is simpler.
Always use constants (User::SUBSCRIPTION_ACTIVE) instead of hardcoded numbers to avoid mistakes.
Make sure your rules() validate the subscription attribute correctly (which you are already doing).
Let me know if you want me to help with a checkbox-based form or further integration tips!
$statusText shows current subscription status (subscribed or unsubscribed)
The hidden input [holds the new subscription status (toggled)]
The submit button shows action the user will perform (subscribe or unsubscribe)
When form is submitted, you get the new subscription status in your form model attribute $subscription to process
You don’t need JS or extra inputs, because you build the toggled value on the server side
Just a reminder for your form model and process method
Make sure your process() updates based on $this->subscription:
php
public function process(): bool
{
try {
$model = new NewsletterSubscriber();
if (!$model->upsertSubscriber(
$this->_user->email,
$this->subscription,
$this->_user->id
)) {
throw new \Exception('Failed to update newsletter subscriber.');
}
$this->_user->subscription = $this->subscription;
if (!$this->_user->save(false, ['subscription'])) {
throw new \Exception('Failed to save user subscription.');
}
return true;
} catch (\Throwable $e) {
ExceptionLogger::log($e, 'account_newsletter_form_error_');
}
return false;
}
This minimal change will fix your view logic and keep your UI intact exactly as you want.
Let me know if you want me to check your form processing code as well!
Full minimal example with your existing layout, including JS: