I have a View that lists entity IDs of some sort and I have created a Rules View for this. In Rules, I have created a component where I want to fetch the total number of rows from that Rules View and do something with that number which should be an integer, I believe. I don't want to do something with each row. I just need to collect the total. I'm using the "Collect view result rows" action to try to collect the total number of rows as a number. How do I make this number available in my Rules component without looping over the entire list?
1 Answer
Here's a working recipe. (since no one is replying, I asked ChatGPT but it couldn't help me either)
Requirements: Drupal 7, Views 3, Views Rules
Step 1: Create a View and add the following fields:
- Global: View Results Counter (reverse the order and set the label to #)
- List the entity IDs
- Add filters as you see fit.
- Set the pager setting to: display all items.
Step 2: Create a Rules View In the Rules Settings choose: edit field info Here configure the Rules: row variables
"#" set it to "enabled", check the box "Use rendered result", choose "integer" as the Data type and leave the label and Name as it is. The name should now be "counter"
ID set it to "enabled", choose "Course" as the Data type (that is my ECK entity name) and I set the label to "Id" and the name to "id"
Hit apply.
Step 3: Create a Rules component (as component plugin I chose: "Rule")
Add the action: "Collect view result rows", leave everything as it is and hit "save"
Add a variable: Set the Type as "integer" and the optional initial value: choose "Data selector" and drill down to "counter:0" This will take the first counter value from the first row. Since we have set it to reverse, we now have the total number of items in the view which is what we want. I left the name of the Variable label and the Variable name as it gave me so that was "Added variable" and "variable_added"
Hit save
Show a message and enter: [variable-added:value]
Go to the Components overview page and click on the "execute" button next to the name of your rule ... et voila!
{ "rules_show_me_the_total_number_of_active_courses" : { "LABEL" : "Show me the total number of Active Courses", "PLUGIN" : "rule", "OWNER" : "rules", "TAGS" : [ "component", "courses", "rule", "test", "vbo" ], "REQUIRES" : [ "views_rules", "rules" ], "DO" : [ { "views_rules_collect_rows" : { "USING" : { "views_rules_display" : "course_collection_for_cron:views_rules_1" }, "PROVIDE" : { "counter" : { "counter" : "List of #" }, "id" : { "id" : "List of Id" } } } }, { "variable_add" : { "USING" : { "type" : "integer", "value" : [ "counter:0" ] }, "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } } } }, { "drupal_message" : { "message" : "The Added Variable value counter: [variable-added:value]" } } ]
} }