Query with Extension Methods

(Note!!  This blog has been updated. Due to changes in nopCommerce, use just "Product", not "ProductVariant.Product".)

A little while back we introduced some new functions that you can use to query your cart when creating complex shipping scenarios.  These are also available in Payment Director.  Here's some more details:

You can check if a product is in a particular category (or any category matching a pattern):

Product.HasCategory(categoryName)

Product.HasCategory(categoryId)

Product.HasCategoryMatch(regular_expression)

For example, you can check if there are any items in the cart that have a category that includes the word “Brushes”:

Items.Any(Product.HasCategoryMatch("Brushes"))

You can test if an item has a specific attribute/value (e.g. “Color”,”Blue”), or the specific attribute with any value (“Color”):

HasAttributeValue(attributeName, valueName)

HasAttributeValue(attributeName)

For example, you can get the quantity of items in cart that have the Vanilla scent:

Items.Where(HasAttributeValue("Scent","Vanilla")).Sum(Quantity)

 You can use the value id (integer) if you prefer (in case you change the name)

HasAttributeValue(valueId)

You can get a list of attribute values that the customer has applied to a cart item:

Item.GetAttributeValues(attributeName, valueSeparator)

Item.GetAttributeValues(attributeName)  // value separator defaults to “,”

Of course it does not need to be a list – for example, if you have a “Size” attribute, then you can just get the value the customer entered for the Size.  For example, if you have many products in the cart with a Size attribute, you can calculate a shipping rate based on the size values – let’s say you want the rate to be on a per item basis, for each ($3.33 * Size * Quantity)

Items.Where(HasAttributeValue("Size")) .Sum(3.33 * Decimal.Parse(GetAttributeValues("Size")) * Quantity)

(You can do date/time calculations too – e.g. … .Min(DateTime.Parse(GetAttributeValues("DeliveryDate")) )

Here’s an example of how the new methods make your expressions shorter and more readable:

We’ve blogged before about “Free Shipping over $X - unless there are any excluded items”.  We used a Reference type variable to shorten the query:

Order

Type

Name

Expression

Rate Expression

10

Reference

categories

Product.ProductCategories

 

20

Reference

hasExcludeFromFreeOverX

[@categories].Any(Category.Name = "Exclude from Free Over X")

 

30

OptionExit

Free Shipping

[$SubTotalWithDiscounts] > 50 and !Items.Any([@hasExcludeFromFreeOverX])

0

40

Option

Standard

true

10

Here the same scenario as above with new HasCategory method -

Order

Type

Name

Expression

RateExpression

30

OptionExit

Free Shipping

[$SubTotalWithDiscounts] > 50 and !Items.Any(Product.HasCategory("Exclude from Free Over X"))

0

40

Option

Standard

true

10

Tags :  Functions
Comments
Leave your comment
: