If you need to force the user to select a value from a predefined list, an option is the way to go. This recipe explains how to create an Option
variable and access each of its values.
Let's create a new codeunit from Object Designer.
Then add the following global variable:
Name
Type
ColorOption
Option
With the cursor on the
ColorOption
variable, navigate to View | Properties or (Shift + F4).In the Property window, set the following property:
Property
Value
OptionString
None,Red,Green,Blue
Now write the following code into the
OnRun
trigger of the codeunit:ColorOption := ColorOption::Green; CASE ColorOption OF ColorOption::None: MESSAGE('No Color Selected'); ColorOption::Red: MESSAGE('Red'); ColorOption::Green: MESSAGE('Green'); ColorOption::Blue: MESSAGE('Blue'); END;
Save and close the codeunit.
On executing the codeunit, you should see a window similar to the one shown in the following screenshot:
An Option
is a field or variable that stores one value from a selectable list. In a form, this list will appear as a dropdown from which the user can select a value. The list of options is stored as a comma-separated string in the
OptionString
property. If we query such stored values from a SQL database, we will receive an integer value representing each option. In our current example, the integer value has been mapped with options, where None
= 0
, Red
= 1
, Green
= 2
, and Blue
= 3.
These values are accessed using the variable_name::option_name
syntax. The first line of the example assigns one of the possible values (Green
) to the variable. Then we use a CASE
statement to determine which of the values were selected.
The Option
fields are prevalent throughout the NAV system, but most commonly on documents. In NAV, many documents share the same table. For example, sales quotes, orders, invoices, and return orders are all based on the Sales Header
table. In order to distinguish between the types, there is an Option
field called Document Type
. Design the 36
, Sales Header
table to see the available options for this field.
Now design the 80
, Sales-Post
codeunit. Examine the OnRun
trigger. At the start of the function, you will see the following code:
CASE "Document Type" OF "Document Type"::Order: Receive := FALSE; "Document Type"::Invoice: BEGIN Ship := TRUE; Invoice := TRUE; Receive := FALSE; END; "Document Type"::"Return Order": Ship := FALSE; "Document Type"::"Credit Memo": BEGIN Ship := FALSE; Invoice := TRUE; Receive := TRUE; END; END;
This is a common example of how options are used in NAV. You can scroll through the codeunit to find more examples.
The Using the CASE statement to test multiple conditions recipe in Chapter 2, General Development