namespace app\models;
use app\components\traits\BitmaskTrait;
class Product extends ActiveRecord
{
use BitmaskTrait;
public const PURCHASE_OPTIONS_CART = 1;// 2^0
public const PURCHASE_OPTIONS_INQUIRE = 2;// 2^1
public const PURCHASE_OPTIONS_BUYNOW = 4;// 2^2
/**
* Virtual attribute to hold array for form checkbox binding.
* @var int[]|null
*/
private ?array $_purchaseOptionsArray = null;
public static function tableName(): string
{
return '{{%product}}';
}
public function rules(): array
{
return [
['purchase_options', 'default', 'value' => self::PURCHASE_OPTIONS_CART | self::PURCHASE_OPTIONS_INQUIRE],
['purchaseOptionsArray', 'safe'],// Also allow purchaseOptionsArray for form binding as safe
['purchaseOptionsArray', 'validatePurchaseOptions'],
];
}
/**
* Validates for $this->_purchaseOptionsArray into $product->purchase_options
* @param string $attribute
* @param array $params
*
* Note: Do NOT add parameter(s) type hints. This method overrides an interface
* without type hints on parameters, adding types will cause PHP compatibility errors.
* Only docblock types to indicate expected input types.
*/
public function validatePurchaseOptions($attribute, $params = []): void
{
$values = $this->$attribute;
if (!is_array($values))
{
$this->addError($attribute, 'Invalid purchase options.');
return;
}
$bitmask = $this->arrayToBitmask($values);
$flagsSum = array_sum(self::getPurchaseOptionFlags());
if (($bitmask & ~$flagsSum) !== 0)
{
$this->addError($attribute, 'Product options contain invalid flags.');
return;
}
if (($bitmask & self::PURCHASE_OPTIONS_CART) && ($bitmask & self::PURCHASE_OPTIONS_BUYNOW))
{
$this->addError($attribute, 'Product purchase options cannot include both Cart and Buy Now.');
}
}
/**
* Returns the map of purchase option keys to labels for UI.
* @return array
*/
public function getPurchaseOptionsLabels(): array
{
return [
self::PURCHASE_OPTIONS_CART => \Yii::t('app', 'Cart'),
self::PURCHASE_OPTIONS_INQUIRE => \Yii::t('app', 'Inquire'),
self::PURCHASE_OPTIONS_BUYNOW => \Yii::t('app', 'Buy Now'),
];
}
/**
* Before Validation
* @url https://www.yiiframework.com/doc/api/2.0/yii-base-model#beforeValidate()-detail
* return bool
* Whether the validation should be executed. Defaults to true. If false is returned, the validation
* will stop and the model is considered invalid.
*
* Automatically set the 'type' of the post based on its category's type before validation.
*/
public function beforeValidate(): bool
{
if (!parent::beforeValidate())
{
return false;
}
/**
* Purchase Options Array to Bitmask
* Convert purchaseOptionsArray from form into bitmask int before validation.
*/
if ($this->_purchaseOptionsArray !== null)
{
$this->purchase_options = $this->arrayToBitmask($this->_purchaseOptionsArray);
}
elseif (is_array($this->purchase_options))
{
// Defensive: convert in case purchase_options is array (usually from form POST)
$this->purchase_options = $this->arrayToBitmask($this->purchase_options);
}
else
{
// Ensure integer type
$this->purchase_options = (int) $this->purchase_options;
}
return true;
}
/**
* Returns all possible purchase option flags.
* Useful in forms and validation.
*/
public static function getPurchaseOptionFlags(): array
{
return [
self::PURCHASE_OPTIONS_CART,
self::PURCHASE_OPTIONS_INQUIRE,
self::PURCHASE_OPTIONS_BUYNOW,
];
}
/**
* Defensive getter to return purchase_options with default if null.
* @return int
*/
public function getPurchaseOptions(): int
{
if ($this->purchase_options !== null)
{
return $this->purchase_options;
}
if ($this->isNewRecord)
{
return self::PURCHASE_OPTIONS_CART | self::PURCHASE_OPTIONS_INQUIRE;
}
return 0;
//return $this->purchase_options ?? 0;
}
/**
* Get Purchase Options for Checkboxes
* @return array
*
* Helper to get purchase options as array for checkbox input in forms.
*/
public function getPurchaseOptionsForCheckboxes(): array
{
return $this->bitmaskToArray($this->getPurchaseOptions(), self::getPurchaseOptionFlags());
}
/**
* Returns the purchase options as an array of flags.
* If the internal cache is null, it converts current bitmask.
* Useful for checkboxes.
*/
public function getPurchaseOptionsArray(): array
{
if ($this->_purchaseOptionsArray === null)
{
$this->_purchaseOptionsArray = $this->getPurchaseOptionsForCheckboxes();
}
return $this->_purchaseOptionsArray;
}
/**
* Accepts an array of flags and sets both virtual array and bitmask.
*/
public function setPurchaseOptionsArray(array $values): void
{
$this->_purchaseOptionsArray = $values;
$this->purchase_options = $this->arrayToBitmask($values);
//\Yii::error('setPurchaseOptionsArray called: ' . json_encode($values));
}
/**
* Has Purchase Options
* @param int $flag
* @return bool
*
* Instead of calling hasStatus() twice in the if condition, you can directly
* check using a bitwise operation:
*
* // Fetch the message with a specific ID.
* $product = Product::findOne($id);
*
* if (($product->purchase_options & (Product::PURCHASE_OPTIONS_CART | Product::PURCHASE_OPTIONS_INQUIRE)) ===
* (Product::PURCHASE_OPTIONS_CART| Product::PURCHASE_OPTIONS_INQUIRE)
* )
* {
* echo "This product is inquire only.";
* }
*
* In this alternative approach:
*
* The expression Product::PURCHASE_OPTIONS_CART | Product::PURCHASE_OPTIONS_INQUIRE
* combines both statuses (using the bitwise OR).
*
* The condition checks if both statuses are set within the status field of
* the message.
*
* if ($model->hasPurchaseOptions(Product::PURCHASE_OPTIONS_INQUIRE))
* {
* // do something
* }
*/
public function hasPurchaseOptions(int $flag): bool
{
return ($this->getPurchaseOptions() & $flag) === $flag;
}
/**
* Add Purchase Options
* @param int $flag
*
* Set Statuses (make sure to save):
*
* $user->addPurchaseOptions(Product::PURCHASE_OPTIONS_CART);
* $user->save();// Save changes to the database.
*/
public function addPurchaseOptions(int $flag): void
{
$current = $this->purchase_options ?? 0;
$this->purchase_options = $current | $flag;
}
/**
* Remove Purchase Options
* @param int $flag
*
* For example, if the current status is 5 (00101) and we want to remove
* the "Unread" status (1 or 00001), the resulting status will change to
* 4 (00100).
*
* Removing Purchase Options:
*
* $user->removePurchaseOptions(Product::PURCHASE_OPTIONS_CART);
*/
public function removePurchaseOptions(int $flag): void
{
$current = $this->purchase_options ?? 0;
$this->purchase_options = $current & (~$flag);
}
/**
* Getter User Statuses
* How to use:
*
* $user->isActive();
*/
public function isCart(): bool
{
return $this->hasPurchaseOptions(self::PURCHASE_OPTIONS_CART);
}
public function isInquire(): bool
{
return $this->hasPurchaseOptions(self::PURCHASE_OPTIONS_INQUIRE);
}
public function isBuynow(): bool
{
return $this->hasPurchaseOptions(self::PURCHASE_OPTIONS_BUYNOW);
}
/**
* Setters User Statuses
* How to use:
*
* $user->activateAccount();
*
* Note: Delete status is exclusive and clears all other flags.
*/
public function setCart(): void
{
$this->addPurchaseOptions(self::PURCHASE_OPTIONS_CART);
}
public function setInquire(): void
{
$this->addPurchaseOptions(self::PURCHASE_OPTIONS_INQUIRE);
}
public function setBuynow(): void
{
$this->addPurchaseOptions(self::PURCHASE_OPTIONS_BUYNOW);
}
}
Bitmask Trait
code
namespace app\components\traits;
trait BitmaskTrait
{
public function bitmaskToArray(int $bitmask, array $allFlags): array
{
$flags = [];
foreach ($allFlags as $flag)
{
if (($bitmask & $flag) === $flag)
{
$flags[] = $flag;
}
}
return $flags;
}
public function arrayToBitmask(array $flags): int
{
$bitmask = 0;
foreach ($flags as $flag)
{
$bitmask |= (int) $flag;
}
return $bitmask;
}
}
so i want to refactor the message code to be more inline with how product uses bitmask, cleaner. But also my reply form is not work, no error logs.. just
does nothing, which if i remember correct is usally a scenario issue. Lets make message code easier to understand and better. No snippets. full and complete
code only.
Assistant
Certainly! Below is a refactored complete Message model using your Product bitmask style and trait approach, and a cleaned-up ReplyForm with scenario handling fixed to work properly. I’ve also provided a BitmaskTrait that you can re-use.
BitmaskTrait (place in app\components\traits\BitmaskTrait.php)
php
<?php
namespace app\components\traits;
trait BitmaskTrait
{
/**
* Converts a bitmask int into an array of active flags.
* @param int $bitmask
* @param int[] $allFlags
* @return int[]
*/
public function bitmaskToArray(int $bitmask, array $allFlags): array
{
$flags = [];
foreach ($allFlags as $flag) {
if (($bitmask & $flag) === $flag) {
$flags[] = $flag;
}
}
return $flags;
}
/**
* Converts an array of flags into a single bitmask int.
* @param int[] $flags
* @return int
*/
public function arrayToBitmask(array $flags): int
{
$bitmask = 0;
foreach ($flags as $flag) {
$bitmask |= (int)$flag;
}
return $bitmask;
}
}
Refactored Message Model (app\models\Message.php)
php
User
Assistant
Great question!
Why do we have both validateStatusArray and validateStatus?
validateStatusArray is designed to validate the virtual attribute statusArray, which is an array used for form checkbox binding. It validates that the submitted array of flags from the form is valid and non-conflicting before converting and saving to the status integer field.
validateStatus is designed to validate the actual stored integer attribute status — typically invoked by Yii’s model validation during validate() or save() operations on the model itself. This validates that the integer bitmask stored in the database is valid and does not contain conflicting flags.
Where and when is each one used?
validateStatusArray
This is triggered by the rule:
php
['statusArray', 'validateStatusArray']
Meaning when you load and validate the form with statusArray (the virtual attribute), this method checks the submitted array values.
validateStatus
This is not explicitly attached to the Yii validator rules. So, unless you attach it as a rule, Yii doesn’t automatically call it.
In your previous code and typical use, you or some part of your code is supposed to call validateStatus('status') explicitly before saving or during an extended validation process. For example:
php
$message->validateStatus('status');
This ensures that the raw status int is valid independently of the virtual array. This is important during model updates or after programmatic changes to $status.
So is validateStatus really needed?
If you always validate the virtual attribute statusArray through the form and always save only if it is valid, then it might be redundant to validate the integer separately.
But, , then you need a final validation on the integer field itself, so calling is a good safety net.
User
code
public function process(): bool
{
$transaction = \Yii::$app->db->beginTransaction();
try
{
$scenario = $this->getScenario();
$updatedFields = [];// Message model attubutes.
// If Message Model status is not set to 'replied', and form Model 'reply' is not empty.
if (($this->_message->status !== Message::STATUS_REPLIED) && (!empty($this->reply)))
{
if (in_array($scenario, ['both']))
{
$this->_message->setStatusFromCheckboxes($this->checkboxes);
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();// Set it to the current Unix timestamp.
//$this->_message->repliedTime = date('Y-m-d H:i:s');// If defined as a timestamp '$this->timestamp()'.
$updatedFields = ['status', 'replied', 'repliedTime'];
}
if (in_array($scenario, ['replyOnly']))
{
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();
//$this->_message->repliedTime = date('Y-m-d H:i:s');
$updatedFields = ['replied', 'repliedTime'];
}
if (in_array($scenario, ['statusOnly']))
{
$this->_message->setStatusFromCheckboxes($this->checkboxes);
$this->_message->addStatus(Message::STATUS_READ);
$updatedFields = ['status'];
}
}
else
{
$this->_message->setStatusFromCheckboxes($this->checkboxes);
$this->_message->addStatus(Message::STATUS_READ);
$updatedFields = ['status'];
}
// Save Contact model depending on Scenario. $updatedFields['data'];
if ($this->_message->save(false, $updatedFields))
{
if ((in_array($scenario, ['replyOnly', 'both'])) && (!empty($this->reply)))
{
if (!$this->sendEmail())
{
throw new YiiBaseException('Failed to send email.');
}
}
// 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, 'reply_form_error_');
}
return false;
}
Assistant
Your process() method is functionally very close to mine, but yours has an extra conditional block checking:
php
if (($this->_message->status !== Message::STATUS_REPLIED) && (!empty($this->reply))) {
// handle all scenarios
} else {
// default fallback
}
Whereas mine simply switches on scenario without that extra check.
Analysis of your approach
Your current logic basically says:
If your Message status is NOT STATUS_REPLIED and reply text is present:
Apply scenario specific logic.
For example, if scenario is both, set status from checkboxes, add REPLIED, update reply and time.
If replyOnly, add REPLIED, set reply and time.
If statusOnly, set status from checkboxes and add READ.
Else (message already has REPLIED status OR no reply text):
Just update status from checkboxes and add READ.
That is perfectly fine if that logic matches your business rules.
Your approach includes extra safeguard:
If message is already status REPLIED, then no matter the scenario or reply text, it just updates statuses (adds READ).
If there is no reply text, it treats it as only status update regardless of scenario.
Some thoughts for improvement / stability & clarity
The checks for (in_array($scenario, ['statusOnly'])) inside the big if condition are somewhat redundant since the outer if requires non-empty reply. statusOnly scenario normally means no reply, only status update.
It could be simplified a bit by rearranging conditions, but if it works for you and matches your UX, it is absolutely fine to keep.
If you want minimal changes, I’d suggest possibly:
php
User
code
Assistant
You are right — I didn’t include the full controller previously.
Below is an example of how your MessageController could be implemented to work with the refactored Message model and ReplyForm, applying scenarios properly and handling the validation and saving process cleanly.
Example MessageController.php
php
User
Error
Non-static method app\models\Message::getStatusLabels() cannot be called statically
Assistant
The error
code
Non-static method app\models\Message::getStatusLabels() cannot be called statically
means you're calling a non-static method statically like:
php
Message::getStatusLabels()
but the method is an instance method, not static.
Why does this happen?
Look at your Message model method:
php
public function getStatusLabels(): array
{
return [
self::STATUS_UNREAD => \Yii::t('app', 'Unread'),
// ...
];
}
It is NOT declared as static, so calling Message::getStatusLabels() raises that PHP error.
How to fix?
You have two options:
Option 1: Make the method static
In your Message model, change the method to static:
php
public static function getStatusLabels(): array
{
return [
self::STATUS_UNREAD => \Yii::t('app', 'Unread'),
// ...
];
}
This is the preferred fix because logically, getStatusLabels() returns class-level constants mapping to labels — it's natural to make it a static method.
Option 2: Call it on instance, not statically
If for some reason you want to call on an instance:
php
$model = new Message();
$labels = $model->getStatusLabels();
But this is less practical because the labels are the same for all instances.
In your view or elsewhere, use:
php
$statusOptions = Message::getStatusLabels();
Assuming you made getStatusLabels() static.
Final steps
Go to your Message model.
Find getStatusLabels() method.
Change signature from:
php
public function getStatusLabels(): array
to:
php
public static function getStatusLabels(): array
Do the same if you have other similar methods that you call statically, like getStatusFlags().
Summary example:
php
public static function getStatusLabels(): array
{
return [
self::STATUS_UNREAD => \Yii::t('app', 'Unread'),
self::STATUS_READ => \Yii::t('app', 'Read'),
// etc
];
}
After this, your static calls will work fine and the error will be resolved.
If you want, I can review all relevant methods to suggest which should be static.
Certainly! Here's your first snippet updated to visually and structurally match the style of the second snippet, wrapping the checkboxes inside a <fieldset> with a <legend>, and organizing the layout with Bootstrap flex utility classes:
Added <fieldset> and <legend> around the checkbox list for semantic grouping and consistent labeling.
Wrapped checkboxes inside a container with the Bootstrap classes d-flex flex-wrap justify-content-start for responsive inline arrangement.
Kept the checkbox rendering code intact.
Added comments to mark container divs, matching your style.
This preserves your dynamic fetching of $statusOptions while matching the structure and styles of your provided example.
User
is their anywhere in message code that shows "message->type"
Assistant
In the large Message model code you provided earlier, there is one place referencing $this->type and related labels:
php
/**
* Types List
*/
public static function getTypeLabels(): array
{
return [
self::TYPE_CONTACT => \Yii::t('app', 'Contact'),
self::TYPE_INQUIRY => \Yii::t('app', 'Inquiry'),
self::TYPE_ORDER => \Yii::t('app', 'Order'),
self::TYPE_SUPPORT => \Yii::t('app', 'Assistance'),
];
}
public function getTypeList(): string
{
$types = self::getTypeLabels();
return $types[$this->type];
}
What does this mean?
Your Message model assumes the existence of a type attribute/column (likely an integer or string) storing the message type.
The constants TYPE_CONTACT, TYPE_INQUIRY, etc. — these constants were not provided in your excerpt but presumably exist with integer values.
The function getTypeLabels() returns a map of these types, and getTypeList() returns the label corresponding to the current message's $type.
Are those constants defined?
Your snippet does not include definitions for those TYPE_* constants. If they do not currently exist, you'd need to define them, for example:
php
public const TYPE_CONTACT = 1;
public const TYPE_INQUIRY = 2;
public const TYPE_ORDER = 3;
public const TYPE_SUPPORT = 4;
Or whatever values your application expects.
In summary:
Yes, there is usage of $message->type (via $this->type) in the getTypeList() method.
It is indirectly used wherever you call $message->getTypeList() to display the message's type label.
However, no other code you showed uses $message->type directly (e.g., no validations, no rules for it).
If you want to fully support type, you should:
Define the TYPE_* constants.
Add validation and possibly a default in the model’s rules.
Optionally add a database column type if not already present.
Use getTypeLabels() and getTypeList() for UI and display.
If you want, I can help you define and integrate the type property fully—just ask!
User
depending on the type of message should be factored on if a message can be replied too, and how its handled
Assistant
To handle different message types and conditionally allow replies (and possibly customize how replies are handled), you can extend your Message model and ReplyForm logic to take type into account.
Step 1: Define the message types constants and supporting methods in Message model
Add constants if missing:
php
public const TYPE_CONTACT = 1;
public const TYPE_INQUIRY = 2;
public const TYPE_ORDER = 3;
public const TYPE_SUPPORT = 4;
Add helper methods:
php
/**
* Returns all message type labels.
* @return array<int, string>
*/
public static function getTypeLabels(): array
{
return [
self::TYPE_CONTACT => \Yii::t('app', 'Contact'),
self::TYPE_INQUIRY => \Yii::t('app', 'Inquiry'),
self::TYPE_ORDER => \Yii::t('app', 'Order'),
self::TYPE_SUPPORT => \Yii::t('app', 'Support'),
];
}
/**
* Returns current message type label or Unknown.
*/
public function getTypeLabel(): string
{
$types = self::getTypeLabels();
return $types[$this->type] ?? \Yii::t('app', 'Unknown');
}
/**
* Indicates whether this message type is replyable.
* Customize per your business logic.
*/
public function isReplyable(): bool
{
// Example logic: only allow replies for Support and Inquiry
return in_array($this->type, [self::TYPE_SUPPORT, self::TYPE_INQUIRY], true);
}
Step 2: Modify ReplyForm to respect message type when processing
Update constructor or add a method to check if replies are allowed, e.g.:
php
public function canReply(): bool
{
return $this->_message->isReplyable();
}
Then in your validation or process methods:
User
the replyform, actionViewUpdate() and view-update.php all likely need updated to handle type.
if type is:
contact, than send email
Assistant
Absolutely! To handle the type-dependent reply behavior — specifically, if message type is contact, then you want to send email on reply — you'll need to:
Update ReplyForm to be type-aware,
Update your actionViewUpdate() controller method to adjust scenarios and processing based on type,
Update the view to show/hide reply form elements based on type.
Updated ReplyForm
Make it aware of whether the message can be replied to and if email should be sent:
php
User
as i was saying... the replyform, actionViewUpdate() and view-update.php all likely need updated to handle type.
/**
Message Management System
This is the model class for table "{{%message}}".
@property int $id
@property int|null $parent_id
@property int $type
@property int|null $product_id
@property string|null $name
@property string $email
@property string|null $subject
@property string $body
@property int $status
@property string|null $replied
@property int|null $repliedTime
@property string|null $created_ip
@property string|null $updated_ip
@property int|null $created_by
@property int|null $updated_by
@property int $created_at
@property int|null $updated_at
@property Message[] $replies
How to:
parentMessage=Message::findOne(id);// Find the message being replied to
$model = new Message();
model−>load(Yii::app->request->post());
model−>parentid=parentMessage->id;// Set the parent ID for threading
if ($model->save())
{
code
// Successfully saved the reply
}
*/
If a user has a account they can send message that only the admin can read, depending on how they send a message determions the type
of message and should also determine how the user interacts with said message.
If type is:
Contact: Send reply via email only
Inquiry are sent via modals (similar to contact form) directly to the admin. Only reply with email.
Order: Is from a user for order assistance, only users can use this feature. Send via message and email
Support: Is from a user only. Send via message and email
Assistant
Thanks for the detailed context! To adapt your message system to support different message types with different reply and handling logic, here’s a comprehensive plan and sample implementations for your:
Message model (with types & helper methods)
ReplyForm (scenario, validation, process based on type)
MessageController::actionViewUpdate() (handling form submission and reply logic)
View (view-update.php) (adjust UI based on message type)
1. Update your Message Model
Add type constants, helper methods, and type-based logic.
php
<?php
namespace app\models;
use yii\db\ActiveRecord;
use app\components\traits\BitmaskTrait;
class Message extends ActiveRecord
{
use BitmaskTrait;
// Message Types
public const TYPE_CONTACT = 1; // Contact form message
public const TYPE_INQUIRY = 2; // Product inquiry via modal/contact
public const TYPE_ORDER = 3; // User order assistance message
public const TYPE_SUPPORT = 4; // Support message from user
// ... (other constants and properties)
// Example status constants (as before)
public const STATUS_UNREAD = 1;
public const STATUS_READ = 2;
public const STATUS_REPLIED = 128;
// etc...
/**
* Returns mapping of message types.
*/
public static function getTypeLabels(): array
{
return [
self::TYPE_CONTACT => \Yii::t('app', 'Contact'),
self::TYPE_INQUIRY => \Yii::t('app', 'Inquiry'),
self::TYPE_ORDER => \Yii::t('app', 'Order'),
self::TYPE_SUPPORT => \Yii::t('app', 'Support'),
];
}
/**
* Returns current message type label.
*/
public function getTypeLabel(): string
{
$types = self::getTypeLabels();
return $types[$this->type] ?? \Yii::t('app', 'Unknown');
}
/**
* Returns whether this type supports replying via internal message (database).
*/
public function supportsMessageReply(): bool
{
return in_array($this->type, [self::TYPE_ORDER, self::TYPE_SUPPORT], true);
}
/**
* Returns whether this type requires email replies.
* Contact and Inquiry require email reply only
*/
public function requiresEmailReply(): bool
{
return in_array($this->type, [self::TYPE_CONTACT, self::TYPE_INQUIRY], true);
}
/**
* Returns whether the user (sender) can reply via internal messaging system.
* For your current logic, Orders and Support types allow user replies saved in DB.
*/
public function userCanReply(): bool
{
return $this->supportsMessageReply();
}
// Other existing methods such as statuses and bitmask...
}
User
Why cant the admin reply to all messages? since using the message it saves in the database and sends a email to
the user asking the question. Why am I limiting what the admin can do? with:
if ($model->userCanReply()) :
and such. The reply is what the user reads, now maybe I didn't explain well enough how this message management system
should work. Or perhaps thier needs to be a admin/user check somewhere and that determions if a email is sent or not.
Assistant
Great question and a very important clarification! You're right to rethink limiting the admin's ability to reply based solely on the message type.
Understanding the problem:
Users send messages of different types (Contact, Inquiry, Order, Support).
Admin views these messages and replies.
For admin replies:
Replies are saved in the database (message replies thread).
An email is sent to the user notifying them of the reply.
For user replies (if enabled):
Replies might only be saved internally, or sent as emails too, depending on your policy.
Why your current userCanReply() check causes issues:
userCanReply() method is typically written like this:
php
public function userCanReply(): bool
{
return $this->supportsMessageReply();
}
Where supportsMessageReply() is based on message type, e.g., only Order and Support return true.
This means your code is limiting "reply via messages" only to certain types, possibly thinking of "user replies" — but in reality:
ADMIN should be able to reply (message + email) on all message types.
Users may have restricted ability to reply or not reply depending on type.
What you need:
Separate the logic between "Who is replying?" (admin or user) and message "type".
Admins can reply internally (database) and send emails regardless of message type.
User replies may be restricted by message type and controls.
How to implement this
Step 1: Determine the current user’s role (Admin or User)
Assuming you have a user identity system and roles, e.g., Yii::$app->user->can('admin').
Step 2: Add method to detect if current user is admin or user
php
public function isAdminReply(): bool
{
return Yii::$app->user->can('admin'); // adjust according to your RBAC or auth
}
User
where are you getting isAdminReply() from?
Assistant
Good question!
isAdminReply() is not a built-in Yii method or something that exists out-of-the-box. It’s a custom helper method you define yourself to encapsulate the logic "Is the current reply being made by an admin user?".
Why create isAdminReply()?
You want to differentiate who is replying — admin or regular user.
It makes your code clearer and easier to maintain.
Where & how should you define it?
Probably inside your ReplyForm class (or possibly in the Message model or a base class if you prefer), so you can easily check that information anywhere in reply handling.
Example implementation in ReplyForm using Yii RBAC or your authentication system:
php
public function isAdminReply(): bool
{
// You can customize this check based on your app's user roles/permissions
return Yii::$app->user->can('admin');
}
What does this do?
Yii::$app->user->can('admin') checks if the currently logged-in user has the admin role or permission, using Yii’s RBAC or Access Control configured in your app.
If they do, returns true.
Otherwise, returns false.
How to customize?
If you use some other role or permission names, replace 'admin' with your app’s role or permission name.
If you rely on a different user property (like $user->isAdmin), you can implement accordingly.
Example alternative:
php
public function isAdminReply(): bool
{
return !Yii::$app->user->isGuest && Yii::$app->user->identity->isAdmin === true;
}
Here assuming your User model has an isAdmin boolean property.
Why not check this directly everywhere?
Putting this into a method like isAdminReply() keeps your form/controller code clean:
php
if ($this->isAdminReply()) {
// Admin-specific logic here (e.g. always allow reply, always send email)
} else {
// User-specific restrictions here
}
Recap:
It's a custom method you add.
It uses your app-specific user role or permission checks to decide if the current user is an admin.
You can call it from ReplyForm, Message model, controller, or helpers — wherever needed.
It enables conditional logic based on who is replying.
If you want, I can help you integrate role checks consistently in your models, forms, or controllers!
User
can i not just do it like this?
public function canReply(): bool
{
if (RoleHelper::isHelper())
{
return true;
}
code
return $this->supportsMessageReply();
}
/**
* TODO
*/
public function shouldSendEmailOnReply(): bool
{
// Admin replies always send email to notify user
if ($this->canReply())
{
return true;
}
// User replies email logic here (optional)
return $this->_message->requiresEmailReply();
}
Assistant
Yes, absolutely! Your approach is perfectly fine and even clearer — using your existing role helper (RoleHelper::isHelper()) to detect admin-like users (helpers) simplifies the logic meaningfully.
Explanation of your code
php
public function canReply(): bool
{
if (RoleHelper::isHelper()) {
// Admin or "helper" users can always reply
return true;
}
// Otherwise, only allow reply if message supports user reply
return $this->supportsMessageReply();
}
/**
* Whether an email should be sent when a reply is made.
*/
public function shouldSendEmailOnReply(): bool
{
// If current user can reply (admin/helper), always send email
if ($this->canReply()) {
return true;
}
// For users, check if message type requires email replies
return $this->_message->requiresEmailReply();
}
Why this is good:
You reuse your existing role helper — no need to reinvent admin detection.
Any user/actor considered a "helper" (admin, support staff, etc.) can always reply and trigger email notifications.
Regular users are restricted based on message type (supportsMessageReply() and requiresEmailReply()).
This cleanly separates:
Who can reply (canReply())
Whether email should be sent (shouldSendEmailOnReply())
Minor suggestion
In your shouldSendEmailOnReply(), maybe it’s safer to also check if there is reply text, so you don't send empty emails accidentally:
php
public function shouldSendEmailOnReply(): bool
{
if ($this->canReply() && !empty($this->reply)) {
return true;
}
return $this->_message->requiresEmailReply() && !empty($this->reply);
}
Final thoughts
Yes, using RoleHelper::isHelper() instead of creating a new isAdminReply() method is perfectly fine, idiomatic, and likely better:
You centralize role logic in one place.
Your form logic stays clean and maintainable.
It's easy to update permissions simply by extending or editing RoleHelper.
Summary
Your snippet is good practice and I fully recommend it. Just make sure:
RoleHelper::isHelper() returns true only for admin-like users who are allowed to reply and send emails always.
supportsMessageReply() & requiresEmailReply() remain focused on per message type rules (mostly for restricting user abilities).
If you want, I can help you integrate this pattern fully into your ReplyForm and controller!
User
so you suggest making shouldSendEmailOnReply() but than dont suggest where or how to use it?
Assistant
Great point! Sorry for the disconnect — yes, after creating shouldSendEmailOnReply(), you absolutely need to use it in your reply processing flow to decide when to send email notifications.
Where and how to use shouldSendEmailOnReply() in your code?
The natural place is inside your ReplyForm::process() method, which handles saving the reply and sending emails. Specifically, replace your current email sending condition with a call to shouldSendEmailOnReply(). This keeps the decision logic centralized.
Example: Using shouldSendEmailOnReply() in process()
php
public function process(): bool
{
$transaction = Yii::$app->db->beginTransaction();
try {
$scenario = $this->getScenario();
$fields = [];
if ($scenario === 'both') {
$this->applyStatusesToMessage();
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();
$fields = ['status', 'replied', 'repliedTime'];
} elseif ($scenario === 'replyOnly') {
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();
$fields = ['replied', 'repliedTime'];
} elseif ($scenario === 'statusOnly') {
$this->applyStatusesToMessage();
$this->_message->addStatus(Message::STATUS_READ);
$fields = ['status'];
}
if ($this->_message->save(false, $fields)) {
// Use shouldSendEmailOnReply() to decide sending email
if ($this->shouldSendEmailOnReply() && !empty($this->reply)) {
if (!$this->sendEmail()) {
throw new \Exception('Failed to send email.');
}
}
$transaction->commit();
return true;
}
} catch (\Throwable $e) {
$transaction->rollBack();
Yii::error("ReplyForm process failed: {$e->getMessage()}");
}
return false;
}
User
does this make sense
Assistant
Yes, your code logic mostly makes sense, just a few clarifications and suggestions to improve clarity and fix some minor issues:
What your snippet does:
Checks if the user can reply to this message ($model->userCanReply()).
If can reply:
If the message has not been replied (!$model->hasStatus(Message::STATUS_REPLIED)) AND the reply content is not set or empty (ValueHelper::isSetAndNull($model->replied)):
Shows a textarea field for the reply.
Otherwise:
Shows a bootstrap card displaying the existing reply with replied date/time.
If cannot reply:
Shows an alert that "You cannot reply to this message."
Wrapper .row div is opened inside the if($model->userCanReply()) block but closed after the else block. (A small fix needed)
Suggestions
Fix the .row wrapper:
You open <div class="row">only if user can reply, but close it after else which triggers if user cannot reply. This results in invalid HTML if the user cannot reply (no opening .row but closed div).
Solution: Move the opening <div class="row"> outside the first condition.
Use consistent naming or logic for checking if replied content is empty:
The method ValueHelper::isSetAndNull() is not standard, so make sure it does what you expect (checks if a value is set and not null or empty).
Alternatively, you can simplify with:
php
empty($model->replied)
Optional: Add classes to form textarea container for consistent Bootstrap layout (like wrapping textarea in .col-md-12).
Improved example adjusting these:
php
User
rewrite this to only appear if thier is a reply.. else do nothing
Assistant
Certainly! Here's your snippet rewritten so that it only renders the entire "User replies" block if there is at least one reply. If there are no replies, it outputs nothing:
The entire block is wrapped inside an if (!empty($replies)) check.
If $replies is empty, no markup is output at all — effectively "do nothing."
This keeps your page cleaner without empty sections.
If you'd like, I can also help provide an alternative that outputs a placeholder message or any other behavior!
User
so when i save the view-update.. it reloads the pag but than i get the error:
Bad Request
Missing required parameters: id (ID: error_68686e3032e9a2.54031066). Please try again later.
2025-07-05 00:13:36 [::1][1][nil56gnvnhbf0s5vbuiv8u6v09][error][yii\web\HttpException:400] yii\web\BadRequestHttpException: Missing required parameters: id
Assistant
The Bad Request - Missing required parameters: id error after saving and redirecting indicates that your redirect URL (probably in your controller) is missing the required id parameter.
Likely cause
In your action (e.g., actionViewUpdate), after successful save or processing, you are doing something like:
php
return $this->redirect(['view-update']);
But the view-update route requires an id parameter:
php
public function actionViewUpdate(int $id)
Since the redirect didn’t specify id, Yii throws BadRequestHttpException complaining about missing the required parameter.
if ($replyForm->process()) {
// After processing, redirect back to the same view
return $this->redirect(['view-update', 'id' => $model->id]);
}
Other things to check
Make sure all your links to view-update include 'id' as a GET parameter.
Check your URL manager rules if you have any special routing that might interfere.
Summary
Your redirect after post must include the required parameters (id) for the receiving action. Adding 'id' => $model->id to the redirect array fixes this error.
Let me know if you want me to check your controller code or give a full example!
User
code
Assistant
Your actionViewUpdate code looks mostly solid and follows the typical Yii2 pattern. The main reason you're getting the "Missing required parameter: id" error on redirect is here:
php
return $this->redirect(['index']);
Your index action probably expects no parameters, so that redirect is fine. But when you save and want to stay on the same page (e.g., viewUpdate), you must explicitly pass the id:
What you likely want
If you want to redirect back to the same message view after reply:
Your actionViewUpdate() requires $id as a parameter:
php
public function actionViewUpdate(int $id)
Redirecting without'id' => $model->id leads to missing parameter error.
Adding the ID tells Yii where exactly to redirect.
Additional optional tips
If you do want to redirect to 'index' (message list) after reply, just ensure index action does not require parameters.
If your redirect is meant to go to 'view-update', always include 'id'.
Summary
php
if ($replyForm->process())
{
$this->setScenarioSuccessFlash($replyForm->getScenario(), $model);
// Redirect to the same message view, passing id:
return $this->redirect(['view-update', 'id' => $model->id]);
}
If you want me to review the rest of your controller or help improve redirect logic, just ask!
User
did not solve the issue.. i click the submit button.. and i get:
The error message 'Missing required parameters: id' indicates that somewhere in your request lifecycle (likely during a redirect or URL generation), the id parameter, which is required by your action method, is not being provided.
Let's break down common causes and fixes for this issue in your context:
Step 1: Confirm which URL is causing the error
The error occurs after submission, likely during the redirect that happens after $replyForm->process().
From your code snippet:
php
if ($replyForm->process())
{
$this->setScenarioSuccessFlash($replyForm->getScenario(), $model);
return $this->redirect(['index']);
}
Here, You redirect to 'index' route without parameters.
Because 'index' action likely does NOT require an id, no problem here.
So this probably is NOT the source of your error.
Step 2: Identify any other redirects or URL generation that require id
Check the success flash message method you call:
php
private function setScenarioSuccessFlash(string $scenario, $model): void
{
switch ($scenario)
{
case 'statusOnly' :
$msg = \Yii::t(
'app',
'The status for message #{id} has been updated.',
['id' => $model->id]
);
break;
case 'replyOnly' :
case 'both' :
default :
$msg = \Yii::t(
'app',
'Your reply to {to} has been sent.',
['to' => $model->email]
);
break;
}
\Yii::$app->session->setFlash('success', $msg);
}
This is okay.
Step 3: Check your layout/breadcrumbs or view generating links that might lack 'id'
User
seemed to assit with it working.. but now im getting the error:
Failed to save message or send reply email.
Assistant
The error message "Failed to save message or send reply email" comes from your controller’s responding logic after $replyForm->process() returns false. This indicates one or both of these problems happened during process():
The database save failed
The email sending failed
How to debug and fix
1. Improve error visibility
Modify your process() method in ReplyForm to log and expose the error cause.
Add logging and get model errors after save fails.
Example update in process():
php
public function process(): bool
{
$transaction = Yii::$app->db->beginTransaction();
try {
$scenario = $this->getScenario();
$fields = [];
if ($scenario === 'both') {
$this->applyStatusesToMessage();
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();
$fields = ['status', 'replied', 'repliedTime'];
} elseif ($scenario === 'replyOnly') {
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();
$fields = ['replied', 'repliedTime'];
} elseif ($scenario === 'statusOnly') {
$this->applyStatusesToMessage();
$this->_message->addStatus(Message::STATUS_READ);
$fields = ['status'];
}
if (!$this->_message->save(false, $fields)) {
// Save failed — get errors and log
$errors = $this->_message->getErrors();
Yii::error('Message save error: ' . json_encode($errors), __METHOD__);
$transaction->rollBack();
return false;
}
// Decide on sending email
if ($this->shouldSendEmailOnReply() && !empty($this->reply)) {
if (!$this->sendEmail()) {
Yii::error('Failed to send reply email for message ID ' . $this->_message->id, __METHOD__);
$transaction->rollBack();
return false;
}
}
$transaction->commit();
return true;
} catch (\Throwable $e) {
$transaction->rollBack();
Yii::error("ReplyForm process exception: {$e->getMessage()}", __METHOD__);
return false;
}
}
Not yet included in a published release.
namespace app\models;
class Message extends ActiveRecord
{
const STATUS_UNREAD = 1;// 0b00001
const STATUS_READ = 2;// 0b00010
const STATUS_IMPORTANT = 4;// 0b00100
const STATUS_RESOLVED = 8;// 0b01000
const STATUS_SPAM = 16;// 0b10000
const STATUS_ARCHIVED = 32;// 0b100000
const STATUS_FLAGGED = 64;// 0b110000
const STATUS_REPLIED = 128;// 0b10000000
public static function tableName(): string
{
return '{{%message}}';
}
public function rules(): array
{
return [
// Message Status
['status', 'default', 'value' => self::STATUS_UNREAD],
/**
* Validate the order's status to ensure it does not contain any contradictory
* combinations before proceeding with the save operation. This method will add
* any validation errors to the model if invalid statuses are detected, preventing
* the order from being saved if the validation fails.
*/
['status', 'validateStatus'],
];
}
public function validateStatus($attribute, $params = []): void
{
$validFlags = self::STATUS_UNREAD | self::STATUS_READ | self::STATUS_IMPORTANT | self::STATUS_RESOLVED |
self::STATUS_SPAM | self::STATUS_ARCHIVED | self::STATUS_FLAGGED | self::STATUS_REPLIED;
// If any bit outside validFlags is set, invalid
if (($this->$attribute & ~$validFlags) !== 0)
{
$this->addError($attribute, 'Status contains invalid flags.');
return;
}
/**
* Unread and Read conflict.
*
$unreadAndRead = self::STATUS_UNREAD | self::STATUS_READ;
if (($this->status & $unreadAndRead) === ($unreadAndRead))
{
$this->addError($attribute, \Yii::t('app', 'Status cannot be both unread and read.'));
}//*/
// Important and Resolved conflict.
$importantAndResolved = self::STATUS_IMPORTANT | self::STATUS_RESOLVED;
if (($this->status & $importantAndResolved) === $importantAndResolved)
{
$this->addError($attribute, \Yii::t('app', 'Status cannot be both important and resolved.'));
}
// Important and Spam conflict.
if (($this->status & self::STATUS_IMPORTANT) && ($this->status & self::STATUS_SPAM))
{
$this->addError($attribute, \Yii::t('app', 'Status cannot be both important and spam.'));
}
// Resolved and Spam conflict.
if (($this->status & self::STATUS_RESOLVED) && ($this->status & self::STATUS_SPAM))
{
$this->addError($attribute, \Yii::t('app', 'Status cannot be both resolved and spam.'));
}
// Archived and Spam conflict.
if (($this->status & self::STATUS_ARCHIVED) && ($this->status & self::STATUS_SPAM))
{
$this->addError($attribute, \Yii::t('app', 'Status cannot be both archived and spam.'));
}
}
public function addError($attribute, $error = ''): void
{
// Example implementation, adapt as needed per your environment
echo "Validation error on {$attribute}: {$error}\n";
}
public function getStatusLabels(): array
{
return [
//self::STATUS_UNREAD => \Yii::t('app', 'Unread'),// Handled within.
self::STATUS_READ => \Yii::t('app', 'Read'),
self::STATUS_IMPORTANT => \Yii::t('app', 'Important'),
self::STATUS_RESOLVED => \Yii::t('app', 'Resolved'),
self::STATUS_SPAM => \Yii::t('app', 'Spam'),
self::STATUS_ARCHIVED => \Yii::t('app', 'Archived'),
self::STATUS_FLAGGED => \Yii::t('app', 'Flagged'),
self::STATUS_REPLIED => \Yii::t('app', 'Replied'),
];
}
public function getStatusLabel(): string
{
$labels = [];
foreach (self::getStatusLabels() as $bit => $label)
{
if ($this->hasStatus($bit))
{
$labels[] = $label;
}
}
return empty($labels) ? \Yii::t('app', 'Unknown') : implode(', ', $labels);
}
public function getStatusList(): string
{
$statuses = self::getStatusLabels();
if (array_key_exists($this->status, $statuses))
{
return $statuses[$this->status];
}
return \Yii::t('app', 'Unknown');
}
/**
* Types List
*/
public static function getTypeLabels(): array
{
return [
self::TYPE_CONTACT => \Yii::t('app', 'Contact'),
self::TYPE_INQUIRY => \Yii::t('app', 'Inquiry'),
self::TYPE_ORDER => \Yii::t('app', 'Order'),
self::TYPE_SUPPORT => \Yii::t('app', 'Assistance'),
];
}
public function getTypeList(): string
{
$types = self::getTypeLabels();
return $types[$this->type];
}
/**
* Get Status for Checkboxes
* @return array An array containing currently active statuses for the message.
*
* Returns array of active status flags for checkboxes.
* No exclusivity enforced here; validation step forbids invalid combos.
*/
public function getStatusForCheckboxes(): array
{
$statuses = [];
/**
* Unread and Read conflict.
*
if ($this->hasStatus(self::STATUS_UNREAD) && !$this->hasStatus(self::STATUS_READ))
{
$statuses[] = self::STATUS_UNREAD;
}
elseif (!$this->hasStatus(self::STATUS_UNREAD) && $this->hasStatus(self::STATUS_READ)
{
$statuses[] = self::STATUS_READ;
}//*/
// Important and Resolved conflict.
if ($this->hasStatus(self::STATUS_IMPORTANT) && !$this->hasStatus(self::STATUS_RESOLVED))
{
$statuses[] = self::STATUS_IMPORTANT;
}
elseif (!$this->hasStatus(self::STATUS_IMPORTANT) && $this->hasStatus(self::STATUS_RESOLVED))
{
$statuses[] = self::STATUS_RESOLVED;
}
// Only add Spam if it's not conflicting (important, resolved, archived)
// Spam conflicts are handled at validation, so just add if set
if ($this->hasStatus(self::STATUS_SPAM))
{
$statuses[] = self::STATUS_SPAM;
}
// Archived (not mutually exclusive with anything except spam, handled by validation)
if ($this->hasStatus(self::STATUS_ARCHIVED))
{
$statuses[] = self::STATUS_ARCHIVED;
}
// Flagged and Replied just add if set
if ($this->hasStatus(self::STATUS_FLAGGED))
{
$statuses[] = self::STATUS_FLAGGED;
}
if ($this->hasStatus(self::STATUS_REPLIED))
{
$statuses[] = self::STATUS_REPLIED;
}
return array_unique($statuses);
}
public function setStatusFromCheckboxes($checkboxes): void
{
$this->status = 0;
foreach ($checkboxes as $value)
{
$this->addStatus((int) $value);
}
}
/**
* Has Status
* @param int $flag
* @return bool
*
* Instead of calling hasStatus() twice in the if condition, you can directly
* check using a bitwise operation:
*
* $user = User::findOne($id);// Fetch the message with a specific ID.
* if (($user->status & (User::STATUS_ACTIVE | User::STATUS_LOCKED)) ===
* (User::STATUS_ACTIVE | User::STATUS_LOCKED))
* {
*
* echo "This product is inquire only.";
* }
*
* In this alternative approach:
*
* The expression User::STATUS_ACTIVE | User::STATUS_LOCKED
* combines both statuses (using the bitwise OR).
*
* The condition checks if both statuses are set within the status field of
* the message.
*/
public function hasStatus(int $flag): bool
{
return ($this->status & $flag) === $flag;
}
/**
* Add Status
* @param int $flag
*
* Set Statuses (make sure to save):
*
* $user->addStatus(User::STATUS_ACTIVE);
* $user->save();// Save changes to the database.
*/
public function addStatus(int $flag): void
{
$this->status |= $flag;
}
/**
* Remove Status
* @param int $flag
*
* Removing Statuses:
*
* $user->removeStatus(User::STATUS_ACTIVE);
*/
public function removeStatus(int $flag): void
{
$this->status &= ~$flag;
}
/**
* Getter User Statuses
* How to use:
*
* $user->isActive();
*/
public function isUnread(): bool
{
return $this->hasStatus(self::STATUS_UNREAD);
}
public function isRead(): bool
{
return $this->hasStatus(self::STATUS_READ);
}
public function isImportant(): bool
{
return $this->hasStatus(self::STATUS_IMPORTANT);
}
public function isResolved(): bool
{
return $this->hasStatus(self::STATUS_RESOLVED);
}
public function isSpam(): bool
{
return $this->hasStatus(self::STATUS_SPAM);
}
public function isArchived(): bool
{
return $this->hasStatus(self::STATUS_ARCHIVED);
}
public function isFlagged(): bool
{
return $this->hasStatus(self::STATUS_FLAGGED);
}
public function isReplied(): bool
{
return $this->hasStatus(self::STATUS_REPLIED);
}
/**
* Setters User Statuses
* How to use:
*
* $user->activateAccount();
*/
public function setUnread(): void
{
$this->addStatus(self::STATUS_UNREAD);
}
public function setRead(): void
{
$this->addStatus(self::STATUS_READ);
}
public function setImportant(): void
{
$this->addStatus(self::STATUS_IMPORTANT);
}
public function setResolved(): void
{
$this->addStatus(self::STATUS_RESOLVED);
}
public function setSpam(): void
{
$this->addStatus(self::STATUS_SPAM);
}
public function setArchived(): void
{
$this->addStatus(self::STATUS_ARCHIVED);
}
public function setFlagged(): void
{
$this->addStatus(self::STATUS_FLAGGED);
}
public function setReplied(): void
{
$this->addStatus(self::STATUS_REPLIED);
}
}
namespace app\controllers;
class MessageController extends BaseController
{
public function actionViewUpdate(int $id): Response|string
{
$model = $this->findModel($id);
$replyForm = new ReplyForm($model->id);
$request = \Yii::$app->request;
if (($request->isPost) && ($replyForm->load($request->post())))
{
// Checks Message $model if $model->status has STATUS_REPLIED and if $model->replied been set.
if (!$model->hasStatus(Message::STATUS_REPLIED) && ValueHelper::isSetAndNull($model->replied))
{
// Handle Replyform $replyForm->checkboxes as statuses bits (Message $model->status)
$selectedStatus = 0;
foreach ($replyForm->checkboxes as $status)
{
$selectedStatus |= (int) $status;
}
// Compare the Replyform $replyForm->status with the current Message $model->status
$getStatus = $selectedStatus !== $model->status;
// Determine if Replyform $replyForm->reply has been provided via the Replyform model
$getReply = ValueHelper::isSetNotNull($replyForm->reply);
if ($getReply && $getStatus)
{
$replyForm->scenario = 'both';
}
elseif ($getReply)
{
$replyForm->scenario = 'replyOnly';
}
elseif ($getStatus)
{
$replyForm->scenario = 'statusOnly';
}
}
else
{
$replyForm->scenario = 'statusOnly';
}
// Use the selected scenario to validate ReplyForm $replyForm and run $replyForm->process() function
if ($replyForm->validate())
{
// Update the Message model's status based on the checkboxes from the ReplyForm. This ensures
// the latest status is used for validation, allowing conflicts to be caught e.g., conflicting
// statuses like important and resolved) during validation.
$model->setStatusFromCheckboxes($replyForm->checkboxes);
// Message $model custom status validation check. If error occurs, flash errors
if (!$replyForm->validateAssociatedMessage($model))
{
$this->setErrorsFlash($model);
}
else
{
// if (!$model->hasStatus(Message::STATUS_REPLIED)) {
if ($replyForm->process())
{
$this->setScenarioSuccessFlash($replyForm->scenario, $model);
return $this->redirect(['index']);
}
else
{
$this->setErrorsFlash($replyForm);
}
//}// Else statement with error if trying to save Message $model->status as STATUS_REPLIED.
}
}
// Replyform $replyForm validation failed. Check errors.
else
{
$this->setErrorsFlash($replyForm);
}
}
// First time viewing Message, mark Message $model->status to read and remove unread.
if (($request->isGet) && ($model->hasStatus(Message::STATUS_UNREAD)))
{
try
{
$model->removeStatus(Message::STATUS_UNREAD);
$model->addStatus(Message::STATUS_READ);
if (!$model->save(false, ['status']))
{
throw new YiiDbException("Failed to save message status to the database.");
}
}
catch (Throwable $e)
{
\Yii::$app->session->setFlash('error', 'Could not mark status as read.');
// Use the ExceptionLogger to handle and log the exception.
ExceptionLogger::log($e, 'reply_form_error_');
}
}
// Fetching of replies for the message is only needed for Order and internal Inquries on product.
$replies = $model->getReplies()->all();
// Setup Formatter Helper for view
$formatterHelper = FormatterHelper::create($this->_formatter);
return $this->render('viewUpdate', [
'model' => $model,
'replyForm' => $replyForm,
'replies' => $replies,
'formatterHelper' => $formatterHelper,
]);
}
private function setScenarioSuccessFlash(string $scenario, $model): void
{
switch ($scenario)
{
case 'statusOnly' :
$msg = \Yii::t(
'app',
'The status for message #{id} has been updated.',
['id' => $model->id]
);
break;
case 'replyOnly' :
case 'both' :
default :
$msg = \Yii::t(
'app',
'Your reply to {to} has been sent.',
['to' => $model->email]
);
break;
}
\Yii::$app->session->setFlash('success', $msg);
}
private function setErrorsFlash($model): void
{
$modelErrors = $model->getErrors();
if (!empty($modelErrors))
{
$errorMessages = [];
foreach ($modelErrors as $errors)
{
$errorMessages = array_merge($errorMessages, $errors);
}
// Strip tags from each error message and prepare the final string.
$strippedErrorMessages = implode(' ', array_map('strip_tags', $errorMessages));
\Yii::$app->session->setFlash('error', \Yii::t('app', 'Error: {errors}', [
'errors' => $strippedErrorMessages,
]));
}
/**
* Generic error response.
*
else
{
\Yii::$app->session->setFlash('error', ErrorMessageHelper::genericError());
}//*/
}
protected function findModel(int $id): Message
{
if ($this->_isGuest)
{
return $this->goHome();
}
$model = Message::findOne(['id' => $id]);
if ($model !== null)
{
return $model;
}
//throw new YiiWebNotFoundHttpException(ErrorMessageHelper::badRequest());
$msg = \Yii::t('app', 'No Message found with `{value}`', ['value' => $id]);
throw new YiiWebNotFoundHttpException($msg);
}
}
declare(strict_types=1);
namespace app\models\forms;
class ReplyForm extends Model
{
/**
* Note: Public typed properties must be initialized with default
* values (e.g. empty string) to avoid "must not be accessed before
* initialization" PHP errors.
**
* Bootstrap 5 does not allow multi select. Changed from `$status`
* to `checkboxes`.
*/
public array $checkboxes = [];
public string $reply = '';
// @var app\models\Message
private ?Message $_message = null;
// @var ParamHelper to class property.
private string $_appName;
private string $_emailSupport;
//public function __construct(Contact $contact, $config = [])// Dependency injection.
public function __construct(int $id, array $config = [])
{
/**
* Dependency injection Example
* Passing Contact model into a class through its constructor.
*
* Note: At this time, we recatch the Message via find as a extra
* security messure.
*
$this->_message = $message;//*/
// Assign user object class propert to a local variable
$this->_message = Message::findOne($id);
if (!$this->_message)
{
throw new YiiBaseInvalidArgumentException('Unable to find Message.');
}
// @var ParamHelper to class property
$this->_appName = AppHelper::name();
$this->_emailSupport = ParamHelper::get('email.support');
/**
* Call to parent constructor
* The parent constructor should be called last to ensure proper object
* initialization and handling of configuration settings.
*/
parent::__construct($config);
}
public function rules(): array
{
return [
// No fields are mandatory due to defaults; validate if they are set.
[['checkboxes', 'reply'], 'safe'],
[['reply'], 'required', 'on' => 'replyOnly'],// Making reply required only in the replyOnly scenario.
/**
* Example of syntax to require attributes per scenario, if needed:
*/
//[['status'], 'required', 'on' => 'statusOnly'],
//[['reply'], 'required', 'on' => 'replyOnly'],
//[['status', 'reply'], 'required', 'on' => 'both'],
];
}
/**
* Validates the associated message model
* @param Message $messageModel
* @return bool
*/
public function validateAssociatedMessage(Message $messageModel): bool
{
// Call the validateStatus method from the Message model.
$messageModel->validateStatus('status', []);
// Returns true if there are no errors.
return !$messageModel->hasErrors();
}
public function scenarios()
{
$scenarios = parent::scenarios();
$scenarios['replyOnly'] = ['reply'];// Only sends a reply.
$scenarios['statusOnly'] = ['checkboxes'];// Using checkboxes to only update status.
$scenarios['both'] = ['status', 'reply'];// Updates both status and reply.
return $scenarios;
}
public function attributeLabels(): array
{
return ['replied' => \Yii::t('app', 'Reply')];
}
public function process(): bool
{
$transaction = \Yii::$app->db->beginTransaction();
try
{
$scenario = $this->getScenario();
$updatedFields = [];// Message model attubutes.
// If Message Model status is not set to 'replied', and form Model 'reply' is not empty.
if (($this->_message->status !== Message::STATUS_REPLIED) && (!empty($this->reply)))
{
if (in_array($scenario, ['both']))
{
$this->_message->setStatusFromCheckboxes($this->checkboxes);
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();// Set it to the current Unix timestamp.
//$this->_message->repliedTime = date('Y-m-d H:i:s');// If defined as a timestamp '$this->timestamp()'.
$updatedFields = ['status', 'replied', 'repliedTime'];
}
if (in_array($scenario, ['replyOnly']))
{
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();
//$this->_message->repliedTime = date('Y-m-d H:i:s');
$updatedFields = ['replied', 'repliedTime'];
}
if (in_array($scenario, ['statusOnly']))
{
$this->_message->setStatusFromCheckboxes($this->checkboxes);
$this->_message->addStatus(Message::STATUS_READ);
$updatedFields = ['status'];
}
}
else
{
$this->_message->setStatusFromCheckboxes($this->checkboxes);
$this->_message->addStatus(Message::STATUS_READ);
$updatedFields = ['status'];
}
// Save Contact model depending on Scenario. $updatedFields['data'];
if ($this->_message->save(false, $updatedFields))
{
if ((in_array($scenario, ['replyOnly', 'both'])) && (!empty($this->reply)))
{
if (!$this->sendEmail())
{
throw new YiiBaseException('Failed to send email.');
}
}
// 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, 'reply_form_error_');
}
return false;
}
protected function sendEmail(): bool
{
/**
* Make Safe for User
* Strip HTML and PHP tags from a string @url https://www.php.net/manual/en/function.strip-tags.php
*/
$stripReply = strip_tags($this->reply, '<p><a><i><b><u>');
$sanitizedReply = preg_replace('/\bhttps?:\/\/\S+/i', '', $stripReply);// No links.
try
{
$appName = AppHelper::name();
$isSent = \Yii::$app->mailer->compose(
['html' => 'emailReply-html', 'text' => 'emailReply-text'],
[
'emailAppName' => $this->_appName,
'emailMessage' => $this->_message,
'emailReply' => $sanitizedReply,
],
)
->setFrom($this->_emailSupport)
->setTo($this->_message->email)
->setSubject('Re: ' . $this->_message->subject)//->setSubject(\Yii::t('appEmail', 'Welcome to...'))
->setTextBody($sanitizedReply)
->send();
if (!$isSent)
{
throw new YiiBaseException("The email could not be sent to {$this->_message->email}.");
}
return true;
}
catch (Throwable $e)
{
// Use the ExceptionLogger to handle and log the exception.
ExceptionLogger::log($e, 'reply_form_sendmail_error_');
}
return false;
}
}
<?php
namespace app\models;
use yii\db\ActiveRecord;
use app\components\traits\BitmaskTrait;
class Message extends ActiveRecord
{
use BitmaskTrait;
// Status flags - powers of two
public const STATUS_UNREAD = 1; // 0b00000001
public const STATUS_READ = 2; // 0b00000010
public const STATUS_IMPORTANT = 4; // 0b00000100
public const STATUS_RESOLVED = 8; // 0b00001000
public const STATUS_SPAM = 16; // 0b00010000
public const STATUS_ARCHIVED = 32; // 0b00100000
public const STATUS_FLAGGED = 64; // 0b01000000
public const STATUS_REPLIED = 128; // 0b10000000
/**
* Virtual attribute; used to interact with form checkboxes.
* @var int[]|null
*/
private ?array $_statusArray = null;
public static function tableName(): string
{
return '{{%message}}';
}
public function rules(): array
{
return [
['status', 'default', 'value' => self::STATUS_UNREAD],
['status', 'integer'],
['statusArray', 'safe'], // safe for mass assignment & form binding
['statusArray', 'validateStatusArray'],
];
}
/**
* Custom validation for statusArray input from checkboxes.
*
* @param string $attribute
* @param array $params
*/
public function validateStatusArray($attribute, $params = []): void
{
$values = $this->$attribute;
if (!is_array($values)) {
$this->addError($attribute, 'Invalid status selection.');
return;
}
$bitmask = $this->arrayToBitmask($values);
$validFlags = array_sum(self::getStatusFlags());
if (($bitmask & ~$validFlags) !== 0) {
$this->addError($attribute, 'Status contains invalid flags.');
return;
}
// Conflicting status checks:
// Cannot be both UNREAD and READ
if (($bitmask & self::STATUS_UNREAD) && ($bitmask & self::STATUS_READ)) {
$this->addError($attribute, 'Status cannot be both unread and read.');
}
// Cannot be both IMPORTANT and RESOLVED
if (($bitmask & self::STATUS_IMPORTANT) && ($bitmask & self::STATUS_RESOLVED)) {
$this->addError($attribute, 'Status cannot be both important and resolved.');
}
// IMPORTANT conflicts with SPAM
if (($bitmask & self::STATUS_IMPORTANT) && ($bitmask & self::STATUS_SPAM)) {
$this->addError($attribute, 'Status cannot be both important and spam.');
}
// RESOLVED conflicts with SPAM
if (($bitmask & self::STATUS_RESOLVED) && ($bitmask & self::STATUS_SPAM)) {
$this->addError($attribute, 'Status cannot be both resolved and spam.');
}
// ARCHIVED conflicts with SPAM
if (($bitmask & self::STATUS_ARCHIVED) && ($bitmask & self::STATUS_SPAM)) {
$this->addError($attribute, 'Status cannot be both archived and spam.');
}
}
/**
* Get all valid status flags.
* @return int[]
*/
public static function getStatusFlags(): array
{
return [
self::STATUS_UNREAD,
self::STATUS_READ,
self::STATUS_IMPORTANT,
self::STATUS_RESOLVED,
self::STATUS_SPAM,
self::STATUS_ARCHIVED,
self::STATUS_FLAGGED,
self::STATUS_REPLIED,
];
}
/**
* Get status labels for UI elements.
* @return array<int, string>
*/
public static function getStatusLabels(): array
{
return [
self::STATUS_UNREAD => \Yii::t('app', 'Unread'),
self::STATUS_READ => \Yii::t('app', 'Read'),
self::STATUS_IMPORTANT => \Yii::t('app', 'Important'),
self::STATUS_RESOLVED => \Yii::t('app', 'Resolved'),
self::STATUS_SPAM => \Yii::t('app', 'Spam'),
self::STATUS_ARCHIVED => \Yii::t('app', 'Archived'),
self::STATUS_FLAGGED => \Yii::t('app', 'Flagged'),
self::STATUS_REPLIED => \Yii::t('app', 'Replied'),
];
}
/**
* Defensive getter for status with default.
* @return int
*/
public function getStatus(): int
{
return $this->status ?? self::STATUS_UNREAD;
}
/**
* Return status as array of active flags for checkbox inputs.
* @return int[]
*/
public function getStatusForCheckboxes(): array
{
return $this->bitmaskToArray($this->getStatus(), self::getStatusFlags());
}
/**
* Virtual status array getter - used for form checkbox binding.
* @return int[]
*/
public function getStatusArray(): array
{
if ($this->_statusArray === null) {
$this->_statusArray = $this->getStatusForCheckboxes();
}
return $this->_statusArray;
}
/**
* Virtual status array setter - to be called by forms.
* @param int[] $values
*/
public function setStatusArray(array $values): void
{
$this->_statusArray = $values;
$this->status = $this->arrayToBitmask($values);
}
/**
* Set the internal "status" bitmask from a list of flags.
* Useful on form submit.
* @param int[] $checkboxes
*/
public function setStatusFromCheckboxes(array $checkboxes): void
{
$this->status = $this->arrayToBitmask($checkboxes);
$this->_statusArray = $checkboxes;
}
/*
* Check if specific status flag is set.
* @param int $flag
* @return bool
*/
public function hasStatus(int $flag): bool
{
return ($this->getStatus() & $flag) === $flag;
}
/*
* Add a status flag.
* @param int $flag
*/
public function addStatus(int $flag): void
{
$this->status = ($this->getStatus() | $flag);
$this->_statusArray = null; // reset cache
}
/*
* Remove a status flag.
* @param int $flag
*/
public function removeStatus(int $flag): void
{
$this->status = ($this->getStatus() & (~$flag));
$this->_statusArray = null; // reset cache
}
// Convenience boolean getters
public function isUnread(): bool { return $this->hasStatus(self::STATUS_UNREAD); }
public function isRead(): bool { return $this->hasStatus(self::STATUS_READ); }
public function isImportant(): bool { return $this->hasStatus(self::STATUS_IMPORTANT); }
public function isResolved(): bool { return $this->hasStatus(self::STATUS_RESOLVED); }
public function isSpam(): bool { return $this->hasStatus(self::STATUS_SPAM); }
public function isArchived(): bool { return $this->hasStatus(self::STATUS_ARCHIVED); }
public function isFlagged(): bool { return $this->hasStatus(self::STATUS_FLAGGED); }
public function isReplied(): bool { return $this->hasStatus(self::STATUS_REPLIED); }
// Convenience setters
public function setUnread(): void { $this->addStatus(self::STATUS_UNREAD); }
public function setRead(): void { $this->addStatus(self::STATUS_READ); }
public function setImportant(): void { $this->addStatus(self::STATUS_IMPORTANT); }
public function setResolved(): void { $this->addStatus(self::STATUS_RESOLVED); }
public function setSpam(): void { $this->addStatus(self::STATUS_SPAM); }
public function setArchived(): void { $this->addStatus(self::STATUS_ARCHIVED); }
public function setFlagged(): void { $this->addStatus(self::STATUS_FLAGGED); }
public function setReplied(): void { $this->addStatus(self::STATUS_REPLIED); }
/**
* Get concatenated statuses as readable string for display.
* @return string
*/
public function getStatusLabel(): string
{
$labels = [];
foreach (self::getStatusLabels() as $flag => $label) {
if ($this->hasStatus($flag)) {
$labels[] = $label;
}
}
return !empty($labels) ? implode(', ', $labels) : \Yii::t('app', 'Unknown');
}
/**
* Validation for the raw status integer attribute (before save).
* Validates possible invalid/unknown bits and conflicting combinations.
*
* @param string $attribute
* @param array $params
*/
public function validateStatus($attribute, $params = []): void
{
$statusVal = $this->$attribute;
$validFlags = array_sum(self::getStatusFlags());
if (($statusVal & ~$validFlags) !== 0) {
$this->addError($attribute, 'Status contains invalid flags.');
return;
}
// Check conflicts same as validateStatusArray
if (($statusVal & self::STATUS_UNREAD) && ($statusVal & self::STATUS_READ)) {
$this->addError($attribute, \Yii::t('app', 'Status cannot be both unread and read.'));
}
if (($statusVal & self::STATUS_IMPORTANT) && ($statusVal & self::STATUS_RESOLVED)) {
$this->addError($attribute, \Yii::t('app', 'Status cannot be both important and resolved.'));
}
if (($statusVal & self::STATUS_IMPORTANT) && ($statusVal & self::STATUS_SPAM)) {
$this->addError($attribute, \Yii::t('app', 'Status cannot be both important and spam.'));
}
if (($statusVal & self::STATUS_RESOLVED) && ($statusVal & self::STATUS_SPAM)) {
$this->addError($attribute, \Yii::t('app', 'Status cannot be both resolved and spam.'));
}
if (($statusVal & self::STATUS_ARCHIVED) && ($statusVal & self::STATUS_SPAM)) {
$this->addError($attribute, \Yii::t('app', 'Status cannot be both archived and spam.'));
}
}
}
<?php
declare(strict_types=1);
namespace app\models\forms;
use Yii;
use yii\base\Model;
use app\models\Message;
use yii\base\InvalidArgumentException;
use Throwable;
class ReplyForm extends Model
{
public array $checkboxes = [];
public string $reply = '';
private Message $_message;
private string $_appName;
private string $_emailSupport;
/**
* @param int $id
* @param array $config
* @throws InvalidArgumentException
*/
public function __construct(int $id, array $config = [])
{
$this->_message = Message::findOne($id);
if (!$this->_message) {
throw new InvalidArgumentException('Unable to find Message.');
}
$this->_appName = \Yii::$app->name;
$this->_emailSupport = Yii::$app->params['email.support'] ?? 'support@example.com';
parent::__construct($config);
}
public function rules(): array
{
return [
[['checkboxes', 'reply'], 'safe'],
[['reply'], 'required', 'on' => 'replyOnly'],
[['checkboxes'], 'required', 'on' => 'statusOnly'],
[['reply', 'checkboxes'], 'required', 'on' => 'both'],
];
}
/**
* Assigns statuses from checkboxes to the message model.
* @return void
*/
public function applyStatusesToMessage(): void
{
$this->_message->setStatusFromCheckboxes($this->checkboxes);
}
/**
* Validates the associated message model.
* @return bool
*/
public function validateAssociatedMessage(): bool
{
$this->_message->validateStatus('status');
return !$this->_message->hasErrors();
}
public function attributeLabels(): array
{
return ['reply' => \Yii::t('app', 'Reply')];
}
/**
* Saves the reply and updates message status accordingly.
* @return bool
* @throws \Throwable
*/
public function process(): bool
{
$transaction = Yii::$app->db->beginTransaction();
try {
$scenario = $this->getScenario();
// Update status & reply fields conditionally
if ($scenario === 'both') {
$this->applyStatusesToMessage();
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();
$fields = ['status', 'replied', 'repliedTime'];
} elseif ($scenario === 'replyOnly') {
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();
$fields = ['replied', 'repliedTime'];
} elseif ($scenario === 'statusOnly') {
$this->applyStatusesToMessage();
$this->_message->addStatus(Message::STATUS_READ);
$fields = ['status'];
} else {
// Default fallback
$fields = [];
}
if ($this->_message->save(false, $fields)) {
if (in_array($scenario, ['replyOnly', 'both'], true) && $this->reply !== '') {
if (!$this->sendEmail()) {
throw new \Exception('Failed to send email.');
}
}
$transaction->commit();
return true;
}
} catch (Throwable $e) {
$transaction->rollBack();
\Yii::error("ReplyForm process failed: ".$e->getMessage());
}
return false;
}
/**
* Sends email reply.
* @return bool
*/
protected function sendEmail(): bool
{
try {
$sanitizedReply = strip_tags($this->reply, '<p><a><i><b><u>');
$sanitizedReply = preg_replace('/\bhttps?:\/\/\S+/i', '', $sanitizedReply);
$isSent = \Yii::$app->mailer->compose(
['html' => 'emailReply-html', 'text' => 'emailReply-text'],
[
'emailAppName' => $this->_appName,
'emailMessage' => $this->_message,
'emailReply' => $sanitizedReply,
]
)
->setFrom($this->_emailSupport)
->setTo($this->_message->email)
->setSubject('Re: ' . $this->_message->subject)
->setTextBody($sanitizedReply)
->send();
return $isSent;
} catch (Throwable $e) {
\Yii::error("Failed to send reply email: " . $e->getMessage());
return false;
}
}
/**
* Expose the message model if needed externally.
* @return Message
*/
public function getMessageModel(): Message
{
return $this->_message;
}
}
Notes
The Message model now uses BitmaskTrait exactly like your Product model, with virtual array attributes (getStatusArray/setStatusArray) to bind checkboxes in forms.
Validation for conflicting flags is centralized and consistent for both raw integer and array inputs.
The form class (ReplyForm) respects scenarios and requires checkboxes or reply or both depending on scenario — this likely fixes your "no action" on submit issue because the scenario and validation are properly configured and matched.
The setStatusFromCheckboxes() method is used both in Message and ReplyForm to handle setting the bitmask from the checkbox array.
Sample usage for your checkboxes in view (adjusted to match the statusArray naming):
Quick summary for fixing your typical scenario issues:
Ensure your form sets the scenario appropriately before validation.
The scenario must include the attributes being validated (checkboxes for status updates).
The rules() in ReplyForm enforce requiredness correctly per scenario.
Validation methods are called on the model linked to form attributes (the Message model's validateStatus is called manually).
If you want, I can also assist with refactoring the controller or view files to align with this. But the above should provide a clean complete solution that works like your Product bitmask logic but for Message statuses, and has a proper scenario-based ReplyForm to allow form submission to succeed or properly fail with errors.
Let me know if you want me to provide the MessageController or adjustments on views!
if your model's status can be modified programmatically or by other means (e.g., via APIs, CLI, direct attribute assignment, or batch processes)
validateStatus('status')
In your controller's action or wherever you save a Message, you can do this:
php
$message->validateStatus('status');
if ($message->hasErrors('status')) {
// handle errors
}
Or you can add a rule inside rules():
php
[['status'], 'validateStatus'],
So it automatically runs during model validation like the others.
Recommendation
Add it to the rules for a clean and automatic approach.
php
public function rules(): array
{
return [
['status', 'default', 'value' => self::STATUS_UNREAD],
['status', 'integer'],
['status', 'validateStatus'], // <-- Add this
['statusArray', 'safe'],
['statusArray', 'validateStatusArray'],
];
}
Then Yii will automatically run validateStatus() when you call $model->validate().
Summary
Method
Purpose
When It Runs
Why Needed
validateStatusArray
Validate virtual array attribute from form checkboxes
When validating form attribute statusArray
Validate user input before bitmask conversion
validateStatus
Validate raw integer bitmask field status
During model validation (e.g. before saving)
Validate actual stored bitmask is valid and consistent
TL;DR:
You should add the validateStatus method as a validation rule on status so that the model automatically validates its integer bitmask, and keep validateStatusArray for form input validation.
If you want, I can help update your model rules and explain how to call validation properly!
If their is nothing wrong with how i do scenario i would prefer to keep my process() function as is
public function process(): bool
{
$transaction = \Yii::$app->db->beginTransaction();
try {
$scenario = $this->getScenario();
$updatedFields = [];
// If message is NOT already replied AND reply text is present
if (($this->_message->status !== Message::STATUS_REPLIED) && (!empty($this->reply))) {
if ($scenario === 'both') {
$this->_message->setStatusFromCheckboxes($this->checkboxes);
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();
$updatedFields = ['status', 'replied', 'repliedTime'];
} elseif ($scenario === 'replyOnly') {
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();
$updatedFields = ['replied', 'repliedTime'];
} elseif ($scenario === 'statusOnly') {
$this->_message->setStatusFromCheckboxes($this->checkboxes);
$this->_message->addStatus(Message::STATUS_READ);
$updatedFields = ['status'];
}
} else {
// fallback - no reply or already replied; just update status
$this->_message->setStatusFromCheckboxes($this->checkboxes);
$this->_message->addStatus(Message::STATUS_READ);
$updatedFields = ['status'];
}
if ($this->_message->save(false, $updatedFields)) {
if (in_array($scenario, ['replyOnly', 'both'], true) && !empty($this->reply)) {
if (!$this->sendEmail()) {
throw new \yii\base\Exception('Failed to send email.');
}
}
$transaction->commit();
return true;
}
} catch (\Throwable $e) {
$transaction->rollBack();
\Yii::error('ReplyForm process failed: ' . $e->getMessage());
}
return false;
}
Summary
Your logic is properly handling the cases you want and is valid code.
The main difference is the extra condition on status and reply presence, which adds logic around when to update.
Final advice
If your process works and matches your requirements, keep your current code.
Just make sure scenarios are set correctly before calling process and validation.
Optionally add the ['status', 'validateStatus'] rule on the Message model rules for automatic validation on the status attribute.
Log or handle exceptions carefully (you already do with ExceptionLogger).
If you want, I can also help review your controller form loading/scenario setting for completeness.
Let me know! But overall your current method is fine and you don’t have to change it if preferred.
Certainly! Below is a refactored complete Message model using your Product bitmask style and trait approach, and a cleaned-up ReplyForm with scenario handling fixed to work properly. I’ve also provided a BitmaskTrait that you can re-use.
BitmaskTrait (place in app\components\traits\BitmaskTrait.php)
<?php
namespace app\components\traits;
trait BitmaskTrait
{
/**
* Converts a bitmask int into an array of active flags.
* @param int $bitmask
* @param int[] $allFlags
* @return int[]
*/
public function bitmaskToArray(int $bitmask, array $allFlags): array
{
$flags = [];
foreach ($allFlags as $flag) {
if (($bitmask & $flag) === $flag) {
$flags[] = $flag;
}
}
return $flags;
}
/**
* Converts an array of flags into a single bitmask int.
* @param int[] $flags
* @return int
*/
public function arrayToBitmask(array $flags): int
{
$bitmask = 0;
foreach ($flags as $flag) {
$bitmask |= (int)$flag;
}
return $bitmask;
}
}
Refactored Message Model (app\models\Message.php)
<?php
namespace app\models;
use yii\db\ActiveRecord;
use app\components\traits\BitmaskTrait;
class Message extends ActiveRecord
{
use BitmaskTrait;
// Status flags - powers of two
public const STATUS_UNREAD = 1; // 0b00000001
public const STATUS_READ = 2; // 0b00000010
public const STATUS_IMPORTANT = 4; // 0b00000100
public const STATUS_RESOLVED = 8; // 0b00001000
public const STATUS_SPAM = 16; // 0b00010000
public const STATUS_ARCHIVED = 32; // 0b00100000
public const STATUS_FLAGGED = 64; // 0b01000000
public const STATUS_REPLIED = 128; // 0b10000000
/**
* Virtual attribute; used to interact with form checkboxes.
* @var int[]|null
*/
private ?array $_statusArray = null;
public static function tableName(): string
{
return '{{%message}}';
}
public function rules(): array
{
return [
['status', 'default', 'value' => self::STATUS_UNREAD],
['status', 'integer'],
['statusArray', 'safe'], // safe for mass assignment & form binding
['statusArray', 'validateStatusArray'],
];
}
/**
* Custom validation for statusArray input from checkboxes.
*
* @param string $attribute
* @param array $params
*/
public function validateStatusArray($attribute, $params = []): void
{
$values = $this->$attribute;
if (!is_array($values)) {
$this->addError($attribute, 'Invalid status selection.');
return;
}
$bitmask = $this->arrayToBitmask($values);
$validFlags = array_sum(self::getStatusFlags());
if (($bitmask & ~$validFlags) !== 0) {
$this->addError($attribute, 'Status contains invalid flags.');
return;
}
// Conflicting status checks:
// Cannot be both UNREAD and READ
if (($bitmask & self::STATUS_UNREAD) && ($bitmask & self::STATUS_READ)) {
$this->addError($attribute, 'Status cannot be both unread and read.');
}
// Cannot be both IMPORTANT and RESOLVED
if (($bitmask & self::STATUS_IMPORTANT) && ($bitmask & self::STATUS_RESOLVED)) {
$this->addError($attribute, 'Status cannot be both important and resolved.');
}
// IMPORTANT conflicts with SPAM
if (($bitmask & self::STATUS_IMPORTANT) && ($bitmask & self::STATUS_SPAM)) {
$this->addError($attribute, 'Status cannot be both important and spam.');
}
// RESOLVED conflicts with SPAM
if (($bitmask & self::STATUS_RESOLVED) && ($bitmask & self::STATUS_SPAM)) {
$this->addError($attribute, 'Status cannot be both resolved and spam.');
}
// ARCHIVED conflicts with SPAM
if (($bitmask & self::STATUS_ARCHIVED) && ($bitmask & self::STATUS_SPAM)) {
$this->addError($attribute, 'Status cannot be both archived and spam.');
}
}
/**
* Get all valid status flags.
* @return int[]
*/
public static function getStatusFlags(): array
{
return [
self::STATUS_UNREAD,
self::STATUS_READ,
self::STATUS_IMPORTANT,
self::STATUS_RESOLVED,
self::STATUS_SPAM,
self::STATUS_ARCHIVED,
self::STATUS_FLAGGED,
self::STATUS_REPLIED,
];
}
/**
* Get status labels for UI elements.
* @return array<int, string>
*/
public static function getStatusLabels(): array
{
return [
self::STATUS_UNREAD => \Yii::t('app', 'Unread'),
self::STATUS_READ => \Yii::t('app', 'Read'),
self::STATUS_IMPORTANT => \Yii::t('app', 'Important'),
self::STATUS_RESOLVED => \Yii::t('app', 'Resolved'),
self::STATUS_SPAM => \Yii::t('app', 'Spam'),
self::STATUS_ARCHIVED => \Yii::t('app', 'Archived'),
self::STATUS_FLAGGED => \Yii::t('app', 'Flagged'),
self::STATUS_REPLIED => \Yii::t('app', 'Replied'),
];
}
/**
* Defensive getter for status with default.
* @return int
*/
public function getStatus(): int
{
return $this->status ?? self::STATUS_UNREAD;
}
/**
* Return status as array of active flags for checkbox inputs.
* @return int[]
*/
public function getStatusForCheckboxes(): array
{
return $this->bitmaskToArray($this->getStatus(), self::getStatusFlags());
}
/**
* Virtual status array getter - used for form checkbox binding.
* @return int[]
*/
public function getStatusArray(): array
{
if ($this->_statusArray === null) {
$this->_statusArray = $this->getStatusForCheckboxes();
}
return $this->_statusArray;
}
/**
* Virtual status array setter - to be called by forms.
* @param int[] $values
*/
public function setStatusArray(array $values): void
{
$this->_statusArray = $values;
$this->status = $this->arrayToBitmask($values);
}
/**
* Set the internal "status" bitmask from a list of flags.
* Useful on form submit.
* @param int[] $checkboxes
*/
public function setStatusFromCheckboxes(array $checkboxes): void
{
$this->status = $this->arrayToBitmask($checkboxes);
$this->_statusArray = $checkboxes;
}
/*
* Check if specific status flag is set.
* @param int $flag
* @return bool
*/
public function hasStatus(int $flag): bool
{
return ($this->getStatus() & $flag) === $flag;
}
/*
* Add a status flag.
* @param int $flag
*/
public function addStatus(int $flag): void
{
$this->status = ($this->getStatus() | $flag);
$this->_statusArray = null; // reset cache
}
/*
* Remove a status flag.
* @param int $flag
*/
public function removeStatus(int $flag): void
{
$this->status = ($this->getStatus() & (~$flag));
$this->_statusArray = null; // reset cache
}
// Convenience boolean getters
public function isUnread(): bool { return $this->hasStatus(self::STATUS_UNREAD); }
public function isRead(): bool { return $this->hasStatus(self::STATUS_READ); }
public function isImportant(): bool { return $this->hasStatus(self::STATUS_IMPORTANT); }
public function isResolved(): bool { return $this->hasStatus(self::STATUS_RESOLVED); }
public function isSpam(): bool { return $this->hasStatus(self::STATUS_SPAM); }
public function isArchived(): bool { return $this->hasStatus(self::STATUS_ARCHIVED); }
public function isFlagged(): bool { return $this->hasStatus(self::STATUS_FLAGGED); }
public function isReplied(): bool { return $this->hasStatus(self::STATUS_REPLIED); }
// Convenience setters
public function setUnread(): void { $this->addStatus(self::STATUS_UNREAD); }
public function setRead(): void { $this->addStatus(self::STATUS_READ); }
public function setImportant(): void { $this->addStatus(self::STATUS_IMPORTANT); }
public function setResolved(): void { $this->addStatus(self::STATUS_RESOLVED); }
public function setSpam(): void { $this->addStatus(self::STATUS_SPAM); }
public function setArchived(): void { $this->addStatus(self::STATUS_ARCHIVED); }
public function setFlagged(): void { $this->addStatus(self::STATUS_FLAGGED); }
public function setReplied(): void { $this->addStatus(self::STATUS_REPLIED); }
/**
* Get concatenated statuses as readable string for display.
* @return string
*/
public function getStatusLabel(): string
{
$labels = [];
foreach (self::getStatusLabels() as $flag => $label) {
if ($this->hasStatus($flag)) {
$labels[] = $label;
}
}
return !empty($labels) ? implode(', ', $labels) : \Yii::t('app', 'Unknown');
}
/**
* Validation for the raw status integer attribute (before save).
* Validates possible invalid/unknown bits and conflicting combinations.
*
* @param string $attribute
* @param array $params
*/
public function validateStatus($attribute, $params = []): void
{
$statusVal = $this->$attribute;
$validFlags = array_sum(self::getStatusFlags());
if (($statusVal & ~$validFlags) !== 0) {
$this->addError($attribute, 'Status contains invalid flags.');
return;
}
// Check conflicts same as validateStatusArray
if (($statusVal & self::STATUS_UNREAD) && ($statusVal & self::STATUS_READ)) {
$this->addError($attribute, \Yii::t('app', 'Status cannot be both unread and read.'));
}
if (($statusVal & self::STATUS_IMPORTANT) && ($statusVal & self::STATUS_RESOLVED)) {
$this->addError($attribute, \Yii::t('app', 'Status cannot be both important and resolved.'));
}
if (($statusVal & self::STATUS_IMPORTANT) && ($statusVal & self::STATUS_SPAM)) {
$this->addError($attribute, \Yii::t('app', 'Status cannot be both important and spam.'));
}
if (($statusVal & self::STATUS_RESOLVED) && ($statusVal & self::STATUS_SPAM)) {
$this->addError($attribute, \Yii::t('app', 'Status cannot be both resolved and spam.'));
}
if (($statusVal & self::STATUS_ARCHIVED) && ($statusVal & self::STATUS_SPAM)) {
$this->addError($attribute, \Yii::t('app', 'Status cannot be both archived and spam.'));
}
}
}
Refactored ReplyForm (app\models\forms\ReplyForm.php)
<?php
declare(strict_types=1);
namespace app\models\forms;
use Yii;
use yii\base\Model;
use app\models\Message;
use yii\base\InvalidArgumentException;
use Throwable;
class ReplyForm extends Model
{
public array $checkboxes = [];
public string $reply = '';
private Message $_message;
private string $_appName;
private string $_emailSupport;
/**
* @param int $id
* @param array $config
* @throws InvalidArgumentException
*/
public function __construct(int $id, array $config = [])
{
$this->_message = Message::findOne($id);
if (!$this->_message) {
throw new InvalidArgumentException('Unable to find Message.');
}
$this->_appName = \Yii::$app->name;
$this->_emailSupport = Yii::$app->params['email.support'] ?? 'support@example.com';
parent::__construct($config);
}
public function rules(): array
{
return [
[['checkboxes', 'reply'], 'safe'],
[['reply'], 'required', 'on' => 'replyOnly'],
[['checkboxes'], 'required', 'on' => 'statusOnly'],
[['reply', 'checkboxes'], 'required', 'on' => 'both'],
];
}
/**
* Assigns statuses from checkboxes to the message model.
* @return void
*/
public function applyStatusesToMessage(): void
{
$this->_message->setStatusFromCheckboxes($this->checkboxes);
}
/**
* Validates the associated message model.
* @return bool
*/
public function validateAssociatedMessage(): bool
{
$this->_message->validateStatus('status');
return !$this->_message->hasErrors();
}
public function attributeLabels(): array
{
return ['reply' => \Yii::t('app', 'Reply')];
}
/**
* Saves the reply and updates message status accordingly.
* @return bool
* @throws \Throwable
*/
public function process(): bool
{
$transaction = Yii::$app->db->beginTransaction();
try {
$scenario = $this->getScenario();
// Update status & reply fields conditionally
if ($scenario === 'both') {
$this->applyStatusesToMessage();
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();
$fields = ['status', 'replied', 'repliedTime'];
} elseif ($scenario === 'replyOnly') {
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();
$fields = ['replied', 'repliedTime'];
} elseif ($scenario === 'statusOnly') {
$this->applyStatusesToMessage();
$this->_message->addStatus(Message::STATUS_READ);
$fields = ['status'];
} else {
// Default fallback
$fields = [];
}
if ($this->_message->save(false, $fields)) {
if (in_array($scenario, ['replyOnly', 'both'], true) && $this->reply !== '') {
if (!$this->sendEmail()) {
throw new \Exception('Failed to send email.');
}
}
$transaction->commit();
return true;
}
} catch (Throwable $e) {
$transaction->rollBack();
\Yii::error("ReplyForm process failed: ".$e->getMessage());
}
return false;
}
/**
* Sends email reply.
* @return bool
*/
protected function sendEmail(): bool
{
try {
$sanitizedReply = strip_tags($this->reply, '<p><a><i><b><u>');
$sanitizedReply = preg_replace('/\bhttps?:\/\/\S+/i', '', $sanitizedReply);
$isSent = \Yii::$app->mailer->compose(
['html' => 'emailReply-html', 'text' => 'emailReply-text'],
[
'emailAppName' => $this->_appName,
'emailMessage' => $this->_message,
'emailReply' => $sanitizedReply,
]
)
->setFrom($this->_emailSupport)
->setTo($this->_message->email)
->setSubject('Re: ' . $this->_message->subject)
->setTextBody($sanitizedReply)
->send();
return $isSent;
} catch (Throwable $e) {
\Yii::error("Failed to send reply email: " . $e->getMessage());
return false;
}
}
/**
* Expose the message model if needed externally.
* @return Message
*/
public function getMessageModel(): Message
{
return $this->_message;
}
}
Notes
The Message model now uses BitmaskTrait exactly like your Product model, with virtual array attributes (getStatusArray/setStatusArray) to bind checkboxes in forms.
Validation for conflicting flags is centralized and consistent for both raw integer and array inputs.
The form class (ReplyForm) respects scenarios and requires checkboxes or reply or both depending on scenario — this likely fixes your "no action" on submit issue because the scenario and validation are properly configured and matched.
The setStatusFromCheckboxes() method is used both in Message and ReplyForm to handle setting the bitmask from the checkbox array.
Sample usage for your checkboxes in view (adjusted to match the statusArray naming):
<?php
$statusOptions = Message::getStatusLabels();
$currentStatuses = $model->getStatusForCheckboxes();
$selectedCheckboxes = is_array($replyForm->checkboxes) ? $replyForm->checkboxes : [];
foreach ($statusOptions as $value => $label) :
?>
<div class="me-3">
<?= $form->field($replyForm, 'checkboxes[]')
->checkbox([
'value' => $value,
'checked' => in_array($value, $currentStatuses) || in_array($value, $selectedCheckboxes),
'class' => 'form-check-input form-control square',
])
->label($label, ['class' => 'form-check-label'])
->inline(); ?>
</div>
<?php endforeach; ?>
Quick summary for fixing your typical scenario issues:
Ensure your form sets the scenario appropriately before validation.
The scenario must include the attributes being validated (checkboxes for status updates).
The rules() in ReplyForm enforce requiredness correctly per scenario.
Validation methods are called on the model linked to form attributes (the Message model's validateStatus is called manually).
If you want, I can also assist with refactoring the controller or view files to align with this. But the above should provide a clean complete solution that works like your Product bitmask logic but for Message statuses, and has a proper scenario-based ReplyForm to allow form submission to succeed or properly fail with errors.
Let me know if you want me to provide the MessageController or adjustments on views!
Where is the controller code?
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\web\Response;
use yii\web\NotFoundHttpException;
use app\models\Message;
use app\models\forms\ReplyForm;
use Throwable;
class MessageController extends Controller
{
/**
* View and update message (reply form with status updates)
*
* @param int $id
* @return string|Response
* @throws NotFoundHttpException
*/
public function actionViewUpdate(int $id)
{
$model = $this->findModel($id);
$replyForm = new ReplyForm($model->id);
$request = Yii::$app->request;
if ($request->isPost && $replyForm->load($request->post())) {
// Determine scenario based on submitted data and existing status
// Prepare combined bitmask from checkboxes submitted
$selectedBitmask = 0;
foreach ($replyForm->checkboxes as $flag) {
$selectedBitmask |= (int)$flag;
}
$statusChanged = $selectedBitmask !== $model->status;
$hasReply = trim($replyForm->reply) !== '';
if (!$model->hasStatus(Message::STATUS_REPLIED) && $hasReply) {
if ($statusChanged && $hasReply) {
$replyForm->setScenario('both');
} elseif ($hasReply) {
$replyForm->setScenario('replyOnly');
} elseif ($statusChanged) {
$replyForm->setScenario('statusOnly');
}
} else {
// Already replied or no reply text, only update status
$replyForm->setScenario('statusOnly');
}
// Validate form with the scenario
if ($replyForm->validate()) {
// Sync ReplyForm checkboxes into Message model
$model->setStatusFromCheckboxes($replyForm->checkboxes);
// Validate the Message model's status bitmask correctness
if (!$replyForm->validateAssociatedMessage()) {
Yii::$app->session->setFlash('error', implode(' ', $model->getFirstErrors()));
} else {
if ($replyForm->process()) {
// Set success flash based on scenario
$this->setScenarioSuccessFlash($replyForm->getScenario(), $model);
return $this->redirect(['index']);
} else {
Yii::$app->session->setFlash('error', Yii::t('app', 'Failed to save message or send reply email.'));
}
}
} else {
// Validation failed
Yii::$app->session->setFlash('error', implode(' ', $replyForm->getFirstErrors()));
}
}
// If first GET and message is unread, mark as read
if ($request->isGet && $model->hasStatus(Message::STATUS_UNREAD)) {
try {
$model->removeStatus(Message::STATUS_UNREAD);
$model->addStatus(Message::STATUS_READ);
if (!$model->save(false, ['status'])) {
throw new \RuntimeException('Failed to update message status.');
}
} catch (Throwable $e) {
Yii::error('Failed to mark message as read: ' . $e->getMessage());
Yii::$app->session->setFlash('error', Yii::t('app', 'Could not mark message as read.'));
}
}
$replies = $model->getReplies()->all(); // Assuming relations
$formatterHelper = /* your formatter helper setup here */;
return $this->render('viewUpdate', [
'model' => $model,
'replyForm' => $replyForm,
'replies' => $replies,
'formatterHelper' => $formatterHelper,
]);
}
/**
* Sets success flash messages based on scenario
*
* @param string $scenario
* @param Message $model
*/
protected function setScenarioSuccessFlash(string $scenario, Message $model): void
{
switch ($scenario) {
case 'statusOnly':
$msg = Yii::t('app', 'The status for message #{id} has been updated.', ['id' => $model->id]);
break;
case 'replyOnly':
case 'both':
default:
$msg = Yii::t('app', 'Your reply to {to} has been sent.', ['to' => $model->email]);
break;
}
Yii::$app->session->setFlash('success', $msg);
}
/**
* Helper method to load model or throw not found
*
* @param int $id
* @return Message
* @throws NotFoundHttpException
*/
protected function findModel(int $id): Message
{
if (($model = Message::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException(Yii::t('app', 'Message with ID {id} not found.', ['id' => $id]));
}
}
Explanation
Scenario is set manually based on whether a reply is present and/or status flags were changed.
Validates both the form attributes and the underlying Message model’s status bitmask before save.
Uses transactions/try-catch only inside the form’s process() method (as you already do).
Marks unread messages as read automatically on GET.
Manages flash messages for success or error.
Uses your refactored ReplyForm and Message models cleanly.
You can adjust this to your application as needed, but this example fully integrates your design and solves common scenario issues.
If you want, I can help you with updating your view as well or with other parts. Just ask!
php
public function rules(): array
{
$rules = [
[['checkboxes', 'reply'], 'safe'],
[['checkboxes'], 'required', 'on' => 'statusOnly'],
[['reply'], 'required', 'on' => 'replyOnly'],
[['reply', 'checkboxes'], 'required', 'on' => 'both'],
];
// If message type does NOT allow reply, disable reply requirements
if (!$this->canReply()) {
// For example, remove reply validation rules or mark reply as safe/not required
// Or add custom validation to forbid reply text
$rules[] = ['reply', 'validateNoReplyAllowed'];
}
return $rules;
}
/**
* Custom validator preventing reply text if replies not allowed.
*/
public function validateNoReplyAllowed($attribute, $params): void
{
if (!empty($this->$attribute)) {
$this->addError($attribute, \Yii::t('app', 'This message type does not accept replies.'));
}
}
Step 3: Adjust controller logic according to reply permissions
In controller (e.g. actionViewUpdate), add checks before processing:
php
if ($replyForm->load($request->post())) {
if (!$replyForm->canReply() && !empty($replyForm->reply)) {
Yii::$app->session->setFlash('error', Yii::t('app', 'You cannot reply to this type of message.'));
} else {
// Set scenarios and process as before
}
}
Step 4 (Optional): In UI/view layer, disable/hide reply input for non-replyable messages
In your view file:
php
<?php if ($model->isReplyable()) : ?>
<?= $form->field($replyForm, 'reply')->textarea(['rows' => 5]) ?>
<?php else: ?>
<p class="text-muted"><?= Yii::t('app', 'Replies are not allowed for this message type.') ?></p>
<?php endif; ?>
Summary
Extend Message model with meaningful type constants and add isReplyable() method.
Use isReplyable() in ReplyForm to allow/forbid replies via validation and scenario logic.
Enforce reply restrictions in controller and display appropriate UI.
This gives you centralized, clean control over reply permissions per message type.
If you want, I can help supply a full integrated code example for the model, form, controller, and view with this logic. Just let me know!
<?php
namespace app\models\forms;
use Yii;
use yii\base\Model;
use app\models\Message;
use yii\base\InvalidArgumentException;
use Throwable;
class ReplyForm extends Model
{
public array $checkboxes = [];
public string $reply = '';
private Message $_message;
private string $_appName;
private string $_emailSupport;
public function __construct(int $id, array $config = [])
{
$this->_message = Message::findOne($id);
if (!$this->_message) {
throw new InvalidArgumentException('Unable to find Message.');
}
$this->_appName = Yii::$app->name;
$this->_emailSupport = Yii::$app->params['email.support'] ?? 'support@example.com';
parent::__construct($config);
}
/**
* Returns true if the message can be replied to (e.g. Inquiry, Support).
*/
public function canReply(): bool
{
return $this->_message->isReplyable();
}
/**
* Returns true if an email should be sent on reply (only for Contact type).
*/
public function shouldSendEmailOnReply(): bool
{
return $this->_message->type === Message::TYPE_CONTACT;
}
public function rules(): array
{
$rules = [
[['checkboxes', 'reply'], 'safe'],
[['checkboxes'], 'required', 'on' => 'statusOnly'],
[['reply'], 'required', 'on' => 'replyOnly'],
[['reply', 'checkboxes'], 'required', 'on' => 'both'],
];
// If message cannot be replied to, forbid reply text
if (!$this->canReply()) {
$rules[] = ['reply', 'validateNoReplyAllowed'];
}
return $rules;
}
public function validateNoReplyAllowed($attribute, $params): void
{
if (!empty($this->$attribute)) {
$this->addError($attribute, Yii::t('app', 'This message type does not accept replies.'));
}
}
public function applyStatusesToMessage(): void
{
$this->_message->setStatusFromCheckboxes($this->checkboxes);
}
public function validateAssociatedMessage(): bool
{
$this->_message->validateStatus('status');
return !$this->_message->hasErrors();
}
/**
* Process saving and sending email as needed.
* Throws if email sending failed.
*/
public function process(): bool
{
$transaction = Yii::$app->db->beginTransaction();
try {
$scenario = $this->getScenario();
$fields = [];
if ($scenario === 'both') {
$this->applyStatusesToMessage();
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();
$fields = ['status', 'replied', 'repliedTime'];
} elseif ($scenario === 'replyOnly') {
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();
$fields = ['replied', 'repliedTime'];
} elseif ($scenario === 'statusOnly') {
$this->applyStatusesToMessage();
$this->_message->addStatus(Message::STATUS_READ);
$fields = ['status'];
}
if ($this->_message->save(false, $fields)) {
if (in_array($scenario, ['replyOnly', 'both'], true)
&& !empty($this->reply)
&& $this->shouldSendEmailOnReply()
) {
if (!$this->sendEmail()) {
throw new \Exception('Failed to send email.');
}
}
$transaction->commit();
return true;
}
} catch (Throwable $e) {
$transaction->rollBack();
Yii::error("ReplyForm process failed: {$e->getMessage()}");
}
return false;
}
protected function sendEmail(): bool
{
try {
$sanitizedReply = strip_tags($this->reply, '<p><a><i><b><u>');
$sanitizedReply = preg_replace('/\bhttps?:\/\/\S+/i', '', $sanitizedReply);
return Yii::$app->mailer->compose(
['html' => 'emailReply-html', 'text' => 'emailReply-text'],
[
'emailAppName' => $this->_appName,
'emailMessage' => $this->_message,
'emailReply' => $sanitizedReply,
]
)
->setFrom($this->_emailSupport)
->setTo($this->_message->email)
->setSubject('Re: ' . $this->_message->subject)
->setTextBody($sanitizedReply)
->send();
} catch (Throwable $e) {
Yii::error("Failed to send reply email: " . $e->getMessage());
return false;
}
}
/**
* Accessor to underlying Message model.
*/
public function getMessageModel(): Message
{
return $this->_message;
}
}
Updated MessageController::actionViewUpdate
Adjust scenario selection and flow:
php
public function actionViewUpdate(int $id)
{
$model = $this->findModel($id);
$replyForm = new ReplyForm($model->id);
$request = Yii::$app->request;
if ($request->isPost && $replyForm->load($request->post())) {
// Build bitmask from submitted checkboxes
$selectedBitmask = 0;
foreach ($replyForm->checkboxes as $flag) {
$selectedBitmask |= (int)$flag;
}
$statusChanged = $selectedBitmask !== $model->status;
$hasReply = trim($replyForm->reply) !== '';
$canReply = $replyForm->canReply();
if (!$canReply && $hasReply) {
Yii::$app->session->setFlash('error', Yii::t('app', 'You cannot reply to this type of message.'));
// Do not continue processing
} else {
if (!$model->hasStatus(Message::STATUS_REPLIED) && $hasReply) {
if ($statusChanged && $hasReply) {
$replyForm->setScenario('both');
} elseif ($hasReply) {
$replyForm->setScenario('replyOnly');
} elseif ($statusChanged) {
$replyForm->setScenario('statusOnly');
}
} else {
$replyForm->setScenario('statusOnly');
}
if ($replyForm->validate()) {
$model->setStatusFromCheckboxes($replyForm->checkboxes);
if (!$replyForm->validateAssociatedMessage()) {
Yii::$app->session->setFlash('error', implode(' ', $model->getFirstErrors()));
} else {
if ($replyForm->process()) {
$this->setScenarioSuccessFlash($replyForm->getScenario(), $model);
return $this->redirect(['index']);
} else {
Yii::$app->session->setFlash('error', Yii::t('app', 'Failed to save the message or send reply email.'));
}
}
} else {
Yii::$app->session->setFlash('error', implode(' ', $replyForm->getFirstErrors()));
}
}
}
// Mark unread as read on GET
if ($request->isGet && $model->hasStatus(Message::STATUS_UNREAD)) {
try {
$model->removeStatus(Message::STATUS_UNREAD);
$model->addStatus(Message::STATUS_READ);
if (!$model->save(false, ['status'])) {
throw new \RuntimeException('Failed to update message status.');
}
} catch (\Throwable $e) {
Yii::error("Failed to mark message as read: {$e->getMessage()}");
Yii::$app->session->setFlash('error', Yii::t('app', 'Could not mark message as read.'));
}
}
$replies = $model->getReplies()->all();
$formatterHelper = /* set your formatter helper */;
return $this->render('viewUpdate', [
'model' => $model,
'replyForm' => $replyForm,
'replies' => $replies,
'formatterHelper' => $formatterHelper,
]);
}
Updated view-update.php
Render reply textarea only if message type allows reply (e.g., not for Contact type, or define as you need):
php
<?php if ($model->isReplyable()): ?>
<?= $form->field($replyForm, 'reply')->textarea(['rows' => 5]) ?>
<?php else: ?>
<div class="alert alert-info">
<?= \Yii::t('app', 'Replies are not allowed for this message type.') ?>
</div>
<?php endif ?>
Summary
Message model method isReplyable() controls if reply is logically allowed.
ReplyForm uses that to validate and decide whether replies are allowed and if email should be sent.
Controller uses ReplyForm to enforce and handle reply according to type.
View shows/hides reply input based on reply permission.
If you want I can help build complete code snippets for your Message model’s isReplyable(), or help integrate further!
2. Update the ReplyForm Model
Make it aware of message type, and adapt scenario, validation, and processing accordingly.
php
<?php
namespace app\models\forms;
use Yii;
use yii\base\Model;
use app\models\Message;
use yii\base\InvalidArgumentException;
use Throwable;
class ReplyForm extends Model
{
public array $checkboxes = [];
public string $reply = '';
private Message $_message;
private string $_appName;
private string $_emailSupport;
public function __construct(int $id, array $config = [])
{
$this->_message = Message::findOne($id);
if (!$this->_message) {
throw new InvalidArgumentException('Unable to find Message.');
}
$this->_appName = Yii::$app->name;
$this->_emailSupport = Yii::$app->params['email.support'] ?? 'support@example.com';
parent::__construct($config);
}
public function rules(): array
{
$rules = [
[['checkboxes', 'reply'], 'safe'],
[['checkboxes'], 'required', 'on' => 'statusOnly'],
];
// For Contact and Inquiry types: reply required on replyOnly and both scenarios (reply is email-only)
if ($this->_message->requiresEmailReply()) {
$rules[] = [['reply'], 'required', 'on' => ['replyOnly', 'both']];
// No internal message reply, so disallow checkboxes on these (optional)
}
// For Order and Support: both checkboxes and reply are required in 'both' scenario
if ($this->_message->supportsMessageReply()) {
$rules[] = [['reply'], 'required', 'on' => ['replyOnly', 'both']];
$rules[] = [['checkboxes'], 'required', 'on' => ['statusOnly', 'both']];
}
return $rules;
}
/**
* Helper function to set statuses into message model.
*/
public function applyStatusesToMessage(): void
{
$this->_message->setStatusFromCheckboxes($this->checkboxes);
}
/**
* Validates the associated Message model (status validation).
*/
public function validateAssociatedMessage(): bool
{
$this->_message->validateStatus('status');
return !$this->_message->hasErrors();
}
/**
* Checks if user is permitted to reply (internal message or email).
*/
public function canReply(): bool
{
// User cannot reply if message does not support message reply and no reply entered
if (!$this->_message->userCanReply() && !empty($this->reply)) {
return false;
}
return true;
}
/**
* Process reply form save and email sending.
*/
public function process(): bool
{
$transaction = Yii::$app->db->beginTransaction();
try {
$scenario = $this->getScenario();
$fields = [];
// Process depends on type and scenario
if ($scenario === 'both') {
$this->applyStatusesToMessage();
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();
$fields = ['status', 'replied', 'repliedTime'];
} elseif ($scenario === 'replyOnly') {
// If type is contact or inquiry, only e-mail reply is sent, DB updated with replied fields only
$this->_message->addStatus(Message::STATUS_REPLIED);
$this->_message->replied = $this->reply;
$this->_message->repliedTime = time();
$fields = ['replied', 'repliedTime'];
} elseif ($scenario === 'statusOnly') {
$this->applyStatusesToMessage();
$this->_message->addStatus(Message::STATUS_READ);
$fields = ['status'];
}
if ($this->_message->save(false, $fields)) {
// Send email if Contact or Inquiry type and reply text present
if (($this->_message->requiresEmailReply()) && !empty($this->reply)) {
if (!$this->sendEmail()) {
throw new \Exception('Failed to send email.');
}
}
// For Order and Support, optionally send email too (customize as needed)
elseif (($this->_message->supportsMessageReply())
&& !empty($this->reply)) {
if (!$this->sendEmail()) {
throw new \Exception('Failed to send email.');
}
}
$transaction->commit();
return true;
}
} catch (Throwable $e) {
$transaction->rollBack();
Yii::error("ReplyForm process failed: {$e->getMessage()}");
}
return false;
}
protected function sendEmail(): bool
{
try {
$sanitizedReply = strip_tags($this->reply, '<p><a><i><b><u>');
$sanitizedReply = preg_replace('/\bhttps?:\/\/\S+/i', '', $sanitizedReply);
return Yii::$app->mailer->compose(
['html' => 'emailReply-html', 'text' => 'emailReply-text'],
[
'emailAppName' => $this->_appName,
'emailMessage' => $this->_message,
'emailReply' => $sanitizedReply,
]
)
->setFrom($this->_emailSupport)
->setTo($this->_message->email)
->setSubject('Re: ' . $this->_message->subject)
->setTextBody($sanitizedReply)
->send();
} catch (Throwable $e) {
Yii::error("Failed to send reply email: " . $e->getMessage());
return false;
}
}
public function getMessageModel(): Message
{
return $this->_message;
}
}
3. Update the MessageController::actionViewUpdate
Adapt scenario and flow for type-based replies:
php
public function actionViewUpdate(int $id)
{
$model = $this->findModel($id);
$replyForm = new ReplyForm($model->id);
$request = Yii::$app->request;
if ($request->isPost && $replyForm->load($request->post())) {
// Compose status bitmask from checkboxes
$selectedBitmask = 0;
foreach ($replyForm->checkboxes as $flag) {
$selectedBitmask |= (int)$flag;
}
$statusChanged = $selectedBitmask !== $model->status;
$hasReply = trim($replyForm->reply) !== '';
// Reject reply if user not allowed or type forbids reply text
if (!$replyForm->canReply() && $hasReply) {
Yii::$app->session->setFlash('error', Yii::t('app', 'You cannot reply to this type of message.'));
} else {
// Scenario logic
if (!$model->hasStatus(Message::STATUS_REPLIED) && $hasReply) {
if ($statusChanged && $hasReply) {
$replyForm->setScenario('both');
} elseif ($hasReply) {
$replyForm->setScenario('replyOnly');
} elseif ($statusChanged) {
$replyForm->setScenario('statusOnly');
}
} else {
$replyForm->setScenario('statusOnly');
}
if ($replyForm->validate()) {
$model->setStatusFromCheckboxes($replyForm->checkboxes);
if (!$replyForm->validateAssociatedMessage()) {
Yii::$app->session->setFlash('error', implode(' ', $model->getFirstErrors()));
} else {
if ($replyForm->process()) {
$this->setScenarioSuccessFlash($replyForm->getScenario(), $model);
return $this->redirect(['index']);
} else {
Yii::$app->session->setFlash('error', Yii::t('app', 'Failed to save the message or send reply email.'));
}
}
} else {
Yii::$app->session->setFlash('error', implode(' ', $replyForm->getFirstErrors()));
}
}
}
// Mark unread as read
if ($request->isGet && $model->hasStatus(Message::STATUS_UNREAD)) {
try {
$model->removeStatus(Message::STATUS_UNREAD);
$model->addStatus(Message::STATUS_READ);
if (!$model->save(false, ['status'])) {
throw new \RuntimeException('Failed to update message status.');
}
} catch (\Throwable $e) {
Yii::error("Failed to mark message as read: {$e->getMessage()}");
Yii::$app->session->setFlash('error', Yii::t('app', 'Could not mark message as read.'));
}
}
$replies = $model->getReplies()->all();
// formatterHelper you may instantiate as needed here
$formatterHelper = /* ... */;
return $this->render('viewUpdate', [
'model' => $model,
'replyForm' => $replyForm,
'replies' => $replies,
'formatterHelper' => $formatterHelper,
]);
}
4. Update your view-update.php
Show/hide reply textarea depending on message type, and adjust UI:
ReplyForm dynamically adapts validation and process logic based on message type.
Controller applies scenario logic, validates, and processes accordingly.
View shows or hides reply text field based on whether replying via messages is permitted.
This gives you a flexible, maintainable system aligned with your requirements:
Type
Reply Method
Notes
Contact
Email only
Reply saved as email
Inquiry
Email only
Reply saved as email
Order
Message + email
User can reply internally
Support
Message + email
User can reply internally
If you want, I can help you write unit tests for each type or further customize the email templates and notification flows!
You can put this method in ReplyForm or your Message model, wherever it makes most sense.
Step 3: Refactor reply permission logic to differentiate admin/user
Example in ReplyForm:
php
public function canReply(): bool
{
// Admin can always reply
if ($this->isAdminReply()) {
return true;
}
// For non-admin users check the message type-based logic
return $this->_message->userCanReply();
}
public function shouldSendEmailOnReply(): bool
{
// Admin replies always send email to notify user
if ($this->isAdminReply()) {
return true;
}
// User replies email logic here (optional)
return $this->_message->requiresEmailReply();
}
Step 4: Adjust your controller logic accordingly
In actionViewUpdate(), instead of blocking a reply based solely on message type, block only if the current user cannot reply:
php
if (!$replyForm->canReply() && $hasReply) {
Yii::$app->session->setFlash('error', Yii::t('app', 'You cannot reply to this message.'));
// halt processing
} else {
// Continue as before
}
Step 5: Adjust your view to check admin vs user and permissions separately
Can reply only if userCanReply() true (depends on message type)
Email on reply depends on your business rules
Why admin should always have reply access?
Admins manage all messages; restricting by message type would reduce admin capability.
Admin replies should always notify users — email sending is important here.
Why differentiate?
Users may only be allowed to reply to some types of messages.
Users may only use email replies for some types.
But admins need full control.
If you want, I can help you rewrite your ReplyForm, Message, controller, and views to fully reflect this logic, including examples of role checks and reply/email sending decisions.
Would you like me to do that?
Why is this good?
The method encapsulates your rules about who should send emails and when.
The process logic stays cleaner and easier to maintain.
All email decision logic is in one place (shouldSendEmailOnReply()), so changes require edits only in that method.
Summary & takeaway
You defineshouldSendEmailOnReply() in your ReplyForm to decide if an email should be sent.
You use that method inside your reply processing to conditionally trigger email sending.
This approach clarifies your code and gives you flexibility for future changes (e.g., different email rules by role, message type, or scenario).
If you'd like, I can provide a full updated version of your ReplyForm::process() including shouldSendEmailOnReply() usage, or help integrate this into your controller and view code. Just ask!
The .row wrapper is always output if user can reply, avoiding unbalanced divs.
The text area and reply card are wrapped in Bootstrap grid columns for consistent spacing.
empty() is a simple, reliable way to check if reply content is empty or not.
The else alert is outside the .row wrapper logically and visually separate.
Summary
Your logic is sound.
Just fix the .row div placement to avoid invalid HTML.
Simplify empty checks where possible.
Consider consistent Bootstrap styling wrappers for form elements & content display.
If you want, I can provide a complete snippet with example surrounding structure for easier integration!
public function actionViewUpdate(int $id): Response|string
{
$model = $this->findModel($id);
// PHP 8 match expression (if you are on PHP 8+)
$type = match ($model->type)
{
Message::TYPE_CONTACT => \Yii::t('app', 'contact'),
Message::TYPE_ORDER => \Yii::t('app', 'order'),
default => \Yii::t('app', 'inquiry'),
};
// Set Page title for the browser tab/page title and page header.
$pageTitle = \Yii::t('app', 'view');
// Set Title, Keywords, and Discription
$this->setMeta($this->_mvcName . ' / ' . $type . ' ' . $pageTitle . ' #' . $id , null, null, false);
// Set page breadcrumbs. (optional)
\Yii::$app->layoutManager->addBreadcrumb(['label' => $this->_mvcAdminName, 'url' => [$this->_mvcAdminUrl]]);// admin
\Yii::$app->layoutManager->addBreadcrumb(['label' => $this->_mvcName, 'url' => ['index']]);// index.
\Yii::$app->layoutManager->addBreadcrumb(['label' => $id, 'url' => ['view', 'id' => $id]]);// model->id
\Yii::$app->layoutManager->addBreadcrumb($pageTitle);// page now
$replyForm = new ReplyForm($model->id);
$session = \Yii::$app->session;
$request = \Yii::$app->request;
if (($request->isPost) && ($replyForm->load($request->post())))
{
// Handle Replyform $replyForm->checkboxes as statuses bits (Message $model->status)
$selectedBitmask = 0;
foreach ($replyForm->checkboxes as $flag)
{
$selectedBitmask |= (int) $flag;
}
// Compare the Replyform $replyForm->status with the current Message $model->status
$statusChanged = $selectedBitmask !== $model->status;
// Determine if Replyform $replyForm->reply has been provided via the Replyform model
$hasReply = trim($replyForm->reply) !== '';
// Reject reply if user not allowed or type forbids reply text
if (!$replyForm->canReply() && $hasReply)
{
$session->setFlash('error', \Yii::t('app', 'You cannot reply to this type of message.'));
}
else
{
// Checks Message $model if $model->status has STATUS_REPLIED and if $model->replied been set
if (!$model->hasStatus(Message::STATUS_REPLIED) && $hasReply)
{
if ($statusChanged && $hasReply)
{
$replyForm->setScenario('both');
}
elseif ($hasReply)
{
$replyForm->setScenario('replyOnly');
}
elseif ($statusChanged)
{
$replyForm->setScenario('statusOnly');
}
}
else
{
// Already replied or no reply text, only update status
$replyForm->setScenario('statusOnly');
}
// Validate form with the scenario
if ($replyForm->validate())
{
// Sync ReplyForm checkboxes into Message model
$model->setStatusFromCheckboxes($replyForm->checkboxes);
// Validate the Message model's status bitmask correctness
if (!$replyForm->validateAssociatedMessage())
{
$session->setFlash('error', implode(' ', $model->getFirstErrors()));
}
else
{
// if (!$model->hasStatus(Message::STATUS_REPLIED)) {
if ($replyForm->process())
{
// Set success flash based on scenario
$this->setScenarioSuccessFlash($replyForm->getScenario(), $model);
return $this->redirect(['index']);
}
else
{
$session->setFlash('error', \Yii::t('app', 'Failed to save message or send reply email.'));
}
//}// Else statement with error if trying to save Message $model->status as STATUS_REPLIED.
}
}
// Validation failed
else
{
$session->setFlash('error', implode(' ', $replyForm->getFirstErrors()));
}
}
}
// If first GET and message is unread, mark as read
if (($request->isGet) && ($model->hasStatus(Message::STATUS_UNREAD)))
{
try
{
$model->removeStatus(Message::STATUS_UNREAD);
$model->addStatus(Message::STATUS_READ);
if (!$model->save(false, ['status']))
{
throw new YiiDbException("Failed to save message status to the database.");
}
}
catch (Throwable $e)
{
\Yii::$app->session->setFlash('error', 'Could not mark status as read.');
// Use the ExceptionLogger to handle and log the exception.
ExceptionLogger::log($e, 'reply_form_error_');
}
}
// Fetching of replies for the message is only needed for Order and internal Inquries on product.
$replies = $model->getReplies()->all();
// Setup Formatter Helper for view
$formatterHelper = FormatterHelper::create($this->_formatter);
return $this->render('viewUpdate', [
'model' => $model,
'replyForm' => $replyForm,
'replies' => $replies,
'formatterHelper' => $formatterHelper,
]);
}
Set 'action' => ['view-update', 'id' => $model->id] in ActiveForm::begin()
Link URLs without required id param
Add 'id' => $model->id to all URLs (Html::a, etc.) pointing to actions needing id
Breadcrumb or layout URLs missing id
Confirm appropriate params included or remove if unnecessary
JavaScript / AJAX requests missing id param
Pass id properly in AJAX URLs
If after checking your form and links you still have problems, share your view file’s form portion and any relevant URL/link generation. I can help pinpoint the issue.
Let me know if you'd like me to explain how to fix your ActiveForm or links specifically!
2. Check Model Validation and DB Save
Even though you use save(false, $fields) to skip model validation, your DB may raise constraints (e.g., NOT NULL columns missing).
Double-check that all required columns are either set in your model or have database defaults.
Ensure $fields array contains the attributes you actually updated.
If $this->_message->repliedTime is defined as an integer or datetime column? If it's datetime, set with date('Y-m-d H:i:s') instead of time().
3. Check Email Sending
Verify that your Yii mailer component is correctly configured.
Check your mail sending log, or try sending a test email manually.
sendEmail() method can fail silently but now logs errors with the updated code.
Check if reply text $this->reply contains anything unexpected breaking the mail.
4. Further debugging tips
Temporarily disable email sending (sendEmail() call) to isolate if error is from the DB save or email.
Example:
php
// Temporarily skip email to test:
if (false && $this->shouldSendEmailOnReply() && !empty($this->reply)) {
if (!$this->sendEmail()) {
// ...
}
}
Then if saving works, start debugging your mail config.
5. Check transaction behavior
If mail sending fails and you rollback the transaction, the message changes won't persist.
You can decide if you want to rollback when email fails or commit anyway and just report email failure separately.
Summary
Add error logs for:
Save failure (getErrors())
Email sending failure
Exception catches
Verify:
Your data are correct for DB columns
Mailer config is working
Attribute types match DB schema (timestamps vs strings)
If you want, I can help you review your Message table schema and the sendEmail() implementation or provide sample mail config to ensure sending works. Just let me know!