Custom procedures

Completed

The reasons for creating custom procedures are to:

  • Organize the program.

  • Create self-explaining code.

  • Simplify the development process.

  • Make code reusable, which reduces work.

  • Reduce errors.

  • Help make modifications easier.

  • Reduce the size of the objects.

A procedure is a named part of a program. You can group many lines, give it a name, and then call this block of code by its name.

To create a new custom function, use the tprocedure snippet.

local procedure MyProcedure()
begin
   // Some logic goes here.
end;

A procedure, whether custom or existing, can be called from within expressions or from within statements.

Procedure call in an expression

In the following example, the CalculatePrice custom procedure is called from within an expression that multiplies the calculated price with a certain quantity. The CalculatePrice procedure performs some calculation logic and returns the result as a decimal.

trigger OnRun()
begin
  TotalCost := Quantity * CalculatePrice();
end;

procedure CalculatePrice() : Decimal
begin
   // Some calculation logic goes here.
end;

Procedure call in a statement

In the next example, the custom function MyCustomFunction is called from within a statement.

trigger OnRun()
begin
  if Quantity > 5 then
    MyCustomFunction();
end;

procedure MyCustomFunction()
begin
   // Some logic goes here.
end;

GuiAllowed function

When creating custom procedures, you should consider the GuiAllowed function. You can use this function to determine when certain parts of your code should be run, depending on whether a graphical user interface (GUI) is available or not.

A user interface isn't used when your code is being run by a web service. If your code expects user input or displays a message, it results in an error. By using the GuiAllowed function, you can test if a GUI is available or not before requesting user input.

if GuiAllowed then
   Message('Hello');

This function is used in Business Central when your function can be called through the API service.