I have a price field in a TClientDataSet that comes from the database but it is calculated, that is, it is saved, but it respects a formula according to freight cost and taxes.
The formula works well mathematically and I have it in the afterpost event:
procedure TDataModule1.cdsproductosAfterPost(DataSet: TDataSet);
begin
with DataModule1 do
begin
DataModule1.cdsproductos.Open;
DataModule1.cdsproductos.Edit;
cdsproductosprecioactual.AsFloat:=cdsproductosCosto.AsFloat*
(cdsproductosGanancia.AsFloat/100)+
cdsproductosCosto.AsFloat+cdsproductosRedondeo.AsFloat + (cdsproductosCosto.AsFloat *
(cdsproductosImpuesto.AsFloat/100))+cdsproductosFlete.AsFloat;
end;
end;
So my question is: how do I update the price DBEdit when changing any DBEDit that influences the formula, example: when changing the cost, the price must change and be saved without having to click on the save button.
You can use the event
OnChange
of the fields that are part of the formula, in this wayPrecio
it will be updated automatically every time the value of any of these fields changes, without waiting until after posting in the record.To achieve this, you can start by factoring the formula code into a separate method, say:
Costo
So let's say this calculation should be fired whenever any of the ,Redondeo
,Ganancia
, fields changeImpuesto
(I don't know if I missed any, but you get the picture), you can write event handlers forOnChange
each of these fields and call the methodCalcularPrecio
, which would look something like:Good practices
I have noticed that you use a statement
with
in your code, like this:I don't know exactly what you want to achieve, but in my opinion, this statement is not only not necessary, but it is superfluous and could cause problems if you create more than one instance of the class at run time in the future. . When any method of the class is cast,
TDataModule1
you already have access to all members of the class for the instance on which the method was cast. These members do not need to be referenced with a variable.I've also seen a couple of other details:
You use the method
AfterPost
to modify data from the same record that you just inserted/updated in the underlying table in the database (I understand that is not what you want in the case ofPrecio
, but if you still use it in other cases, I recommend doing it in elBeforePost
, which is fired just before sending the insert/modify to the engine.This will prevent any record from being outdated in the dataset if something fails during the execution of the
AfterPost
.BeforePost
The / methodsAfterPost
and, in general, most of the DataSet are called while the dataset is open, you do not need to open it , which you do in the first line of code:That line is unnecessary, since this event will never be launched on a closed data set.