if (product.ProductAttributeMappings.Any())
{
//product has some attributes. let a customer see them
return Json(new
{
redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName() }),
});
}
If the product only has readonly checkbox attributes that the customer would have no control over this behaviour still occurs (if the checkbox is set to pre-selected). I think it would be preferable in this case if the product was added directly to the basket. This can be achieved by changing the code above to this:
if (product.ProductAttributeMappings.Any(a => a.AttributeControlType != AttributeControlType.ReadonlyCheckboxes))
{
//product has some attributes that are not readonly. let a customer see them
return Json(new
{
redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName() }),
});
}
This bypasses the initial validation for products that only have readonly checkbox attributes but the add to basket still fails when the _shoppingCartService.AddToCart function is called. This can be made to work by generating the attributesXml for the readonly attributes and passing it to the AddToCart function like this (additions in bold):
string attributesXml = "";
//if product has some readonly attributes generate the xml to allow them to add to basket
foreach (var attribute in product.ProductAttributeMappings.Where(a => a.AttributeControlType == AttributeControlType.ReadonlyCheckboxes))
{
//load read-only (already server-side selected) values
var attributeValues = _productAttributeService.GetProductAttributeValues(attribute.Id);
foreach (var selectedAttributeId in attributeValues
.Where(v => v.IsPreSelected)
.Select(v => v.Id)
.ToList())
{
attributesXml = _productAttributeParser.AddProductAttribute(attributesXml,
attribute, selectedAttributeId.ToString());
}
}
//now let's try adding product to the cart (now including product attribute validation, etc)
addToCartWarnings = _shoppingCartService.AddToCart(customer: _workContext.CurrentCustomer,
product: product,
shoppingCartType: cartType,
storeId: _storeContext.CurrentStore.Id,
attributesXml: attributesXml,
quantity: quantity);
if (addToCartWarnings.Count > 0)
{
//cannot be added to the cart
//but we do not display attribute and gift card warnings here. let's do it on the product details page
return Json(new
{
redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName() }),
});
}
I think these two changes would allow products that have only readonly attributes to be added directly to the basket while still retaining the current redirect behaviour for products with attribute types that require the customer to make a decision.