If I change an order's status to "Cancelled" (my custom order status I created), I want to ensure that the CP editors provide a "Cancellation Reason" from a dropdown field in the order. I've set up a custom validator to do this but it doesn't get recognized in Commerce's flash message.
In my plugin, I'm adding a custom rule to Order
elements like:
use my\plugin\validators\CancellationReasonValidator;
use craft\events\DefineRulesEvent;
use craft\commerce\elements\Order;
use yii\base\Event;
Event::on(
Order::class,
Order::EVENT_DEFINE_RULES,
static function(DefineRulesEvent $event) {
/* @var Order $order */
$event->rules[] = [['cancellationReason'], CancellationReasonValidator::class];
});
My validator looks like:
use Craft;
use craft\commerce\elements\Order;
use yii\validators\Validator;
class CancellationReasonValidator extends Validator
{
public function validateAttribute($model, $attribute)
{
$cancellationReasonField = $model->$attribute;
/* @var Order $model */
if ( $model->isCompleted
&& $model->getOrderStatus()->handle === 'cancelled'
&& ! $cancellationReasonField->value) {
$this->addError($model, $attribute, Craft::t(
'site',
'A cancellation reason is required for {orderNumber}',
['orderNumber' => $model->shortNumber]
));
}
}
}
If I edit an order, change the status to "Cancelled", and click the red update button, the validation works:
However, if I do this from the orders listing view, where I try to update an order's status like in the screenshot below, there is no flash message displayed to the user that the order couldn't save.
I understand there's a lot of asynchronous JS happening here, but how do I tap into showing some sort of message to my CP editors, preferably one that mentions the order's shortNumber
?