# How to perform x = x + y in Rules

How can I add this action in Rules? This is my pseudocode:

``````1 total=0;
2 //loop through each line item {
3 //get quantity of each product
4 total = total + line_item_quantity;}
5 if total =< 2 then total = 0;
6 total_cost = total * \$1.50
``````

I think I can get everything working with the Conditional Rules module. but I cannot get

``````x = x + y
``````

to work on Rules because they say that the variable already exists.

Also, how do I use conditions on entities like calculated shipping cost? What's the variable name?

• I don't remember now, but wouldn't `x += y` work? Commented Feb 14, 2014 at 7:50
• Actually I was referring to adding an action (so that I don't need to do it programatically). Is it possible? Commented Feb 14, 2014 at 12:04

Have a look at my answer to the question about "How to add up all items of a field collection field using Rules?". Your question is, IMO, a minor variation of it. Just replace `article-details-item:field-price` by `line_item_quantity` (as in your pseudocode) and it is close to identical.

The custom rule to do the calculation, looks like so:

``````{ "rules_calculate_sum_of_prices_in_all_field_collection_items" : {
"LABEL" : "Calculate sum of prices in all field collection items",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_view--article" : { "bundle" : "article" } },
"IF" : [
{ "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_details" } }
],
"DO" : [
{ "drupal_message" : { "message" : "\u003Cstrong\u003EDrupal calculator\u003C\/strong\u003E started ..." } },
"USING" : { "type" : "decimal", "value" : "0" },
"PROVIDE" : { "variable_added" : { "total_price" : "Price total" } }
}
},
{ "LOOP" : {
"USING" : { "list" : [ "node:field-article-details" ] },
"ITEM" : { "article_details_item" : "Article details item" },
"DO" : [
{ "data_calc" : {
"USING" : {
"input_1" : [ "total-price" ],
"op" : "+",
"input_2" : [ "article-details-item:field-price" ]
},
"PROVIDE" : { "result" : { "calculation_result" : "Calculation result" } }
}
},
{ "data_set" : { "data" : [ "total-price" ], "value" : [ "calculation-result" ] } },
{ "drupal_message" : { "message" : "After adding a price of \u003Cstrong\u003E[article-details-item:field-price]\u003C\/strong\u003E for field collection item with id \u003Cstrong\u003E[article-details-item:item-id]\u003C\/strong\u003E, subtotal is \u003Cstrong\u003E[calculation-result:value]\u003C\/strong\u003E." } }
]
}
},
{ "drupal_message" : { "message" : "The \u003Cstrong\u003ETotal price\u003C\/strong\u003E for all prices included as field collection items is \u003Cstrong\u003E[total-price:value]\u003C\/strong\u003E." } },
{ "drupal_message" : { "message" : "\u003Cstrong\u003EDrupal calculator\u003C\/strong\u003E ended ..." } }
]
}
}
``````

Enough to get you going and get it to work (or should I say "How good are you in reading/digesting the Rules-export-language)?