PHP snippet for limiting the total number of submissions to a Webform. Note that this is different from limiting the number of submissions per user, which is already an option in the webform configuration.
This snippet counts the number of submissions and when the max is reached, all roles for the node are automatically unchecked and the node is saved, thereby denying access to the form. This code is built on this post by quicksketch.
// Count the number of submissions in the webform_submissions table for this node.
$count = db_result(db_query("SELECT count(*) FROM {webform_submissions} WHERE nid = %d", $node->nid));
// The submission limit is 20 - if it has been exceeded...
if ($count >= 20) {
// Uncheck all role access for this node. This disables access so users will see
// this message when they navigate to the form: 'Submissions for this form are closed.'
$node->webform['roles'] = array();
// Save the node with all roles unchecked
node_save($node);
}
The next user that visits the form will receive the message "Submissions for this form are now closed.", which is the default behavior of Webform when no roles have access to submit the form.
Comments
To close a form based on the total of a specific field...
My site uses forms to allow people to claim a limited number of tickets for an event, and I needed to close the form when the tickets are gone. With the help I got here: http://drupal.org/node/532208 , I was able to put together this code snippet for advanced validation:
The "cid" is the number of the field you're totaling over all submissions, based on the order it was added to the form, not the order it's displayed. Adding the value for the field of the form being currently submitted is key, or the form will allow one more registration than it should.
Using the API
Using the API to query for the number of submissions is preferred:
FVS - https://dmarcpal.com
For Drupal 7: $count =
For Drupal 7:
$count = db_query("SELECT sum(data) FROM {webform_submitted_data} ... etc ... WHERE cid = 7")->fetchField();
Use fetchField, db_result is no more.