Is there a way to lock a form if the form is in use? The intention is to avoid two users submitting the same form.

Ted Husted

Your options here are the same as with any enterprise application.

  • Pessimistic locking, and
  • Optimistic locking
For a pessimistic lock, you need some flag on the record that says someone has checked it out, along with some record of who. When an administrator starts the order workflow, you update the database. If someone else try to start the same order, you branch to a page that tells them they can't do that.

This pretty much works, but you also need a good routine for unlocking the order, since some people will invariably fail to complete the workflow and leave a record locked.

For an optimistic lock, you need a version flag on the record. When someone retrieves the record, you include the version number. Before saving the record, you check the version in the database. If it doesn't match, then someone else has beaten your user to the punch, and you branch to a page explaining the problem.

Optimistic locks are fine when the chance of contention is low and the changes are usually minimal. Pessimistic locks are better when the chance of contention is high and the changes are either non-minimal or critical.

Scott Ambler's papers provide some good background about this

I have a telemarketing application that uses pessimistic locks to keep people from trying to call the same person at once. Though, for most things, optimistic locks work well.

HTH, Ted.
Struts in Action

For keeping someone from submitting the same form twice, Struts has a built-in token feature, but that's a different question =:0)