PowerApps Canvas app to apply Patch/Update operations on records within Dynamics 365
Introduction
One of the most common requirements while pushing the record in Dynamics 365 is to check whether a record is already present or not. If not, then create a new record else Update the existing record with updated information.
This requirement can easily be achieved through Power Automate as well, however today we shall learn how this can be achieved through PowerApps itself using Patch Function.
Basically, Patch Function is useful to perform following operations in any data source:
- Create (single or multiple) records
- Update (single or multiple) records
- Merge records
Now, I will use following two Patch function and Let's see what result I get:
Below syntax use to Create a record in Database Table:
Patch(Customers, Defaults(Customers), {ID: "3"}, {First Name: "firstnametext"}, {Job Title: "jobtitle_text"})
Below syntax use to Update the record in Customer Table where ID = 2:
Patch(Customers,First(Filter(Customers, ID = "2" ) ), { Job Title: "jobtitle" } )
Now, Let's understand this, by taking a very simple example from Dynamics 365 perceptive.
Scenario: I want to create a contact in Dynamics 365, If contact with same emailaddress is already present in Dynamics then only Update its details else Create a new contact record.
Step 1: Create a new Canvas App (ignore if you already have) > Connect to Dynamics 365 Data Source.> Connect to contact Entity.
Step 2: Insert a Blank Screen in order to add few Text Input and Button Controls or you can design the app as per your requirement.
Step 3: Insert a Success Screen to show Success Message, once the record gets Created/Updated in Dynamics 365
Step 4: Write following formula on Button Control (onSelect property)
If(IsBlank(
LookUp(Contacts,emailaddress1 =Emailaddress_Text.Text)),
Patch(Contacts,Defaults(Contacts),{'First Name':firstname_text.Text},{'Last Name':lastname_text.Text},{emailaddress1:Emailaddress_Text.Text},{'Home Phone':phone_text.Text}),
Patch(Contacts,First(Filter(Contacts,emailaddress1 =Emailaddress_Text.Text)),{'First Name':firstname_text.Text},{'Last Name':lastname_text.Text},{emailaddress1:Emailaddress_Text.Text},{'Home Phone':phone_text.Text})
);
Navigate(SuccessScreen,ScreenTransition.Fade);
Step 4: Run the App
No Contact records present in dynamic 365
Run canvas app in order to create contact record in dynamic 365.
Fill the details and click on Submit.
Record will get created in Dynamics 365 and Navigate to Success Screen.
A new contact has been created in Dynamics 365.
Now I am updating Last Name and mobile phone and Click on submit.
Submitted information in Dynamics 365 and Navigate to Success Screen.
Existing contact Record has been updated with updated Last Name and mobile phone.
Thank you..!
*This post is locked for comments