RE: Alert if Topic value is already existed when creating new opportunity using code
Hi Huong,
What you are trying to do is a duplicate detection check before an opportunity can be created in the system.
There are 3 ways to do this.
- Using the out of the book Duplicate detection settings.
If you are an administrator, go to Settings -> Data management -> Duplicate detection rules. Create a new rule. Select 'Opportunity' in the primary and Matching entity types. Select Topic as the field and match type as 'Exact Match'. Save and publish this rule.
Now whenever an opportunity is created, the user will get a Warning saying an opportunity with the same Topic already exists in the system. The user can opt to either navigate to the existing opportunity and complete their process. Or click on save and continue to save the opportunity with the duplicate Topic.
2. Set 'Topic' as an alternate key.
Go to Settings -> Customization -> Customize the system. In the default solution, go to Opportunity entity and click on 'Keys'. Create a new key and select 'Topic' and save. Please note that when creating an alternate key the system will create an indexing for the Topic column in the Opportunity table. PLEASE ENSURE THERE ARE NO DUPLICATES EXISTING IN THE SYSTEM before creating the alternate key. If not the creating process will fail. I normally Export the concerned column to an excel via advanced Find and check for duplicates. If duplicates exist, I will remove the value from the column and upload the excel back. This ensures there are no duplicates before I create the alternate key.
Once an alternate key is set up for the Topic column, whenever a user tries to save an opportunity with the same Topic, the system will throw an error indicating that the Topic value has to be unique.
3. On-change JavaScript
This is done by creating a javascript web resource that checks for duplicates as soon as the Topic is entered by the user (ideal user experience but requires coding)
Create a new JavaScript function with the below code. The function should trigger on change of the Topic field
var topic = formContext.getAttribute("name").getValue();
Xrm.WebApi.retrieveMultipleRecords("opportunity", "?$select=name$filter=name eq '" + topic + "'").then(
function success(result) {
|
if( result.entities.length > 0) { |
formContext.getControl("name").setNotification("Please enter a unique value", "err1"); |
console.log(error.message); |
Hope the above helps.
If found useful, please mark the answer as verified