How to tackle this issue?
I add the error into the error collection, but every time a validation is done, I think $errorCollection
is re-initialized, hence it's null. And previously added error are not shown in errorCollection-error nor $cart->errors
? In twig, I can still see the error.
class MinimumOrderValueValidator implements CartValidatorInterface
{
private $config;
public function __construct(SystemConfigService $config)
{
$this->config = $config;
}
public function validate(Cart $cart, ErrorCollection $errorCollection, SalesChannelContext $context): void
{
// Check if there is at least one physical product in the cart
$hasPhysicalProduct = $this->hasPhysicalProduct($cart);
$errorId = 'minimum_order_value_error'; // Identifier for the error
if (!$hasPhysicalProduct) {
// No physical products found, so no need to check for the minimum order value
$this->removeMinimumOrderValidationError($cart, $errorId);
return;
}
$minimumOrderValue = $this->config->get('MyAppTheme.config.MinimumOrderValue') ?? 10; // Default to 10 if not defined
// Check if the total cart value is less than the minimum order value
if ($cart->getPrice()->getTotalPrice() < floatval($minimumOrderValue)) {
// Check if an error with the specific ID already exists
$existingError = $errorCollection->get($errorId);
if (!$existingError) {
// Add error as the total cart value is less than the minimum order value
$errorCollection->add(new MinimumOrderValueNotReachedException(
$errorId,
strval($minimumOrderValue)
));
}
} else {
// Cart value meets the minimum order value, remove the error if it exists
$this->removeMinimumOrderValidationError($cart, $errorId);
}
}
// Function to check if the cart contains at least one physical product
private function hasPhysicalProduct(Cart $cart): bool
{
foreach ($cart->getLineItems() as $item) {
$states = $item->getStates();
if (!empty($states) && 'is-physical' === $states[0]) {
return true;
}
}
return false;
}
// Function to remove MinimumOrderValueNotReachedException from the error collection
private function removeMinimumOrderValidationError(Cart $cart, $errorId): void
{
foreach ($cart->getErrors() as $error) {
if ('promotion-not-found' === $error->getMessageKey()) {
$cart->getErrors()->remove($errorId);
}
}
}
}
OK, I found out that errors added to errorCollection
, even though they show in twig but are not added to $cart
. I added errors to cart and was able to remove them from there, and it wasn't reinitialized.
$cart->addErrors(new MinimumOrderValueNotReachedException(
$errorId,
strval($minimumOrderValue)
));