Friday, 29 June 2018

WORKFLOW

Chapter 11: Workflow
11-1
CHAPTER 11: WORKFLOW
Objectives
The objectives are:
•  Implement a new line-item workflow.
•  Review the workflow providers in Microsoft Dynamics
®
AX 2012.
•  Create a custom workflow provider.
•  Enable queues for a workflow document.
•  Discuss how currency type fieldsfunction within the Condition
Editor.
•  Review the steps required to implement a new hierarchy type field to
be used in the Condition Editor.
Introduction
Workflow in Microsoft Dynamics AX 2012 uses a combination of Application
Object Tree (AOT) elements created by the developer and additional set up that
is completed by the end-user to control the configuration and process a workflow
will follow.
This course introduces advanced development topics that explain how to
implement line-item workflows, create workflow work item queues, create new
workflow providers, implement currency support in the Condition Editor, and
implement conditions on fields that represent hierarchies in the Condition Editor.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-2
Line-Item Workflows
Workflows act on business documents. Sometimes patterns exist where there is a
relationship between two tables―one is a header table; for example, Expense
header, and the other is a line-item table. The line-item table contains records that
relate to the header, for example, an expense report has many expense lines.
Line-item workflow in Microsoft Dynamics AX 2012 supports this header and
line pattern. The developer must enable line-item support for each workflow
where a header and line-item relationship exists. Then the business user can
configure a workflow that includes a "Line-item workflow" element. In that
element, the business user can select the workflows that he or she wants to act on
the line items. For example, some transactions might be processed by using a
project approval workflow, others might be processed by using a workflow that
only requires approval by the manager. End-users interact with line-item
workflows in the same manner as other workflows—by taking workflow actions
on the line items.
NOTE: Some tables are enabled for line-item workflows out of the box, such as
purchase requisitions and expense reports.
Create a Custom Line-Item Workflow
The high-level steps a developer must take to implement a new line-item
workflow include the following.
1.  Identify the header and line table thathave to be workflow enabled,
and then make sure that there is a table relationship between them.
a.  Open the AOTand browse to Data Dictionary > Tables.
b.  Select the line-item table and then expand the Relationsnode.
c.  Verify that a relation exists back to the header table.
2.  Assuming that a workflow already exists for the header table, create
a new line-item workflow under the Line-item workflownode of
the header workflow.
3.  Set the properties of the new line-item workflow including the
relation, event handlers, and menu items as needed.
4.  Optionally, you can set the EnableLineItemWaitSelectionto Yes if
you want to give the business user access to choose whether the lineitem workflow element should be wait for all line-item workflows to
complete before you move on to the next element.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-3
5.  Create a new Line-item workflow type under the Line-item
workflow that is created in step 2, and then select the Workflow type
for the line-item workflow. Thisstep constrains the line-item
workflow to only be available for the business user based on that
workflow type. Multiple line-item workflow types can be added if it
is required.
6.  Enable the common workflow userinterface elements at the line
level of the forms that the end-user will use to interact with the
header and line records.
Now, the business user can create a new workflow on the line-item table by using
the line-item workflow type, then create a new workflow on the header table by
using the header workflow type, and then configure the line-item workflow
element in the header workflow by selecting the line-item workflow he or she
just created.
TIP: You can review the Purchase requisition review workflow to see how steps
2, 3 and 4 are implemented for this workflow. (Open AOT > Workflow >
Workflow Types > PurchReqReview.)
Scenario: Line-Item Workflows
Isaac, the Business Systems Developer, has just finished creating a workflow for
purchase orders. He has also created all the classes, event handlers, and menu
items for a new purchase order line workflow. Now he must create the new
purchase order line workflow type and link it to the purchase order header
workflow.
NOTE: Before you can begin this demonstration, you must create a duplicate of
the PurchOrderHeaderTemplate.
To create a new purchase order line template, follow these steps.
1.  Open theDevelopment Workspace.
2.  Open the Projectswindow, and expand the Shared Projectsfolder.
3.  Right-click the LineItemWorkflowDemonstrationproject and
select Open.
4.  Right-click LineItemWorkflowDemonstrationand select New >
Workflow > Workflow type.
5.  Select the newly create WorkflowType1node, and open the
Propertieswindow.
6.  Set the Nameto PurchOrderLineTemplate.
7.  Set the CanceledEventHandlerproperty to
PurchLineTemplateEventHandler.
8.  Set the CancelMenuItemproperty to PurchLineWorkflowCancel.
9.  Set the Categoryto PurchCategory.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-4
10. Set the CompletedEventHandlerproperty to
PurchLineTemplateEventHandler.
11. Set the Documentproperty to PurchLineDocument.
12. Set the DocumentMenuItemproperty to PurchTable.
13. Set the Labelproperty to @SYS301073.
14. Set the HelpTextproperty to @SYS301074.
15. Set the StartedEventHandlerproperty to
PurchLineTemplateEventHandler.
16. Save the project.
To link a line-item workflow to a headerworkflow, follow these steps. In this
example, the PurchOrderLineTemplate will be added to the
PurchOrderHeaderTemplate.
1.  In the LineItemWorkflowDemonstrationproject, expand the
PurchOrderHeaderTemplateworkflow type.
2.  Right-click the Line-item Workflowsnode, and then selectNew
Line-item Workflow.
3.  Set the Nameproperty to PurchOrderLineTemplate.
4.  Set the CancelMenuItemproperty to WorkflowLineItemCancel.
5.  Set the EnableLineItemWaitSelectionproperty to No.
6.  Set the HelpTextproperty to @SYS301074.
7.  Set the Labelproperty to @SYS301073.
8.  Set the LineItemWorkflowRelationproperty to PurchLine.
9.  Right-click the Line-item Workflow Typesnode under the
PurchOrderLineTemplatenode, and then select New Line Item
Workflow Type.
10. In the LineItemWorkflowTypeproperty enter
PurchOrderLineTemplate.
11. Save the project.
Workflow Providers
Workflow providers in Microsoft Dynamics AX provide application specific data
for a workflow at run time. The application data provided can include the
following:
•  User IDs based on user groups.
•  Due dates based on employee or manager working days.
•  Specific user or manager IDs based on their maximum approval
limits.
•  Groups of users assigned to a specific work item queue.
The following topics describe the default workflow providers in Microsoft
Dynamics AX and how to implement them.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-5
Workflow Provider Overview
In Microsoft Dynamics AX, you can use workflow providers to provide
application-specific information to a workflow instance at run time. For example,
you can use workflow providers to determine who is required to approve an
invoice, or by which date an invoice payment is considered late. This topic
describes the default providers available in Microsoft Dynamics AX.
There are several types of workflow providers that you can implement in
Microsoft Dynamics AX workflow.
•  Hierarchy: Determines a user ID based on search in a hierarchy.
•  Due date: Determines the due date for a task or approval, or the due
date for a step in a task or approval.
•  Participant: Resolves a user group or role into one or more specific
user IDs.
•  Queue: Determines a queue name to assign the work item to. A
particular user that is assigned to that queue can then manually
accept or claim the work item. When a work item is accepted it will
no longer be possible for any other member of the queue to act on it,
unless it is delegated or released back to the queue.
Each task or workflow must have a duedate provider defined to determine the
last date by which the workflow element can be compeleted. For example, the
maximum number of days to complete a task, or the maximum time permitted to
wait for an approval before automatic denial of the approval.
A provider is also used to select a user orgroup of users for the task or approval
step. For example, the participant provider could select a manager from a
manager's role to approvean expense report. In Microsoft Dynamics AX 2012
the providers for a workflow element are inferred. There are no special
parameters that must be set on the elements in the AOT to specify the type of
provider. Each workflow element can have many different types of providers
available. However, only one type of provider can be selected when configuring
a workflow element.
The WorkflowHierarchyProvider.getNextNodemethod is called when an
approval or task is started to retrieve the identity of the user in the hierarchy that
should be assigned a work item.
The WorkflowHierarchyProvider.getNodeDataTypemethod is called when
the approval or task is started to return an object of the type the hierarchy
provider expects as input. Because each hierarchy provider implementation can
have a different input type, the input type is based on the type of hierarchy. For
example, an organizational hierarchy provider might return employee ID,
whereas a product hierarchy provider might return a product ID.
The WorkflowHierarchyProvider.convertToNodeDataTypemethod is called
at run time when an extended data type value must be converted to a data type
that the hierarchy supports as the start node.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-6
The WorkflowHierarchyProvider.convertUserIdToNodeDataTypemethod is
called at run time to convert a user ID value to a data type that the hierarchy
supports. When a reserved word is selected, such as workflow owner or
workflow originator, a user ID is passed.
The WorkflowHierarchyProvider.getSupportedDataTypemethod is called to
return the set of supported extended data types that the hierarchy provider can
convert into node data types. The set is displayed as a drop-down list in the user
interface.
Due Date Provider
You can use a due date provider to determine a specific due date for a task or
approval based on a specified start date. Microsoft Dynamics AX workflow
provides the WorkflowWorkCalendarDueDateProviderclass that returns the
date before which the workflow work item must be completed.
The due date provider can use the company calendar defined in the Basic module
to resolve a time span for a task or approval into a date that takes nonworking
days into consideration. For example, the default due date provider can calculate
the correct date for an expense report approval that should be approved within 10
workdays. Any holidays or non-working days specified in the calendar setup in
the Organization administrationmodule are calculated into the approval due
date.
The WorkflowWorkCalendarDueDateProviderclass implements the
WorkflowDueDateProvider interface that contains the following methods.
•  WorkflowDueDateProvider.getCalendarTokens
•  WorkflowDueDateProvider.resolve
•  WorkflowDueDateProvider.resolveNonUser
The WorkflowDueDateProvider.getCalendarTokensmethod is called from
the workflow configuration user interface so that the user can select a calendar
from the list of supported calendars. This method provides a list of the calendars
IDs from a calendar system, such as the calendar defined in the Organization
administration module's Calendarsform.
The WorkflowDueDateProvider.Resolvemethod is called when a task or
approval step is started to determine the due date of the step. For example, the
workflow configuration is set up to require an expense report approval within 10
work days. When the approval step or task is started, the due date provider's
resolve method is called to return the actual due date. The calendar ID specified
in the configuration user interface is passed into this method to resolve the time
span for a workflow work item into the due date for the work item based on the
calendar ID.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-7
The WorkflowDueDateProvider.resolveNonUsermethod is called to
determine the due date for the workflow element itself. In the configuration user
interface, this is the due date for Set a time limit for the task. This method is
implemented when you do not have a userto determine the maximum duration
for a work item.
Participant Provider
You can use a participant provider to return a list of users from any abstraction,
such as a user group. Microsoft Dynamics AX workflow provides the
WorkflowUserGroupParticipantProviderclass that returns a list of users
based on a Microsoft Dynamics AX user group.
The WorkflowUserGroupParticipantProviderclass implements the
WorkflowParticipantProviderinterface that contains the following methods:
•  WorkflowParticipantProvider.getParticipantTokens
•  WorkflowParticipantProvider.resolve
The WorkflowParticipantProvider.GetParticipantTokensmethod is called
from the workflow configuration user interface to display a list of supported
participant tokens. Participant tokens are IDs of user roles or user group names.
When you implement a customer provider,the participant token represents the
abstraction when you implement a different concept. For example, if you
implemented a new provider for commission groups, the IDs could represent the
commission group ID.
The WorkflowParticipantProvider.Resolvemethod is called when a task or
approval step is started to determine the specific user who will complete the step.
For example, the workflow configuration is set up to require the approver of a
step to be the purchasing manager. When the approval step is started, the
participant provider resolve method is called to return the user ID of a specific
purchasing manager.
Queue Provider
You can use a queue provider to return a list work item queues that are
configured in the Homemodule. Microsoft Dynamics AX workflow provides the
WorkflowQueueProviderclass that returns a list of work item queues.
The WorkflowWorkItemQueueProviderclass implements the
WorkflowQueueProviderinterface which contains the following methods:
•  WorkflowParticipantProvider.getQueueTokens
•  WorkflowParticipantProvider.queueIDToQueueName
•  WorkflowParticipantProvider.queueNameToQueueID
•  WorkflowParticipantProvider.resolve
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-8
The WorkflowParticipantProvider.getQueueTokensmethod is called from the
workflow configuration user interface to display a list of queue names for queuebased assignment.
The WorkflowParticipantProvider.queueIDToQueueNamemethod is called
to convert a workflow queue ID to a name.
The WorkflowParticipantProvider.queueNameToQueueIDmethod is called
to convert a workflow queue name to a workflow queue ID.
The WorkflowParticipantProvider.Resolvemethod is called when a task or
approval step is started to determine the specific queue to assign the step. For
example, the workflow configuration is set up to require the approver of a step to
be one of the purchasing agents that are all part of a queue called Purchasing.
When the approval step is started, the queue provider resolve() method is called
to return the queue ID.
Create Custom Workflow Providers
In Microsoft Dynamics AX, there are four default workflow providers. In some
cases, these default providers might not meet your application requirements. The
following procedure describes the steps that you have to implement a custom
workflow provider.
You must complete the following high level steps to implement a new workflow
provider.
1.  Create a "provider" class that contains the business logic for your
new provider.
2.  Create a new provider under the appropriate Providersnode in the
AOT, and then set the Name, Label, and HelpTextproperties.
3.  Specify the AssociationTypeproperty. This defines the
organizational scope of the provider.For example, organization wide
versus company specific. This requires that the business logic be
written in such a way that it respects the value of this property.
4.  Set the AvailableForAllWorkflowsTypesproperty.
a.  If a new provider is implemented for a specific workflow, then
set this property to No. Next, create new workflow types for
each type that the provider can be used for under the Workflow
Typesnode. This limits the visibility and use of the provider in
to the selected workflows.
b.  If a new provider is general purpose in nature and does not have
an affinity to a specific workflow, then set this property to Yes
and it will be available throughout Microsoft Dynamics AX.
5.  Set the ProviderClassproperty by selecting the name of the class
that is developed in step 1.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-9
Procedure: Create a Custom Workflow Provider
To create a new workflow provider, follow these steps.
1.  In the AOT, expand the Classesnode.
2.  Right-click the Classesnode, and then select New Class. A new
class group displays under the Classes node.
3.  Expand the new class, right-click classDeclaration, and then click
Edit.
4.  Enter the following code in the class declaration.
public class <MyCustomWorkflowParticipantProviderClassName>
implements WorkflowParticipantProvider
{
}
5.  Right-click in the Code Editorwindow, click New, and then enter
the following code for the getParticipantTokens method.
public WorkflowParticipantTokenList getParticipantTokens()
{
// Constructs the new user group list.
WorkflowParticipantTokenList userGroups =
WorkflowParticipantTokenList::construct();
;
// ToDo Define your user groups here.
return userGroups;
}
6.  Right-click in the Code Editorwindow, click New, and then enter
the following code for the resolve method.
public WorkflowUserList resolve(WorkflowContext _context,
WorkflowParticipantToken _participantTokenName)
{
// Declare the variables.
UserGroupList userGroupList;
WorkflowUserList userList =
WorkflowUserList::construct();
;
// Verify that the participant token is set or throw
an error.
if (!_participantTokenName)
throw error("@SYS105453");
// ToDo Enter code to add users to the user list.
{
userList.add(userGroupList.UserId);
}
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-10
return userList;
}
7.  Close the Code Editorwindow and then click Yesto save the
changes.
Work Item Queues
Microsoft Dynamics AX 2012 introduces the queue functionality that is used to
assign work items (from workflow) to specific groups of employees. Several
setup steps occur in the rich client including creating queue groups, queues, and
queue assignment rules. However, the developer must perform some actions to
make sure that the setup of a work item queue works correctly when it is selected
in a workflow elements configuration.
Developer Actions
The developer must complete the following high level steps to enable queues for
a document.
1.  Enable queues in the workflow document by setting the following
attribute on the workflow document class in the class declaration
WorkflowDocIsQueueEnabledAttribute(true,"<label>")
a.  <label> is the label ID that represents the business document
name.
b.  The business document name tells the workflow system that any
workflows based on this workflow document can have work
items generated that are assigned to a queue.
2.  Next, create a custom WorkflowQueueCreatedEventHandler
class. This is necessary to store additional data that is used when you
view the work items that are assigned to a queue in the user
interface.
a.  The custom class must derive from the base class
WorkflowQueueCreatedEventHandler
b.  You have to override the mapFields() method
HINT: For an example of how to implement this, refer to the
TrvDocumentQueuedTaskEventHandler class in AOT. The mapFields method is
overridden to set the DocumentID, Type and Company.
3.  Set the WorkItemsCreatedEventHandlerproperty on the task
element in AOT with the custom
WorkflowQueueCreatedEventHanderclass created previously.
This guarantees that it is used at run time.
4.  Create custom list page queries to allow for filters based on queue
assignment.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-11
5.  Bind the queries to the menu items for each list page. For example,
refer to the PurchReqwAllMyReportsand
PurchReqMyDirectReports Display Menu Itemsfor an example
of how this is achieved.
Scenario: Enable Queues for a Document
Isaac, the Business Systems Developer,has just finished creating a new
workflow for expense reports. Now, he canallow the expense reports tasks to be
assigned to a queue so that one of the accountants can review the expense
reports. He also wants to create two new list pages that will filter the expense
reports assigned to queues so that users can easily view expense reports that are
assigned to them or to their queues.
Demonstration: Enable Queues for a Document
To enable queues for a document, follow these steps.
1.  Open the Development Workspace.
2.  Select the document class or create a new document class for the
workflow document.
3.  Right-click the classDeclarationand select View Code.
4.  Decorate the method with the
WorkflowDocIsQueueEnabledAttribute.
The following code sample is an example of the TrvWorkflowExpHeader class
declaration which is decorated with the
WorkflowDocIsQueueEnabledAttribute (the first line) to enable queues for the
expense report workflow.
[
WorkflowDocIsQueueEnabledAttribute(true, "@SYS317210"),
ExpressionCurrencyFieldMapAttribute(methodstr(TrvWorkflowEx
pHeader, parmTotalExpenseAmount),
methodstr(TrvWorkflowExpHeader,
parmAccountingCurrencyCode)),
ExpressionCurrencyLEAttribute(tableStr(TrvExpTable),
fieldStr(TrvExpTable, LegalEntity)),
ExpressionCurrencyLEAttribute(tableStr(TrvExpTrans),
fieldStr(TrvExpTrans, LegalEntity)),
ExpressionCurrExchRateDateAttribute(tableStr(TrvExpTrans),
fieldStr(TrvExpTrans, TransDate))
]
class TrvWorkflowExpHeader extends WorkflowDocument
{
}
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-12
Demonstration: Create a Workflow Queue Event Handler
To create an event handler for managing the queue data in the user interface,
follow these steps.
1.  Right-click the Classesnode in the AOT, and then select New Class.
2.  Right-click the newly created class and select View Code.
3.  In the classDeclaration, create a name the class
<Workflow>DocumentQueuedTaskEventHandler where
<Workflow> is the name of the document that you are enabling
workflow for.
4.  Make sure that the class extends
WorkflowQueueCreatedEventHandler, and then save the class.
5.  Right-click the new class in the AOT, and then select Override
methodand select mapFields.
a.  Declare the Workflow macro.
b.  Declare the table that stores the data for your document.
c.  Declare the WorkflowDocIsQueueEnabledAttribute.
d.  Declare the DictClass.
e.  Set the DictClass equal to the class that is used for your
document workflow.
f.  Set the WorkflowDocIsQueueEnabledAttribute variable that you
created in step 5.c. equal to the WorkflowDocumentAttribute in
the Workflow macro.
g.  Set the document table variable created in step 5.b. to the record
that is currently selected.
h.  Set the parameters in the WorkflowQueueCreatedEventHandler
class equal to the fields from the table fields in the document
table that you declared in step 5.b.
The following code sample is an example of the
TrvDocumentQueuedTaskEventHandler class.
public class TrvDocumentQueuedTaskEventHandler extends
WorkflowQueueCreatedEventHandler
{
}
protected void mapFields()
{
#Workflow
TrvExpTable trvExpTable;
WorkflowDocIsQueueEnabledAttribute attribute;
DictClass dictClass;
dictClass = new
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-13
DictClass(classNum(TrvWorkflowExpHeader));
attribute =
dictClass.getAttribute(#WorkflowDocumentAttribute);
trvExpTable =
TrvExpTable::findRecId(this.parmWorkflowWorkitemTable().Ref
RecId);
this.parmDocumentId(trvExpTable.ExpNumber);
this.parmDocumentType(attribute.parmFriendlyName());
this.parmCompanyInfo(trvExpTable.company());
}
Demonstration: Link the Workflow Queue Event Handler
to the Workflow Type
After you have created an event handler for the work item queue, you have to
link the new event handler class to the taskor approval in the AOT. To link the
workflow event handler to a workflow task, follow these steps.
1.  In the AOT, expand the Workflownode, and then expand the Tasks
node.
2.  Select the task that you want to allow work item queues for, or if it
does not exist, create a new task and set the properties as required.
3.  Right-click the task and select Properties.
4.  Set the WorkItemsCreatedEventHandlerproperty to the event
handler class that you created in Demonstration: Create a Workflow
Queue Event Handler.
5.  Save the Task.
NOTE: Queues are not supported for approvalelements because the way users
interact with them is different than tasks.
Demonstration: Create a List Page Query for Queues
Next, you must create a query or multiple queries to filter the documents based
on the queue assignment. For example, you could create a query to filter for
expense reports that are assigned to the current user logged on (Expense reports
assigned to me), or to view all expense reports work items that are assigned to a
queue that the current user is a part of (Expense reports assigned to my
queues).
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-14
Work Items Assigned to Me
To create a query that filters for work items that are assigned to the current users,
join the WorkflowWorkItemTableand add a range on the UserIDfield and set
the Valueproperty to (UserID = currentUserID()). The following sample is
taken from the TrvExpTable_AssignedToMe query that controls the filter for the
Expense reports assigned to me form located in Travel and expense > Common
> Expenses > Expense reports assigned to me.
FIGURE 11.1 TRVEXPTABLE_ASSIGNEDTOME QUERY
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-15
Work Items Assigned to My Queues
To create a query that filters for work items that are assigned to a queue the
current users belongs to, join the WorkflowWorkItemQueueAssignee table and
add a range on the UserIDfield and set the Valueproperty to (UserID =
currentUserID()). The following sample is taken from the
TrvExpTable_AssignedToMyQueuesquery that controls the filter for the
Expense reports assigned to meform located in Travel and expense >
Common > Expenses > Expense reports assigned to my queues.
FIGURE 11.2 TRVEXPTABLE_ASSIGNEDTOMYQUEUES QUERY
For other examples of queries and list pages that you can add to a document,
refer to the Purchase requisitionlist pages that are located in Procurement and
sourcing > Common > Purchase requisitions.
Demonstration: Bind the Query to a Menu Item
The final step in the process is to create menu items that are bound to the query
that you created in Create a List Page Query for Queues demonstration. Then
you must add the menu item to the menu.
To create a menu item that is bound to your query, follow these steps.
1.  In the AOTexpand Menu Items.
2.  Right-click the Displaynode and select New Menu Item.
3.  Right-click the new menu item and select Properties.
4.  Enter a Namefor the menu item.
5.  Specify the Labeland the HelpText property for the menu item.
6.  Select the primary list page in the Objectproperty.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-16
7.  In the Queryproperty, specify the query that you created in the
Create a List Page Query for Queues demonstration.
8.  Specify the other properties as required and then save the menu item.
When you are finished, drag the menu item into the menu where you want the list
page to appear.
Currency in the Condition Editor
Earlier releases of Microsoft Dynamics AX do not include any support in the
Condition Editor used to compare amounts in different currencies. In Microsoft
Dynamics AX 2012, the Condition Editor is extended so that conditions can be
created when the currencies being used oneither side of the condition could be
different. Additionally, Microsoft Dynamics AX 2012 introduces the following
features.
•  The currency code can be obtained for a field on the left side of the
condition that contains an amount.
•  The end-user can select a currency code for an amount entered on the
right side of the condition.
•  The left and right side of the condition can be converted into a
common currency so that they can be evaluated.
The most basic approach to implementing currency fields in the Condition Editor
is to set meta-data that will be used by the default currency provider. This metadata is then used by the Condition Editor together with a default currency
provider without any additional development. This is true only when the
currency codefield is on the same table as the currency amountfield. In all
other cases, coding is required to either extend the default currency provider
implementation or to implement a new currency provider that meets your
application needs.
Scenario: Currency Code in the Record
In this example it is assumed that the currency codefield is stored in the same
table as the currency valueor amountfield. This is the most common scenario
and the following steps are required.
1.  Set the currency meta-data for the currency code field. Refer to the
Define Currency Meta Dataprocedure for more information.
2.  Review the behavior of the ExpressionCurrencyDefaultProvider
class to determine whether the requirements are met.
3.  If the ExpressionCurrencyDefaultProvider meets your requirements,
then no additional action is required.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-17
4.  If the ExpressionCurrencyDefaultProvider does not meet your
requirements, you must either:
a.  Extend the default provider. Refer to the Extend the Default
Currency Providerprocedure for more information.
b.  Implement your own provider. Refer to the Implement a New
Currency Providerprocedure for more information.
Scenario: Currency Code Associated to the Ledger
In this scenario, the Accounting currencyand Default exchange rate typeare
obtained from the Ledgerform associated with the legal entity that is referenced
by the record. There are two possible outcomes in this scenario dependent on the
SaveDataPerLegalEntityproperty on the table.
When the SaveDataPerCompanyproperty is set to Yes, no additional
development steps are required because the dataAreaIDfield will be
automatically set in the meta datato the default currency provider.
When the SaveDataPerLegalEntity property is set to No, then the legal entity is
represented by a field other than the dataAreaIDon the record. In this scenario
the developer must add an attribute to the workflow document class to identify
the table and field that stores the legal entity value.
[ExpressionCurrencyLEAttribute('<Query.DataSource.Name>','<
Field.Name>')]
NOTE: There are no additional steps required to implement this scenario.
However, this scenario will only be used if the method described in the Currency
Code scenario does not apply, and there is no calculated field that returns the
currency code.
IMPORTANT: A "global" or system currency codeis not supported in the base
implementation. Therefore, you must implement a new currency provider or
extend the default currency provider if this is a requirement.
Scenario: Currency Code ina Calculated Field or
Business Logic
If you have written application-specific business logic, or if you must obtain the
currency code by using a calculated field, you can extend the default currency
provider or implement a new currency provider.
When the currency to be used is not stored in same table or is calculated, you
must set the ExpressionCurrencyFieldMappingAttribute to be the field
(calculated or otherwise) from the workflow document that provides the currency
code. Use the following code sample to guide you.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-18
[
ExpressionCurrencyProviderAttribute(classstr(<Your>Currency
Provider),
ExpressionCurrencyFieldMappingAttribute('parm<CalculatedFie
ld1>', '<Field in the document’s root table>'),
ExpressionCurrencyFieldMappingAttribute('parm<CalculatedFie
ld2>', 'parm<CalculatedField3 representing the currency
code>')
]
class <yourWorkflowDocumentClass> extends WorkflowDocument
{
...
}
IMPORTANT: A relation must be defined on the field that stores the currency
codes. This relation is used by the system to create a lookup for currency codes
in the Condition Editor. If a relation does not exist, the ellipses buttonwill not
appear in the Condition Editor and the user cannot select the currency code from
a list.
Procedure: Define Currency Code Meta Data
To set the meta data for a currency amount field, follow these steps.
1.  Open the Development Workspace.
2.  In the AOT, expand Data Dictionary, and then right-click
Extended Data Typesand select New > Real.
3.  Enter a Nameand Labelfor the extended data type.
4.  Set the Extendsproperty to either Amountor AmountMST.
5.  Set the other properties on the extended data type as required.
6.  Save the extended data type.
NOTE: You can choose to skip steps 2 through 6 and just add the Amount or
AmountMST extended data types directly to your table.
7.  In the AOTexpand Data Dictionary, and the under the Tables node
select the table that you want to implement a currency for.
8.  Drag the extended data type that you created in step 2 into the table.
9.  Drag the CurrencyCodeextended data type into the table.
10. Create other fields on the table as required.
11. Save the table.
12. Right-click the Relationsnode on the table and selectNew >
Relation.
13. Enter a Namefor the relation such as Currency.
14. Select Currencyin the Tableproperty.
15. Set the other properties as required. Refer to the TrvExpTrans table
> Currencyrelation for an example of how to implement this.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-19
16. Right-click the relation created in step 12, and then select New >
Normal.
17. In the Fieldproperty, select the field that you created in step 9.
18. Set the Related fieldproperty to the CurrencyCodefield (which is
from the Currencytable).
19. If required, specify the SourceEDTproperty as the extended data
type for the Field.
20. Save the table.
Procedure: Extend the Default Currency Provider
The following developer actions are required to extend the default currency
provider.
1.  Create a class that extends ExpressionCurrencyDefaultProvider.
2.  Extend specific method(s) as needed based on your requirements.
Refer to the Implement a New Currency Providerprocedure for a list
of the methods that can be extended.
3.  Register the new class in the workflow document by using the
ExpressionCurrencyProviderattribute.
Procedure: Implement a New Currency Provider
To implement a new currency provider, follow these steps.
1.  Create a class that implements ExpressionCurrencyProvider.
2.  Implement the following methods:
a.  boolean isCurrencyEnabled: Used to determine whether the
field is currency enabled or not.
b.  getCurrencyCodeLookup: Used to display a currency code
lookup form and returns the selected currency code.
c.  getCurrencyCode: Used to return the currency code for a field,
for the current record.
d.  getExchangeDate: Used to obtain the date that is passed into the
currency conversion.
e.  getExchangeRateType: Used to obtain the exchange rate type
that is passed into the currency conversion.
f.  ConvertAmountField: Used to convert an amount value in the
fromFieldand fromField'scurrency code to the toField's
currency code. The converted amount is returned.
g.  ConvertAmountValue: Used to convert the fromAmountin
the fromCurrencyCodeto a value in the toCurrencyCode. The
converted amount is returned.
3.  Register the new class in the workflow document by using the
ExpressionCurrencyProviderattribute. Use the following code
sample as a guide.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-20
[ExpressionCurrencyProviderAttribute(classstr(<Your>Currenc
yProvider))]
class <YourWorkflowDocumentClass> extends WorkflowDocument
{
...
}
Example: Currency in the Condition Editor
The expense report document class, TrvWorkflowExpHeader, includes an
example of how some currency attributes are implemented. The following figure
displays the code in the class declaration which includes the attributes.
FIGURE 11.3 CLASSES\TRVWORKFLOWEXPHEADER – CODE EDITOR
FORM
Line 3 is the ExpressionCurrencyFieldMapAttributewhich is used to set the
currency code and currency value. The two parameters that are being passed in
are value and the currency code. In this example, there are two methods in the
class that define what the currency code and values are.
The parmTotalExpenseAmountmethod returns the total amount of the expense
report by calling the total() method on the TrvExpTablefor the record that is
passed in.
The parmAccountingCurrencyCodemethod returns the accounting currency in
the Ledgerform for the legal entity that is linked to either the expense line or the
expense header, depending on the record that is passed in. This method is also
decorated with the ExpressionFieldHideAttribute which is used to hide the
currency codefield in the Condition Editor. This prevents the user from
selecting a different currency than the currency that is selected on the transaction
that is passed in.
Lines 4 and 5 use the ExpressionCurrencyLEAttributewhich sets the legal
entity for a table that is passed in. The legal entity is used by the
ExpressionCurrencyDefaultProviderto perform the conversion in the
Condition Editor. Each data source in the document query that included amounts
that need currency conversion support must have their own attribute defined. In
this example, there are two data sources-one for the expense header
(TrvExpTable) and one for the expense lines (TrvExpTrans).
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-21
Line 6 uses the ExpressionCurrExchRateDateAttributewhich sets the
exchange rate date that will be used by the currency converter for making the
conversion from one currency to another. In this example the transDatefield
from the TrvExpTableis passed in.
This class also includes a method which returns the spending limit for the
requester. This method also includes the currency for the spending limit so that a
currency conversion can be complete when this field is selected in the Condition
Editor.
After you have implemented the classes and methods with the correct attributes,
you can use the Condition Editor in the workflow type to select or compare
amounts with relation and accuracy for the currencies. The following figure
illustrates two samples of how these fields can be used.
FIGURE 11.4 EXPENSE REPORT – WORKFLOW APPROVAL – CONDITION
PROPERTIES EXAMPLE
In this example, the first condition is comparing the total expense report amount
to the requesters spending limit. For both fields, the currency code is passed in
automatically based on the record passed into the query. There is no need for the
user to select a currency code.
The second condition in this example is comparing the total expense report
amount to a fixed value of 10,000 United States dollars (USD). The user can
click the ellipsis button (...) to specify the currency for the value that is entered
into the right side of the condition. The currency code is still hidden on the left
side of the condition because it is being calculated by the system in the
parmAccountingCurrencyCodemethod.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-22
Hierarchy Type Fields in the Condition Editor
Microsoft Dynamics AX 2012 supports adding fields and data that have a
hierarchical structure. Examples of these types of fields and data in the user
interface include the organization models and procurement categories.
When a field that has a hierarchical data structure is presented in the Condition
Editor for workflow, the comparison function should include operators such as
"at or above", "above", "at", "below", and "at or below".
Example: Procurement Category Hierarchies
Contoso has created a procurement category hierarchy that includes several
levels for the brands, types, and categories that each product belongs to. Each
buyer at Contoso is responsible for certain brands of products and is therefore
also responsible for the types and categories that are below the selected brand in
the hierarchy.
Now you are creating a new purchase requisition line-level workflow and want to
assign a task in the workflow based on the procurement category that is assigned
to each line of the purchase orders. When you add the procurement category field
to the left side of the condition, the operator for that condition can be set to "at or
below" which will include the brand selected on the right side of the condition
and all the types and categories that are below the brand selected.
The system uses the getLookup() method to display the hierarchy in the
condition, and then at run time the condition is evaluated by using the
getDistance() method.
Developer Actions
To implement a new field that supports hierarchies in the Condition Editor, the
developer must follow these steps.
1.  Create a new class that implements the
ExpressionHierarchyProviderbase class. This class must
implement the methods that are required to enable hierarchy support
in the Condition Editor
a.  getDistance(): Returns the distance from the target node to the
source node in a hierarchy. If a direct path from the source node
to the target node does not exist then a nonzero value must be
returned.
b.  getLookup(): Displays a lookup table that represents the
hierarchy from which the user can select a node. The lookup
table is typically the primary key table for this field in the
foreign key table.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-23
2.  Register the new class on the workflow document class that is used
by decorating the class with the following attribute:
[WorkflowHierarchyProviderAttribute
(classstr(MyHierarchyProviderImplementation), myTableId,
myFieldId)]
The parameters myTableIdand myFieldIdare needed to specify the
table and field within the data source for which this applies. At run time,
when the Condition Editor is invoked, and the hierarchy-enabled field is
selected on the left side of a condition, the Condition Editor will show a
set of hierarchical operators (at or above, above, at, below, at or below),
and will enable a lookup on the right side that allows the end-user to
choose a node in the hierarchy to compare the field on the left side
against.
Developer Actions
To implement a new field that supports hierarchies in the Condition Editor, the
developer must follow these steps.
1.  Create a new class that implements the
ExpressionHierarchyProviderbase class. This class must
implement the methods that are required to enable hierarchy support
in the Condition Editor
a.  getDistance(): Returns the distance from the target node to the
source node in a hierarchy. If a direct path from the source node
to the target node does not exist then a nonzero value must be
returned.
b.  getLookup(): Displays a lookup table that represents the
hierarchy from which the user can select a node. The lookup
table is typically the primary key table for this field in the
foreign key table.
2.  Register the new class on the workflow document class that is used
by decorating the class with the following attribute:
[WorkflowHierarchyProviderAttribute
(classstr(MyHierarchyProviderImplementation), myTableId,
myFieldId)]
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-24
The parameters myTableIdand myFieldIdare needed to specify the table and
field within the data source for which this applies. At run time, when the
Condition Editor is invoked, and the hierarchy-enabled field is selected on the
left side of a condition, the Condition Editor will show a set of hierarchical
operators (at or above, above, at, below, at or below), and will enable a lookup on
the right side that allows the end-userto choose a node in the hierarchy to
compare the field on the left side against.
Example: Hierarchy Type Fields in the Condition Editor
To see an example of how this is implemented, refer to the
PurchReqExpressionProvider class. This class contains the getDistance() and
getLookup() methods for a procurement category hierarchy field. This attribute is
then used in the PurchReqWFLineDocument class.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-25
Lab 11.1 - Workflow Workshop
The workflow workshop is designed to demonstrate from start to finish, how to
implement a new workflow that includes an approval element. In addition, the
workflow that is created will be added as a line-item workflow to another
workflow. It includes concepts covered in the Development III for Microsoft
Dynamics AX 2012 course in addition to conceptscovered in this chapter.
Estimated time to complete: 50 minutes
Scenario
Contoso uses Free Text Invoicesto manage service agreements with many
customers. Currently, workflow is only supported on the header level of the
document. Kevin, the Sales Manager, wants the sales representatives to approve
the free text invoices that are created by the Accounting Department by using the
free text invoice recurring invoice batch job.
Because each line of the free text invoice might be routed to a different sales
representative or might require different levels of approvals, Kevin would like to
implement workflow for each line of the free text invoice.
Kevin has also specified that the new line-item workflow for free text invoices
should include an approval element and the line-item workflow should support
work item queues.
Challenge Yourself!
By using the information that is provided in the scenario, create a new workflow
type for free text invoice lines called
CustFreeTextInvoiceLineWorkflowTemplate that includes a new approval
element. Make sure that you create a new statusfield on the lines of the free text
invoice and that you enable work item queues for the free text invoice template.
When you are finished, add the new free text invoice line workflow into the
CustFreeTextInvoiceTemplate as a line-item workflow.
Challenge Yourself: Posting Logic Extra Credit
Modify the free text invoice posting logic to make sure that the invoice cannot be
posted when one or more lines are not approved.
NOTE: There are no step by step instructions for completing this. For an
example of how this is implemented, refer to the Development III in Microsoft
Dynamics AX 2012 class for more information about how this would be
achieved.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-26
Need a Little Help?
1.  Create a new project named WorkflowWorkshop to store all the
objects that will be modified or created in this workshop.
2.  Create a new workflow statusfield on the free text invoice line table
by using the same extended data type that is used for the free text
invoice header.
3.  Add the new statusfield to the Free text invoice form.
4.  Create a new query to define the data that is used by the workflow.
5.  Run the Workflow Type Wizardto create a new workflow type.
6.  Complete the tasks that are documented by the wizard in the
compiler for the new workflow type.
7.  Run the Approval Wizardto create a new approval element for the
workflow.
8.  Complete the tasks that are documented by the wizard in the
compiler for the new workflow approval element.
9.  Add the approval element to the workflow type.
Step by Step: Create a Project
To create a project for the new workflow, follow these steps.
1.  Open the Development Workspace.
2.  Click the Projectsicon in the toolbar.
3.  Right-click the Shared Projectsnode, and then select New >
Project.
4.  Right-click the new project, and then select Properties.
5.  In the Propertieswindow set the Nameto WorkflowWorkshopLab.
6.  Double-click on the WorkflowWorkshop project to open the project
details.
Step by Step: Free Text Invoice Line Status
To implement a new statusfield in the free text invoice line table and the Free
text invoice form, follow these steps.
1.  In the AOT expand Data Dictionary > Tables, and then select the
CustInvoiceLinetable.
2.  Drag the CustInvoiceLinetable into the WorkflowWorkshop
project.
3.  Expand the CustInvoiceLinetable and then right-click the Fields
node.
4.  Select New > Enum.
5.  In the Propertieswindow for the new field, set the Nameto
WorkflowStatus.
6.  Set the Enumproperty to CustFreeInvoiceWFApprovalStatus.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-27
7.  Set the AllowEditand the AllowEditOnCreateproperties to No.
8.  Save the project.
9.  In the AOT expand Forms and then select the CustInvoiceTable
form.
10. Drag and drop the CustFreeInvoiceform into the project.
11. Right-click the project and then click Restore.
12. Expand Data Sources > CustInvoiceLines > Fields, and locate the
Workflow statusfield.
13. Browse to the lines grid on the form by expanding Designs > Design
> Tab:TabMain > Tab:TabPageDetails > Tab:TabDetails >
TabPage:CombinedViewTabPage > TabPage:CVFastTab >
TabPage:CVLinesFastTab > Grid:LinesGrid.
14. Drag the Workflow statusfield from the Data Sources node to the
last field on the grid.
15. Save the project.
Step by Step: Create a Query
To create a new query to use with the new free text invoice line document class,
follow these steps.
1.  In the AOT, right-click the Queriesnode and then select New
Query.
2.  Select the new query that is created, and then in the Properties
window set the Nameto CustFreeTextInvoiceLineDocument.
3.  Expand the query node and then right-click the Data Sourcesnode
and select New Data Source.
4.  Set the Nameproperty to CustInvoiceLine.
5.  Set the Tableproperty to CustInvoiceLine.
6.  Expand the CustInvoiceLinedata source and then right-click in the
Data Sourcesnode and select New Data Source.
7.  Set the Nameproperty to CustInvoiceTable.
8.  Set the Tableproperty to CustInvoiceTable.
9.  Set the Relationsproperty to Yes.
10. Expand the CustInvoiceTablenode.
11. Right-click the Fieldsnode under CustInvoiceLines and set the
Dynamicproperty to Yes.
12. Right-click the Fields node under CustInvoiceTableand set the
Relationsproperty to Yes.
13. Right-click the Fieldsnode under CustInvoiceTable and set the
Dynamicproperty to Yes.
14. Save the project.
15. Drag the new query into the WorkflowWorkshopLab project.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-28
Step by Step: Create a Workflow Type
To create a new workflow type by using the wizard, follow these steps.
1.  In the AOT, expand the Workflownode.
2.  Right-click the Workflow Typenode and then select Add-Ins >
Workflow type wizard.
3.  On the Workflow Wizardclick Next >.
4.  In the Namefield enter CustFTLineTemplate.
5.  In the Categoryfield, select CustCategory.
6.  Set the Queryproperty to CustFreeTextInvoiceLineDocument.
7.  Set the Document menu itemproperty to CustFreeInvoice.
8.  Click Next.
9.  Click Finish.
10. On the Workflow type createddialog box, click OK.
TIP: The code samples for this lab can be found in the
AX2012_ENUS_DEVIV_11_01_LAB_CODE.txtfile. You can copy and paste
these code samples intothe correct methods.
Next you must update the methods inthe CustFTLineTemplateEventHandler
created by the workflow wizard. Follow these steps to update the started method.
1.  In the Compilerwindow, double-click the message which reads
Write code to execute once the workflow is started.
2.  In the Code Editorwindow for the started() method enter the
following code.
public void started(WorkflowEventArgs _workflowEventArgs)
{
CustInvoiceLine custInvoiceLine;
RecId custInvoiceLineRecId;
custInvoiceLineRecId =
_workflowEventArgs.parmWorkflowContext().parmRecId();
ttsBegin;
select forUpdate custInvoiceLine where
custInvoiceLine.RecId == custInvoiceLineRecId;
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::Pending;
custInvoiceLine.update();
ttsCommit;
}
3.  Save the class.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-29
To update the canceled method, follow these steps.
1.  In the Compilerwindow, double-click the message which reads
"Write code to execute once the workflow is canceled".
2.  In the Code Editorwindow for the canceled() method enter the
following code.
public void canceled(WorkflowEventArgs _workflowEventArgs)
{
CustInvoiceLine custInvoiceLine;
RecId custInvoiceLineRecId;
custInvoiceLineRecId =
_workflowEventArgs.parmWorkflowContext().parmRecId();
ttsBegin;
select forUpdate custInvoiceLine where
custInvoiceLine.RecId == custInvoiceLineRecId;
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::Cancellation;
custInvoiceLine.update();
ttsCommit;
}
3.  Save the class.
To update the completed method, follow these steps.
1.  In the Compilerwindow, double-click the message that reads "Write
code to execute once the workflow is completed."
2.  In the Code Editorwindow for the completed() method enter the
following code.
public void completed(WorkflowEventArgs _workflowEventArgs)
{
CustInvoiceLine custInvoiceLine;
RecId custInvoiceLineRecId;
custInvoiceLineRecId =
_workflowEventArgs.parmWorkflowContext().parmRecId();
ttsBegin;
select forUpdate custInvoiceLine where
custInvoiceLine.RecId == custInvoiceLineRecId;
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::Completed;
custInvoiceLine.update();
ttsCommit;
}
3.  Save the class.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-30
To create a submit method for class CustFTLineTemplateSubmitManager, follow
these steps.
1.  In the Compilerwindow, double-click the message that reads "Write
code to execute once the workflow is submitted".
2.  In the Code Editorwindow, click New.
void submit(Args args)
{
// Variable declaration.
recId recId = args.record().RecId;
WorkflowCorrelationId workflowCorrelationId;
// Hardcoded type name
WorkflowTypeName workflowTypeName =
workflowtypestr(CustFTLineTemplate);
// Initial note is the information that users enter
when they
// submit the document for workflow.
WorkflowComment note ="";
WorkflowSubmitDialog workflowSubmitDialog;
CustInvoiceLine custInvoiceLine;
// Opens the submit to workflow dialog.
workflowSubmitDialog =
WorkflowSubmitDialog::construct(args.caller().getActiveWork
flowConfiguration());
workflowSubmitDialog.run();
if (workflowSubmitDialog.parmIsClosedOK())
{
recId = args.record().RecId;
CustInvoiceLine = args.record();
// Get comments from the submit to workflow
dialog.
note = workflowSubmitDialog.parmWorkflowComment();
try
{
ttsbegin;
workflowCorrelationId =
Workflow::activateFromWorkflowType
(workflowTypeName,
recId,
note,
NoYes::No);
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::Submitted;
// Send an Infolog message.
info("Submitted to workflow.");
ttscommit;
}
catch(exception::Error)
{
info("Error on workflow activation.");
}
}
args.caller().updateWorkFlowControls();
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-31
}
3.  Save the class.
4.  Close the Editorwindow.
To update the main method of CustFTLineTemplateSubmitManager, follow
these steps.
1.  In the Code Editorwindow, select the Mainmethod.
2.  Enter the following code sample into the method.
public static void main(Args args)
{
CustFTLineTemplateSubmitManager
CustFTLineTemplateSubmitManager;
CustFTLineTemplateSubmitManager = new
CustFTLineTemplateSubmitManager();
CustFTLineTemplateSubmitManager.submit(args);
}
3.  Save the class.
4.  Close the Code Editorwindow.
5.  Close the Compiler output window.
6.  Drag all of the objects from the Project
CustFTLineTemplateWFTypewindow into the Project
WorkflowWorkshopLabwindow.
7.  Close the Project CustFTLineTemplateWFTypewindow.
Step by Step: Create an Approval Element
To use the approval wizard to create a new approval element, follow these steps.
1.  In the AOT, expand the Workflownode.
2.  Right-click the Approvalnode and then select Add-Ins > Approval
wizard.
3.  Click Nexton the Workflow wizard form.
4.  Enter FreeTextLineApproval into the Namefield.
5.  Select CustFTLineTemplateDocument in the Workflow document
field.
6.  Select CustomerFreeTextInvoiceLine in the Document preview
field group.
7.  Select CustFreeInvoice in the Document menu item field.
8.  Click Next.
9.  Click Finish.
10. On the Workflow approval element createddialog box, click OK.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-32
Next you must update the methods in the FreeTextLineApprovalEventHandler
created by the workflow wizard. To update the canceled method, follow these
steps.
1.  In the Compilerwindow, double-click the message that reads "Write
code to execute once the workflow is canceled."
2.  In the Code Editorwindow for the canceled() method, enter the
following code.
public void canceled(WorkflowElementEventArgs
_workflowElementEventArgs)
{
CustInvoiceLine custInvoiceLine;
RecId custInvoiceLineRecId;
custInvoiceLineRecId =
_workflowElementEventArgs.parmWorkflowContext().parmRecId()
;
ttsBegin;
select forUpdate custInvoiceLine where
custInvoiceLine.RecId == custInvoiceLineRecId;
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::Cancellation;
custInvoiceLine.update();
ttsCommit;
}
3.  Save the class.
To update the completed method, follow these steps.
1.  In the Compilerwindow, double-click the message that reads "Write
code to execute once the workflow is completed."
2.  In the Code Editorwindow for the completed() method, enter the
following code.
public void completed(WorkflowElementEventArgs
_workflowElementEventArgs)
{
CustInvoiceLine custInvoiceLine;
RecId custInvoiceLineRecId;
custInvoiceLineRecId =
_workflowElementEventArgs.parmWorkflowContext().parmRecId()
;
ttsBegin;
select forUpdate custInvoiceLine where
custInvoiceLine.RecId == custInvoiceLineRecId;
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::Completed;
custInvoiceLine.update();
ttsCommit;
}
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-33
3.  Save the class.
To update the changeRequested method, follow these steps.
1.  In the Compilerwindow, double-click the message that reads "Write
code to execute once change is requested for the workflow."
2.  In the Code Editorwindow for the changeRequested() method,
enter the following code.
public void changeRequested(WorkflowElementEventArgs
_workflowElementEventArgs)
{
CustInvoiceLine custInvoiceLine;
RecId custInvoiceLineRecId;
custInvoiceLineRecId =
_workflowElementEventArgs.parmWorkflowContext().parmRecId()
;
ttsBegin;
select forUpdate custInvoiceLine where
custInvoiceLine.RecId == custInvoiceLineRecId;
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::ChangeRequested;
custInvoiceLine.update();
ttsCommit;
}
3.  Save the class.
To update the returned method, follow these steps.
1.  In the Compilerwindow, double-click the message that reads "Write
code to execute once the workflow is returned."
2.  In the Code Editorwindow for the returned() method, enter the
following code.
public void returned(WorkflowElementEventArgs
_workflowElementEventArgs)
{
CustInvoiceLine custInvoiceLine;
RecId custInvoiceLineRecId;
custInvoiceLineRecId =
_workflowElementEventArgs.parmWorkflowContext().parmRecId()
;
ttsBegin;
select forUpdate custInvoiceLine where
custInvoiceLine.RecId == custInvoiceLineRecId;
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::Rejected;
custInvoiceLine.update();
ttsCommit;
}
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-34
3.  Save the class.
To update the started method, follow these steps.
1.  In the Compilerwindow, double-click the message that reads "Write
code to execute once the workflow is started."
2.  In the Code Editorwindow for the started() method, enter the
following code.
public void started(WorkflowElementEventArgs
_workflowElementEventArgs)
{
CustInvoiceLine custInvoiceLine;
RecId custInvoiceLineRecId;
custInvoiceLineRecId =
_workflowElementEventArgs.parmWorkflowContext().parmRecId()
;
ttsBegin;
select forUpdate custInvoiceLine where
custInvoiceLine.RecId == custInvoiceLineRecId;
custInvoiceLine.WorkflowStatus =
CustFreeInvoiceWFApprovalStatus::PendingApproval;
custInvoiceLine.update();
ttsCommit;
}
3.  Save the class.
To update the class declaration, follow these steps.
1.  In the FreeTextLineApprovalApprovalElement project, expand the
FreeTextLineApprovalEventHandler class.
2.  Double-click the classDeclartion.
3.  In the Code Editorwindow for the classDeclaration enter the
following code.
class FreeTextLineApprovalEventHandler implements
WorkflowElementCanceledEventHandler,
WorkflowElemChangeRequestedEventHandler,
WorkflowElementCompletedEventHandler,
WorkflowElementReturnedEventHandler,
WorkflowElementStartedEventHandler
{
}
4.  Save the class.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-35
To delete the created and denied methods, follow these steps.
1.  In the FreeTextLineApprovalApprovalElementproject, expand
the FreeTextLineApprovalEventHandlerclass.
2.  Right-click the created() method and select Delete.
3.  On the Confirm removedialog box, click OK.
4.  Right-click the denied() method and select Delete.
5.  On the Confirm removedialog box, click OK.
6.  Save the class and then close the Code Editor windows.
7.  Drag all of the objects from the Project
FreeTestLineApprovalElementwindow into the Project
WorkflowWorkshopLabwindow.
8.  Close the Project FreeTestLineApprovalElement window.
9.  Close the Compiler outputwindow.
Next, you must add the approval element to the workflow type. To add the
approval element to the workflow type, follow these steps.
1.  In the AOTwindow expand Workflows > Workflow Types.
2.  Expand the CustFTLineTemplate node.
3.  Drag the FreeTextLineApprovalfrom the
FreeTextLineApprovalApprovalElement project into the Supported
Elementsnode.
4.  Save the workflow type.
Next, you must add the new free text invoice line template to the free text invoice
header template so that it is available as a line-item workflow. To add the line
template to the header template, follow these steps.
1.  In the AOTwindow expand Workflows > Workflow Types.
2.  Locate the CustFreeTextInvoiceTemplateand drag it into the
WorkflowWorkshopLabproject.
3.  Expand the CustFreeTextInvoiceTemplate, and then right-click the
Line Item Workflowsnode of the CustFreeTextInvoiceTemplate
and select New Line Item Workflow.
4.  Set the Nameproperty to CustFTLineTemplate.
5.  Set the Labelto Free text invoice line.
6.  Expand the new CustInvoiceLinenode and then right-click the Line
Item Workflow Typesnode and then select New Line Item
Workflow Type.
7.  In the LineItemWorkflowTypeproperty, select
CustFTLineTemplate.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-36
8.  Save the project.
9.  Compile the project and verify that there are no errors. There will be
one Task, which can be ignored.
10. In the Development Workspace, click Build > Generate
Incremental CIL.
TIP: You can import the AX2012_ENUS_DEVIV_11_01_LAB_SOL.xpo file to
verify and compare your solution.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-37
Summary
Workflow in Microsoft Dynamics AX 2012 supports many new advanced
features. The line-item workflow types are used to create a workflow for data that
has a header and line relationship.
Additionally, the workflow provider framework gives developers the flexibility
to assign workflow elements to participants, queues, and users in a hierarchical
structure.
This chapter also reviewed the classes and attributes that can be called and
extended by the developer to present currency and hierarchy type fields in the
Condition Editor.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-38
Test Your Knowledge
Test your knowledge with the following questions.
1.  Put the following steps for developing a new work item queue in order:
Step:
_____: Add the menu item on the main menu.
_____: Create a new menu item.
_____: Create a new query.
_____: Override the mapFields() method.
_____: Set the query property on the menu item.
_____: Set the WorkItemsCreatedEventHandler property on the approval or
task element.
_____: Create a new class that extends
WorkflowQueueCreatedEventHandler.
_____: Add the WorkflowDocIsQueueEnabledAttribute attribute to the
workflow document.
2.  Categorize the following items:
_____ 1. Used to provide a specific end item, when
a particular starting item is provided.
_____ 2. Used to determine a specific due date for
a task or approval based on a specified start date.
_____ 3. Used to provide a list of users from any
abstraction, such as a user group.
_____ 4. Used to provide a list of users from a
work item queue that is configured in the Home
module.
a.  Due Date Provider
b.  Participant
Provider
c.  Queue Provider
d.  Hierarchy
Provider
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-39
3.  Describe the difference between the getDistance() and getLookup() method
in a class that implements the ExpressionHierarchyProvider class.
4.  Describe why you would set the EnableLineItemWaitSelectionto Yes on a
line-item workflow.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-40
Quick Interaction: Lessons Learned
Take a moment and write down three key points you have learned from this
chapter
1.
2.
3.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Chapter 11: Workflow
11-41
Solutions
Test Your Knowledge
1.  Put the following steps for developing a new work item queue in order:
Step:
8  : Add the menu item on the main menu.
6  : Create a new menu item.
5  : Create a new query.
3  : Override the mapFields() method.
7  : Set the query property on the menu item.
4  : Set the WorkItemsCreatedEventHandler property on the approval or
task element.
2  : Create a new class that extends
WorkflowQueueCreatedEventHandler.
1  : Add the WorkflowDocIsQueueEnabledAttribute attribute to the
workflow document.
2.  Categorize the following items:
d 1. Used to provide a specific end item, when a
particular starting item is provided.
a  2. Used to determine a specific due date for a
task or approval based on a specified start date.
b 3. Used to provide a list of users from any
abstraction, such as a user group.
c  4. Used to provide a list of users from a work
item queue that is configured in the Home module.
a.  Due Date Provider
b.  Participant
Provider
c.  Queue Provider
d.  Hierarchy
Provider
3.  Describe the difference between the getDistance() and getLookup() method
in a class that implements the ExpressionHierarchyProvider class.
MODEL ANSWER:
getDistance(): Returns the distance from the target node to the source node in
a hierarchy. If a direct path from the source node to the target node does not
exist then a nonzero value must be returned.
getLookup(): Displays a lookup table that represents the hierarchy from
which the user can select a node. The lookup table is typically the primary
key table for this field in the foreign key table.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement
Development IV in Microsoft Dynamics
®
AX 2012
11-42
4.  Describe why you would set the EnableLineItemWaitSelectionto Yes on a
line-item workflow.
MODEL ANSWER:
If you want to give the business user access to choose whether the line-item
workflow element should be wait for all line-item workflows to complete
before moving on to the next element.
Microsoft Official Training Materials for Microsoft Dynamics
®
Your use of this content is subject to your current services agreement

No comments:

Post a Comment

Labels

#veryusefulcode (1) AIF (8) AOT Maps (1) Args (1) Ax 2009 Reports (2) AX 2012 navigation (1) Ax 2012 Interview Questions (1) AX 7 (2) AX Architecture (1) Ax Backup (1) AX Workflow (2) AX2012 (1) AX2012 R2 (1) Ax2012R3 (1) AX2012R3 Dynamics Connector Step by Step Installation and Configuration (1) AX2012R3 EP Step by Step Installation and Configuration EP R3 (1) AX2012R3 HelpServer Step by Step Installation and Configuration (1) AX2012R3 Rapid Start Connector Step by Step Installation and Configuration (1) AX2012R3 Report Server and Analysis Server Step by Step Installation and Configuration (1) AX7 (1) Best practices (1) Blocking user to enter (1) Collection Classes (1) Container (1) D365FO (3) Data Migration Frame Work ax 2012R3 (1) Deleting duplicate Record from Table – Ax2012 (1) Delivery due date notification workflow in Ax 2012 (1) Development Steps EP (1) Dimensions (1) DIXF (1) DMF in Ax 2012 R3 (1) Dynamics Ax 2012 Interview Questions (1) DYNAMICS AX 2012 INTERVIEW QUESTIONS PART 2 (1) DYNAMICS AX 7 (1) EDT relation Migration Tool (1) EP AX 2012 (1) Ep Lookup (1) Error (1) Event Handler (1) F5 (1) File Handling (4) Filter on AX2012 Listpage (1) filtering (2) financial dimensions in AX 2012 (3) form (1) images (1) Installation and Configration (4) Installation and Configuration (11) Installation of Management Reporter 2012 for AX 2012 (1) Interaction class in ax 2012 (1) Interview Question (1) Interview Questions For Ax 2012 (1) Invent DIm (1) Jobs (2) license (1) List page and form menuitem enable code (1) Methods (1) microsoft Dynamics AX 365FO (1) Number Sequence Generation – AX 2012 (5) Number Sequence2012 (1) OLTP-OLAP (1) Passing Args (1) Passing form caller and menu item caller in ax 2012 (1) Passing Multiple Records Args (1) Posting in Ax 2012 (1) POSTING PURCHASE ORDER (1) Query (1) Query Filter Form (2) Query Ranges in X++ (1) Question and Answer (1) Report (1) Reports Controller class (1) RLS in ax 2009 (1) SALES ORDER IMPORT/EXPORT FRAMEWORK BY DMF (1) Security (1) security roles (1) Security Sysqueryrangeutil (1) Sharepoint 2016 (1) SQL SERVER (1) SSRS (2) SSRS Reports Controller class (2) Table collections & Virtual company (1) Time (1) TIPS AND TRICKS (1) Web service AIF (3) Web Services on IIS (AIF) Step by Step Installation and Configuration (1) workflow ax2012 (1) Workflow installation (1) Workflow Method (3) X++ (1)