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, the Patch Function is useful to perform the following operations in any data source.
- Create (single or multiple) records
- Update (single or multiple) records
- Merge records
Now, I will use the following two Patch functions, and Let's see what result I get.
Below is the syntax used to Create a record in the Database Table.
Patch(
Customers,
Defaults(Customers),
{ID: "3"},
{First Name: "firstnametext"},
{Job Title: "jobtitle_text"}
)
Below is the syntax used to Update the record in the 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 the Dynamics 365 perceptive.
Scenario
I want to create a contact in Dynamics 365, If a contact with the same email address 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 one) > Connect to Dynamics 365 Data Source.> Connect to contact Entity.
Step 2. Insert a Blank Screen in order to add a few Text Inputs and Button Controls, or you can design the app as per your requirement.
Step 3. Insert a Success Screen in order to show Success Message, once the record gets Created/Updated in Dynamics 365.
Step 4. Write the 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 5. Run the App
No Contact records are present in Dynamic 365.
Run the canvas app in order to create a contact record in Dynamic 365.
Fill in the details and click on Submit.
The record will get created in Dynamics 365 and Navigated to the Success Screen.
A new contact has been created in Dynamics 365.
Now I am updating my Last Name and mobile phone and Clicking on submit.
Submitted information in Dynamics 365 and Navigate to Success Screen.
The existing contact Record has been updated with an updated Last Name and mobile phone.