LUA example: Block saving an order

In this example we’ll see how to prevent an order from being saved for an insolvent customer. Since this is a very drastic measure, we’ll split the procedure into two scripts.

The first raises an alert when the customer is selected, while the second won’t let the order be saved unless the customer or their insolvency status is changed.

Script Group
Form
Event
Value Changed

As mentioned, the first script tells the user that the customer selected for the order is blocked. This avoids filling in the whole order only to find out at the end that it can’t be saved.

if datafield.name() == "gguid_cliente" then
   t = database.getsql("SELECT insolvente FROM clienti WHERE gguid='" .. datafield.getvalue() .. "'")
   if t.countrows() > 0 then
      righe = t.getrows()
      if righe[1].getvalue("insolvente") == 1 then
         program.showerror("Warning: the customer is insolvent. The order cannot be saved!")
      end
   end
end

We intercept the change of the gguid_cliente field. This is the service field of the subtable where the gguid of the selection is stored. It is always better to use the global unique identifier gguid instead of the customer’s actual name, so the customer can be found even if the name changes.

We read the value of the Insolvente field in the customers table and show an error message if the value is one. This field will almost certainly be a check box on the customer form.

Now let’s write the second script, which blocks the order from being saved.

Script Group
Form
Event
Pre-save
 t = database.getsql("SELECT insolvente FROM clienti WHERE gguid='" .. dataview.getvalue("gguid_cliente") .. "'")

if t.countrows() > 0 then
   righe = t.getrows()
      if righe[1].getvalue("insolvente") == 1 then
         errorn.errorcode = "E1"
         errorn.errormessage ="Warning: the customer is insolvent. The order cannot be saved!"
         do return end
     end
end

As you can see, this is practically identical to the first one, except that the gguid value is taken from the dataview. The procedure is the same so that the customer’s insolvency status can still be changed: we could open the customer’s form and change the value while keeping the order form open.

What changes is the use of the errorn object. Its job is to report errors to the program. Here we force an error ourselves by setting a code and a message and exiting the script.

Since this is the pre-save event, the program will stop the form’s Save procedure. The error code can be anything, since it only helps us identify which part of the script raised it.