4

I have some menu items where the action is this:

procedure TMISMainFrm.ActiSalesInvoiceExecute(Sender: TObject);
begin
  if CheckMdiList('Sales Invoice') then
    BEGIN
      SalesInvFrm := tSalesInvFrm.Create(Self,0,UserIdNo,1,1);
      SalesInvFrm.Show;
    END;
end;

The above action can be called from several locations, but the 2nd parameter (the 0), may change. How do I pass the required parameter such that I do not have to recode the routine?

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
mra
  • 97
  • 6

1 Answers1

7

One simple approach, commonly used, is to set the Tag property of the action. It should be different for each action, obviously. Then you change your execute handler like so:

procedure TMISMainFrm.ActiSalesInvoiceExecute(Sender: TObject);
begin
  if CheckMdiList('Sales Invoice') then
    BEGIN
      SalesInvFrm := tSalesInvFrm.Create(Self,(Sender as TAction).Tag,UserIdNo,1,1);
      SalesInvFrm.Show;
    END;
end;
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 1
    This will also work if you connect the same action to different components (buttons, menuitems etc.) and have to react according to the triggered component. In that case use the actions ´ActionComponent´ property to identify the individual component executing the action. – Uwe Raabe Sep 15 '11 at 13:40
  • Don't forget to make sure the sender is a TAction before casting it as such. `if Sender is TAction then SalesInvFrm := ... (Sender As TAction).Tag ...` – Jerry Gagnon Sep 15 '11 at 15:16
  • 2
    @Jerry No don't do that. The `as` is a type safe cast that raises an exception is the object is not a `TAction`. That's what you want because it acts like an assertion. It means this method can only ever be called by the framework in response to an action. – David Heffernan Sep 15 '11 at 15:17
  • @DavidHeffernan what if I needed to use a string parameter which is required for collecting data. I have an action named "doSave" and in this action I'm handling many things and some functions. Is it possible to set some parameters for TAction? – Abdullah Ilgaz May 21 '17 at 18:01
  • 1
    You'd need to derive a subclass with a string property. – David Heffernan May 21 '17 at 18:02