Skip navigation
Share This:

Inspired by Paula Drew's question Auto create a Problem ticket, this article walks you through creating a Flow and a Process, two of Salesforce’s most powerful clicks-not-code development tools, to auto-create a Problem from an Incident. Credit  goes to Bryan Heidenreich as he developed a similar solution for our use at Fruit of the Loom, Inc. to auto-create problems for every priority 1 incident.

 

If this is your first time using Flows or Processes, I highly recommend you check out these great tutorial resources:

 

First, we’ll create a Flow that will use two Record Create elements to create a new Problem record copying over fields from the original Incident then create an Incident-Problem link record to associate them together. After defining the Flow, we’ll create a Process (instead of workflow rule) to monitor the incident object for changes we’re interested in and launch our Flow when appropriate.

 

Go to Setup | Create | Workflows & Approvals | Flows

1.png

Click the New Flow button

2.png

In the flow designer, on the left sidebar, switch to Resources panel and double-click SObject Variable to create a new input variable for the flow. Later when we setup the Process that monitors for when the incident records are closed (or whatever your criteria is), the Process will pass the incident record to the flow referenced as this flow variable. This variable will allow the rest of the flow steps to know the incident’s fields to use them when creating a new Problem record.

3.png

In the pop-up screen, name the variable varIncident (as convention, I always prefix my flow variables with ‘var’). Make sure the Input/Output Type is Input Only. Set the Object Type to BMCServiceDesk__Incident__c (this is the API name of the Incident object). Click OK button.

4.png

In the flow designer, on the left sidebar, switch to the Palette panel and drag the Record Create element to the canvas on the right.

5.png

Give this flow step a name like Create Problem. In the Assignments section, type the API name of the Problem object BMCServiceDesk__Problem__c.

6.png

Next, choose assignments for each of the Problem object’s fields you want to set when this record is created. In this example, we copy the incident’s category, impact, urgency, description, and ownerId. We set the Problem Source field to text value “Incident”.

7.png

At the bottom of this screen, we need to define which flow variable we want the newly created Problem record ID to be stored in so that we can reference it in our next flow step to actually link the incident and problem records together.

8.png

Click the drop-down arrow to the right of the field, some new options will appear. Click CREATE NEW then choose Variable.

9.png

Type the name of this new variable as varProblemId then click OK. We can leave the Input/Output Type as Private because no other operations outside of this flow need to use this variable.

10.png

Click the OK button and the variable screen will close and you should now see {!varProblemId} in the Variable assignment back on the Record Create screen we were working in. Now click the OK button to close the window.

11.png

So far, our flow canvas should have one Record Create element on it:

12.png

Now drag another Record Create element from the Palette onto the canvas below the existing “Create Problem” flow step we just configured. We will use this element to create the “incident problem link” record. Give this step the name Link Incident to Problem and type BMCServiceDesk__Incident_Problem_Link__c in the Create form field. In the Assignments section, set the FKIncident and FKProblem fields to the {!varIncident.id} and {!varProblemId} respectively as shown in this next screen shot. Since we won’t need the ID of this linkage record for any other parts of this flow we can skip the last step “Assign the record ID to a variable” and just click the OK button.

13.png

Our flow canvas should look like the below screenshot when two Record Create elements. Like any flow chart, we need to specify where we start and how the actions should flow from one step to the other.

14.png

With your mouse, hover the “Create Problem” step. Three new icons appear, click the green circle to indicate this is the start element. Next, with your mouse click the diamond at the bottom of the “Create Problem” step and drag onto the “Link Incident to Problem” step. This tells the Flow that when it is invoked that processing should begin in the “Create Problem” step then go to the “Link Incident to Problen” step. Finally, click the Save button in the upper-left of the screen to save our flow.

15.png

On the save flow screen, give your flow a name like BMCRF – Create and Link Problem to Incident Flow (I prefix my flow names with BMCRF to let me know this is for BMC’s RemedyForce) then click OK button. The other text fields will auto-generate based on what you enter into the name field.

16.png

Make sure to Activate this flow. Pull up the detail page of the newly created flow in Setup and click the Activate link as shown below. Only active flows can be invoked by Processes, which is what we will configure next.

17.png

We’re halfway done! Now go back to Setup so we can create the Process that will invoke this Flow.

 

Go to Setup | Create | Workflows & Approvals | Process Builder

18.png

On the Process Builder page, click the New button in upper-right. Give your process a Name like BMCRF – Create Problem from Incident and a description of the purpose of this flow. The API Name will auto-generate from the Name you provided. Click Save button.

19.png

The flow canvas will appear. Click Add Object in the upper-left of the process flow.

20.png

In the Object field of the form that appears on the right, type Incident then choose when this process should be triggered. In this example, we choose “when a record is created or edited” so that we can check for criteria when the incident becomes closed (or whatever criteria you might have when you want a Problem record to be created). Click Save button.

21.png

Now we need to add some criteria to control when our actions will occur. If you’re familiar with workflow rules, this is like setting up the evaluation criteria for when the workflow rule should run. Click the Add Criteria button on the process canvas.

22.png

Give this criteria step a name, like “State Closed”. Choose to execute actions when “filter conditions are met”. Add criteria condition when the “State Open” field equals False. Then, to make sure this action only is invoked when the incident first changes from state “open” to “closed”, check the last checkbox indicating we only want this action processed when “specified changes are made to the record”. This means that if the incident is already closed and it somehow is updated again then this action won’t run (i.e. won’t create more and more problem records from an already closed incident). Click Save button.

23.png

24.png

In the Immediate Actions section for when this criteria step evaluates to true, click Add Action.

25.png

Choose Flows as the Action Type. Give a name of this action like Create Problem from Incident then choose our flow we created earlier in this article. At the bottom of that form it tells us we can set flow variable values. This is great because we want to pass in a reference to the incident evaluated in this Process to our Flow (remember the varIncident variable we created at the beginning?). Click the Add Row button.

26.png

The screen now asks us which flow variable we want to set. You will only see flow variables with Input/Output Type of either Input Only or Input/Output shown here. Select our varIncident variable.

27.png

For the value, click the search field on the right and a new screen will pop-up similar to when we were adding criteria. Instead of choosing a field, simply click the API object name BMCServiceDesk__Incident__c then click the Save button. That window will close and you’ll see that our varIncident variable is now referencing the incident object – the value will be the incident being evaluated by this process and will be passed to the flow. Click the Save button to save this action step.

28.png

29.png

We’re done configuring our Process, now click the Activate button in the top-right of the page.

30.png

Now it’s time to test out our new Process and Flow! Go to Remedyforce Console and create a new incident.

31.png

Now close the incident (or make some edit that matches the criteria you used when defining your Process).

32.png

Make sure you’ve added the Linked Problems related list to your incident page layout. You should now see your new problem record in the Record Details section!

33.png

Share This:

Some Background Info:

 

Inspired by this idea https://communities.bmc.com/ideas/2124 to automatically have incidents assigned to current user by taking some action on the incident. This solution uses a workflow rule and flow to automatically assign current user as staff and set responded date to "now" whenever the Status field changes from OPENED to any other stage (e.g. acknowledged, in process, closed). Another great approach is to provide users a custom action to invoke the flow with any custom logic as done by Mike Leveiller here https://communities.bmc.com/ideas/2124#comment-49445

 

**Please note, as of December 2014, Salesforce has a private beta feature called Processes which will supersede Workflow Rules and Flow Triggers. However, since it is in beta, my instructions still reference the traditional Workflow Rules and Flow Trigger mechanics. Just FYI in case you read these instructions then read Salesforce documentation and the docs recommend doing this via their Process Builder instead.

 

What we'll be doing in this setup:

 

  1. Create one (1) flow with the logic to assign current user as staff and set responded date of the incident
  2. Create one (1) flow trigger to invoke the flow and pass parameters
  3. Create one (1) workflow rule on incident object to invoke the flow trigger

 

Step 1: Create Flow

 

The quickest way to get this flow setup in your sandbox is to deploy it from my github repository. Once deployed, make sure to go to Setup | Create | Workflows & Approvals | Flows to activate it.

 

This flow will assign the current user as the Staff field of the incident under two conditions: the user belongs to the incident's queue and the staff field is blank. It also will set the Responded Date field to "now" if it is blank. This logic of course is completely customizable to your purposes.

 

screenshot

 

Step 2: Create Flow Trigger

 

  1. Go to Setup | Create | Workflows & Approvals | Flow Triggers
  2. Click New Flow Trigger button
  3. Choose Incident object then click Next button
  4. Specify a name for the flow trigger (e.g. "Auto Assign Acknowledged Incidents")
  5. Choose the flow you created in Step 1
  6. Check the option to Set Flow Variables
  7. Specify the incidentId input variable to be the value {!id} This is the incident record id to update in the flow.
  8. Specify the assignToId input variable to be the value {!$User.Id} This is the id of the current user that caused the workflow to run and who the flow will try to assign as Staff on the incident.
  9. Finish saving the flow trigger

 

 

Step 3: Create Workflow Rule

 

  1. Go to Setup | Create | Workflows & Approvals | Workflow Rules
  2. Click New Rule button
  3. Choose Incident object then click Next button
  4. Specify a name for the workflow rule (e.g. "Auto Assign Acknowledged Incidents")
  5. Set the evaluation criteria to "created, and any time it's edited to subsequently meet criteria"
  6. Set the rule criteria to be Incident: Stage~ not equal to Opened
  7. Save workflow rule
  8. Edit the Workflow Actions section
  9. Click the Add Workflow Action drop down button and choose Select Existing Action
  10. Choose the Flow Trigger created in Step 2
  11. Finish saving the workflow rule and activate it

 

 

Share This:

Some Background Info:

 

Inspired by this idea Open records in respective console when select "Recent Items" list and discussion aroundIncident and Task Consoles and how to ensure any URLs (e.g., from search results, recently viewed, look up fields, etc) to an incident, task, problem, change request, release, etc appear in the console rather than the standard Salesforce tabs. The solution is fairly simple and straight forward, create a visualforce page per object type (incident, problem, etc) that inspects url parameter then redirects to the console page.

 

What we'll be doing in this setup:

 

  1. Create one (1) visualforce page per object type (incident, problem, etc) with javascript to redirect to console page
  2. Customize the incident object (or problem, etc) to override the default view, edit, and new actions to open our new visualforce page

 

Step 1: Create Visualforce Pages

 

You will need to create a visualforce page for each object (incident, problem, etc) whose standard salesforce urls should redirect to the Remedyforce Console. I provide the setup for Incidents, Problems, and Change Requests below. Note in the <apex:page> tag that we turn off the header, sidebar, stylesheets, and chat. This is for performance improvements so that we reduce as much 'overhead' as we can so the redirect occurs as quickly as possible.

 

  1. Go to Setup | Develop | Pages
  2. Click New button
  3. Copy the below code and configurations
  4. Save page
  5. Repeat steps 1-4 for each object (incident, problem, change, etc.)

 

Incident Page Redirect

 

Label: BMCRF Console Incident Page Redirect

Name: BMCRF_Console_Incident_Page_Redirect

Description: Visualforce page for overriding the standard page actions ('new', 'view', 'edit') for Incidents so that they open in the Remedyforce Console rather than standard detail page. https://communities.bmc.com/ideas/4988

 

<apex:page standardController="BMCServiceDesk__Incident__c" showHeader="false" standardStylesheets="false" showChat="false" sidebar="false">

<script type="text/javascript">
  
    location.href = '{!$Page.BMCServiceDesk__RemedyforceConsole}?record_id={!$CurrentPage.parameters.id}&objectName=Incident__c';

</script>

</apex:page>


 

 

Problem Page Redirect

 

Label: BMCRF Console Problem Page Redirect

Name: BMCRF_Console_Problem_Page_Redirect

Description: Visualforce page for overriding the standard page actions ('new', 'view', 'edit') for Problems so that they open in the Remedyforce Console rather than standard detail page. https://communities.bmc.com/ideas/4988

 

<apex:page standardController="BMCServiceDesk__Problem__c" showHeader="false" standardStylesheets="false" showChat="false" sidebar="false">

<script type="text/javascript">

    location.href = '{!$Page.BMCServiceDesk__RemedyforceConsole}?record_id={!$CurrentPage.parameters.id}&objectName=Problem__c';

</script>

</apex:page>

 

 

Change Request Page Redirect

 

Label: BMCRF Console Change Page Redirect

Name: BMCRF_Console_Change_Page_Redirect

Description: Visualforce page for overriding the standard page actions ('new', 'view', 'edit') for Change Requests so that they open in the Remedyforce Console rather than standard detail page.

https://communities.bmc.com/ideas/4988

 

<apex:page standardController="BMCServiceDesk__Change_Request__c" showHeader="false" standardStylesheets="false" showChat="false" sidebar="false">

<script type="text/javascript">

    location.href = '{!$Page.BMCServiceDesk__RemedyforceConsole}?record_id={!$CurrentPage.parameters.id}&objectName=Change_Request__c';

</script>

</apex:page>

 

Step 2: Customize Object Actions

 

  1. Go to Setup | Create | Objects then click link for Incidents
  2. Scroll down to the "Buttons, Links, and Actions" section
  3. Click edit link for the Edit action then change the Override with and choose Visualforce Page option then select the visualforce page you created earlier
  4. Click Save button
  5. Repeat the action overrides in step 3 and 4 for both labels View and New
  6. Repeat steps 1-5 for the other objects (Problems, Change Requests, etc.)

 

Share This:

Some Background Info:

 

As of this writing, Salesforce provides no way of reporting on who belongs to which queues. To know who is a queue member, you must either (a) go to the Salesforce Setup page to manage the queue or (b) run a SOQL query and join on groupmember object then export the data using Data Loader or Enabler for Excel. But wouldn't it be great if there was an easier way? Something like the Staples® Easy Button™?

 

(A) Queue Setup Page

queuesetuppage.PNG

 

(B) SOQL Example


SELECT
     id, name, username, isActive
FROM
     user
WHERE
     id IN ( SELECT userOrGroupId FROM groupmember WHERE groupId = :groupId )
ORDER BY
     name

 

 

The Solution: Visualforce and Apex

 

staples_easy_button.jpg

 

Inspired by Chris Kress' post asking how to write a SOQL query to get a list of users assigned to queues, I put together some basic visualforce pages to demonstrate how to use the query and to conveniently export user records to Excel.

 

The source code and deployment options are available on my github repository: https://github.com/DouglasCAyers/sfdc-queue-members-excel. It contains a controller class for executing the SOQL to get queues and users, a test class with 100% code coverage for easy deployment into production orgs, a visualforce page for selecting a queue and viewing its members, and a visualforce page that renders the same queue members list in Excel.

 

The great thing is that this requires no special libraries or third-party code, it's all standard Salesforce functionality. Just too bad actually reporting on queue members isn't a standard report option.

Share This:

Some Background Info:

 

Our company wanted to notify via email the incident assigned staff (Incident: Staff) whenever someone else added action history (eg, added note, sent email, email received, etc). This is to help keep the assigned staff aware that updates have been received or new notes added without the technician actively monitoring the incident console.

 

Since we use both Queue and Staff assignments on our Incidents, the steps outlined here Notify technician when incident is updated via email did not work out of the box. However, if you only support single assignment on Incidents, those steps should work. The reason is because with Queue and Staff assignments enabled, the Incident Owner field always references the Queue. This is important to note when you're trying to wire up the Workflow Email Alerts.

 

The dilemma is that on the Incident History object, the Staff field is not the same as the parent Incident: Staff field but rather is the logged-in user who added the note/action history record. I have no clue why. This confused me for a long time and caused a lot of troubleshooting headache. Secondly, when creating the Email Alert on the Incident History object, there is no option to choose the Staff field from the parent Incident. So you're stuck with either sending the email to the queue (Incident: Incident Owner) or sending the email back to the person who added the note (Incident History: Staff ID). Neither of these were acceptable, so I had to keep digging.

 

My workaround was to introduce two (2) new custom fields on the Incident History object. One is an Email type field that a workflow field update will copy the parent Incident Staff's email address into. The other is a Checkbox type field that workflow field updates will toggle on/off.

 

 

What we'll be doing in this setup:

 

  1. Create two (2) custom fields on Incident History object as mentioned above
  2. Create one (1) email template
  3. Create one (1) workflow email alert
  4. Create three (3) workflow field updates
  5. Create two (2) workflow rules

 

 

Step 1 - Create Custom Fields

 

Notify Staff Comment Added Controller
custom_controller_field.PNG.png

Object: Incident History

Field Label: Notify Staff Comment Added Controller

Data Type: Checkbox

Default Value: Unchecked

 

Incident Assigned Staff Email

custom_email_field.PNG.png

Object: Incident History

Field Label: Incident Assigned Staff Email

Data Type: Email (must be email type so can choose it in email alert we create later)

Default Value: Blank

 

 

Step 2 - Create Email Template

 

Nothing fancy here. Just create a new email template that uses merge fields from the Incident History object. The email alert we create in the next step will reference this email template.

 

 

Step 3 - Create Workflow Email Alert

 

email alert.PNG.png

Object: Incident History

Description: custom_notify_staff_incident_comment_added

Email Template: The template you created in step 3

Recipient: Email Field: Incident Assigned Staff Email (custom field created in step 1)

 

 

Step 4 - Create Workflow Field Updates

 

Set Notify Staff Comment Added Controller
set controller field update.PNG.png

Object: Incident History

Field to Update: Incident History: Notify Staff Comment Added Controller

Field Data Type: Checkbox

Re-evaluate Workflow Rules: Checked (Very important! When a new incident history record is created, we need one workflow rule to run and copy email address into our custom field THEN have workflows run again so that the second workflow can use the email in its email alert. This has to be the order of operations to enforce the email field is copied over before the email alert fires. If you try to use one workflow rule that has a field update to copy the email address and uses the email alert then you leave it up to chance whether the email alert will fire before the email address is ever copied over.)

New Field Value: True

 

Clear Notify Staff Comment Added Controller
clear controller field update.PNG.png

Object: Incident History

Field to Update: Incident History: Notify Staff Comment Added Controller

Field Data Type: Checkbox

Re-evaluate Workflow Rules: Unchecked

New Field Value: False

 

Set Incident Assigned Staff Email
set inc hist email field update.PNG.png

Object: Incident History

Field to Update: Incident History: Incident Assigned Staff Email

Field Data Type: Email

Re-evaluate Workflow Rules: Unchecked

New Field Value: BMCServiceDesk__FKIncident__r.BMCServiceDesk__FKOpenBy__r.Email

 

 

Step 5 - Create Workflow Rules

 

Set Notify Staff Comment Added Controller
workflow set values.PNG.png

Object: Incident History

Name: Set Notify Staff Comment Added Controller

Evaluation Criteria: When a record is created

Rule Criteria: Only runs if staff is assigned to incident -AND- the person creating the incident history record is not the same person

AND(

  NOT( ISBLANK( BMCServiceDesk__FKIncident__r.BMCServiceDesk__FKOpenBy__c ) ),

  BMCServiceDesk__FKIncident__r.BMCServiceDesk__FKOpenBy__c <> BMCServiceDesk__FKUser__c

)

Workflow Actions:

   1. Field Update to set incident assigned staff email (this copies the email address over to be used by email alert in 2nd workflow)

   2. Field update to toggle on the controller field that tells the 2nd workflow it should run

 

Custom Notify Staff Incident Comment Added
workflow email alert.PNG.png

Object: Incident History

Name: Custom Notify Staff Incident Comment Added

Evaluation Criteria: When a record is created, and every time it's edited

Rule Criteria: Incident History: Notify Staff Comment Added ControllerEQUALSTrue

Workflow Actions:

   1. Email alert to the custom email field whose value is set in the first workflow

   2. Field update to toggle off the controller field so this workflow doesn't fire again until a new incident history record is created

Share This:

Some Background Info:

 

There is an idea submitted for this feature https://communities.bmc.com/ideas/3039, so this blog post is about how to implement a workaround until such feature is provided out of the box.

 

As of this writing, there is no out of the box way to default an incident's impact or urgency through administration except through templates. However, it may be unfeasible to require help desk analysts to pick a template when logging every incident, so as a Remedyforce Administrator you're looking for other options to ensure (1) meaningful defaults are assigned to fields and (2) reduce number of fields users have to manually enter.

 

Many folks in the BMC Community have offered workarounds from special templates to workflows and apex triggers. Inspired by Paul Donders trigger solution, below are instructions on how to create and configure the necessary workflows and triggers.

 

Please note, the setup steps below must be performed first in your sandbox then deployed to your production instance because apex code is involved (and that's best practice!)

 

What we'll be doing in this setup:

 

  1. Create two (2) custom fields on Incident object for specifying default values for impact and urgency
  2. Create two (2) workflow rules on Incident object to signal that our code should run
  3. Create two (2) workflow field updates on Incident object to set values into the custom fields from step 1
  4. Create one (1) apex class to contain code and logic for assigning default values to incident impact and urgency
  5. Create one (1) apex trigger on Incident object to invoke the apex class from step 4
  6. Create one (1) apex test class to validate our code and meet Salesforce code coverage requirements to deploy to production

 

 

Step 1 - Create Custom Fields

 

Change Impact Controller custom Incident field
change_impact_controller_incident_field.png

Field Label = Change Impact Controller

Field Name = Change_Impact_Controller

Description = This field is used to activate the workflow / trigger for defaulting the Impact look up field to this value. This workaround is needed because as a managed package, Impact cannot be changed to have a default, and as a look up field, it is not available to Workflow Field Updates.

Help Text = This field is used to activate the workflow / trigger for defaulting the Impact look up field to this value.

Length = 80

 

 

Change Urgency Controller custom Incident field

change_urgency_controller_incident_field.png

Field Label = Change Urgency Controller

Field Name = Change_Urgency_Controller

Description = This field is used to activate the workflow / trigger for defaulting the Urgency look up field to this value. This workaround is needed because as a managed package, Urgency cannot be changed to have a default, and as a look up field, it is not available to Workflow Field Updates.

Help Text = This field is used to activate the workflow / trigger for defaulting the Urgency look up field to this value.

Length = 80

 

 

Step 2 - Create Workflow Rules

 

Set Incident Impact Workflow Rule
set_incident_impact_workflow.png

Object = Incident

Rule Name = Set Incident Impact

Description = Workflow to default Impact when it is not set on the incident. This is to ensure the field has a value and automate its assignment.

Evaluation Criteria = Evaluate the rule when a record is created, and every time it's edited

Rule Criteria = Run this rule if the following formula evaluates to true

                    ISBLANK( BMCServiceDesk__FKImpact__c )

 

 

Set Incident Urgency Workflow Rule
set_incident_urgency_workflow.png

Object = Incident

Rule Name = Set Incident Urgency

Description = Workflow to default Urgency when it is not set on the incident. This is to ensure the field has a value and automate its assignment.

Evaluation Criteria = Evaluate the rule when a record is created, and every time it's edited

Rule Criteria = Run this rule if the following formula evaluates to true

                    ISBLANK( BMCServiceDesk__FKUrgency__c )

 

 

Step 3 - Create Field Updates

 

Set Change Impact Controller Field Update
set_change_impact_controller_field_update.png

Name = Set Change Impact Controller

Unique Name = Set_Change_Impact_Controller

Description = Set the value of this field to what the incident's impact should be set to. Trigger will analyze this field to perform update if this field is not blank. Trigger blanks this field once done so that the workflow rule has to fire to trip the trigger again.

Object = Incident

Field to Update = Incident: Change Impact Controller

New Value = use a formula to set the new value

                    "MEDIUM" (or the name of any Impact in your system you want to use for default)

Re-evaluate Workflow Rules after Field Change = yes, checked (so Priority will be re-calculated by Remedyforce)

Set Change Urgency Controller Field Update
set_change_urgency_controller_field_update.png

Name = Set Change Urgency Controller

Unique Name = Set_Change_Urgency_Controller

Description = Set the value of this field to what the incident's urgency should be set to. Trigger will analyze this field to perform update if this field is not blank. Trigger blanks this field once done so that the workflow rule has to fire to trip the trigger again.

Object = Incident

Field to Update = Incident: Change Urgency Controller

New Value = use a formula to set the new value

                    "MEDIUM" (or the name of any Urgency in your system you want to use for default)

Re-evaluate Workflow Rules after Field Change = yes, checked (so Priority will be re-calculated by Remedyforce)

 

 

Step 4 - Create Apex Class

 

Code is shown below for quick reference, it is also provided as a text file attachment at bottom of this blog post.

 

/**
 * Written by Doug Ayers, https://communities.bmc.com/people/douglas.ayers%40fotlinc.com
 * Inspired by Paul Donders, https://communities.bmc.com/people/p.donders@infravision.com//communities.bmc.com/people/p.donders@infravision.com
 * BMC Communities, https://communities.bmc.com/ideas/3039
*/
public class BMCRF_IncidentTriggerHelper
{
    public static void checkAndSetImpact( List<BMCServiceDesk__Incident__c> incidents ) {


     // get list of all active impacts
        List<BMCServiceDesk__Impact__c> impactList = new List<BMCServiceDesk__Impact__c>([
            SELECT id, name FROM BMCServiceDesk__Impact__c WHERE BMCServiceDesk__inactive__c = false
        ]);


        // convert list of impacts into a map so we can do look ups by impact name (eg, 'MEDIUM')
        Map<String, BMCServiceDesk__Impact__c> impactMap = new Map<String, BMCServiceDesk__Impact__c>();
        for ( BMCServiceDesk__Impact__c impact : impactList ) {
            impactMap.put( impact.name, impact );
        }


        // loop through each incident and check if its impact should be set
        for ( BMCServiceDesk__Incident__c incident : incidents ) {


            System.debug( 'Incident Impact: ' + incident.BMCServiceDesk__FKImpact__r );
            System.debug( 'Change Impact Controller: ' + incident.Change_Impact_Controller__c );


            if ( String.isNotBlank( incident.Change_Impact_Controller__c ) ) {


             // get the impact reference from the map whose name matched the custom controller field's value
                BMCServiceDesk__Impact__c impact = impactMap.get( incident.Change_Impact_Controller__c );


                if ( impact != null ) {


                    System.debug( 'Changing impact to: ' + impact );


                    incident.BMCServiceDesk__FKImpact__c = impact.id;


                } else {


                    System.debug( LoggingLevel.WARN, 'Unknown impact to set: ' + incident.Change_Impact_Controller__c );


                }


                // clear the controller value so this code doesn't run again
                // unless the workflow rules reset the controller value
                incident.Change_Impact_Controller__c = null;


            }


        }


    }


    public static void checkAndSetUrgency( List<BMCServiceDesk__Incident__c> incidents ) {


     // get list of all active urgencies
        List<BMCServiceDesk__Urgency__c> urgencyList = new List<BMCServiceDesk__Urgency__c>([
            SELECT id, name FROM BMCServiceDesk__Urgency__c WHERE BMCServiceDesk__inactive__c = false
        ]);


        // convert list of urgencies into a map so we can do look ups by urgency name (eg, 'MEDIUM')
        Map<String, BMCServiceDesk__Urgency__c> urgencyMap = new Map<String, BMCServiceDesk__Urgency__c>();
        for ( BMCServiceDesk__Urgency__c urgency : urgencyList ) {
            urgencyMap.put( urgency.name, urgency );
        }


        // loop through each incident and check if its urgency should be set
        for ( BMCServiceDesk__Incident__c incident : incidents ) {


            System.debug( 'Incident Urgency: ' + incident.BMCServiceDesk__FKUrgency__r );
            System.debug( 'Change Urgency Controller: ' + incident.Change_Urgency_Controller__c );


            if ( String.isNotBlank( incident.Change_Urgency_Controller__c ) ) {


  // get the urgency reference from the map whose name matched the custom controller field's value
                BMCServiceDesk__Urgency__c urgency = urgencyMap.get( incident.Change_Urgency_Controller__c );


                if ( urgency != null ) {


                    System.debug( 'Changing urgency to: ' + urgency );


                    incident.BMCServiceDesk__FKUrgency__c = urgency.id;


                } else {


                    System.debug( LoggingLevel.WARN, 'Unknown urgency to set: ' + incident.Change_Urgency_Controller__c );


                }


                // clear the controller value so this code doesn't run again
                // unless the workflow rules reset the controller value
                incident.Change_Urgency_Controller__c = null;


            }


        }


    }
}



 

 

Step 5 - Create Trigger

 

Code is shown below for quick reference, it is also provided as a text file attachment at bottom of this blog post.

 

/**
 * Written by Doug Ayers, https://communities.bmc.com/people/douglas.ayers%40fotlinc.com
 * Inspired by Paul Donders, https://communities.bmc.com/people/p.donders@infravision.com//communities.bmc.com/people/p.donders@infravision.com
 * BMC Communities, https://communities.bmc.com/ideas/3039
*/
trigger BMCRF_IncidentTrigger on BMCServiceDesk__Incident__c ( before update ) {


    if ( Trigger.isBefore && Trigger.isUpdate ) {
        BMCRF_IncidentTriggerHelper.checkAndSetImpact( Trigger.new );
        BMCRF_IncidentTriggerHelper.checkAndSetUrgency( Trigger.new );
    }


}



 

Step 6 - Create Apex Test

 

Code is shown below for quick reference, it is also provided as a text file attachment at bottom of this blog post.

 

@isTest
private class BMCRF_IncidentTriggerHelperTest
{
    @isTest
    static void test_set_incident_impact_and_urgency() {


        BMCServiceDesk__Impact__c impact = new BMCServiceDesk__Impact__c();
        impact.name = 'MEDIUM';


        insert impact;


        BMCServiceDesk__Urgency__c urgency = new BMCServiceDesk__Urgency__c();
        urgency.name = 'MEDIUM';


        insert urgency;


        BMCServiceDesk__Category__c category = new BMCServiceDesk__Category__c();
        category.name = 'Test Category';
        category.BMCServiceDesk__AvailableForIncidents__c = true;


        insert category;


        BMCServiceDesk__Incident__c incident = new BMCServiceDesk__Incident__c();
        incident.BMCServiceDesk__incidentDescription__c = 'Test';
        incident.BMCServiceDesk__IncidentType__c = 'Incident';
        incident.BMCServiceDesk__FKCategory__c = category.id;
        incident.BMCServiceDesk__FKClient__c = UserInfo.getUserId();


        System.assert( incident.BMCServiceDesk__FKImpact__c == null );
        System.assert( incident.BMCServiceDesk__FKUrgency__c == null );


        Test.startTest();


        insert incident;


        Test.stopTest();


        incident = [ select id, BMCServiceDesk__Impact_Id__c, BMCServiceDesk__Urgency_Id__c from BMCServiceDesk__Incident__c where id = :incident.id ];


        System.assert( incident.BMCServiceDesk__Impact_Id__c == 'MEDIUM' );
        System.assert( incident.BMCServiceDesk__Urgency_Id__c == 'MEDIUM' );


    }


}