Hey guys, today in this post we are going to learn about How to Avoid Duplicate Name Record Simply Using a Apex Controller Method and Validating a Lightning Input Form with Email Regex Pattern Checked and Submit on Click Button in Salesforce Lightning.
- Don’t forget to check out:- Trigger to check duplicate name to custom object in Salesforce Click Here For More Information
Files we used in this post example:-
preventDuplicateApp.app | Lightning Application | It is used for call the component to preview on browser. |
preventDuplicateCmp.cmp |
Lightning Component | It is used for create a Score Card form on lightning component . |
preventDuplicateCmpController.js |
JavaScript Controller File | It is used for click function for submit the Input field Value into Database. |
preventDuplicateCmpHelper.js | JavaScript Helper Controller File | It is used for fetch the dropdown picklist value from server and it’s call on Javascript doInit function. |
preventDuplicateCmp.css | Component Style CSS | It is used for create custom Style CSS for alignment the form input field and Validation Error. |
preventDuplicateController.apxc | Apex Controller File | It is used for insert input value into database server. |
Live Demo
You can download file directly from github by Click Here.
Other related post that would you like to learn in Salesforce
Step 1:- Create Lightning Application : preventDuplicateApp.app
From Developer Console >> File >> New >> Lightning Application
preventDuplicateApp.app [Component Application File]
<aura:application extends="force:slds">
<c:preventDuplicateCmp/>
</aura:application>
Step 2:- Create Lightning Component : preventDuplicateCmp.cmp
From Developer Console >> File >> New >> Lightning Component
preventDuplicateCmp.cmp [Lightning Component File]
<aura:component controller="preventDuplicateController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
<aura:attribute name="scoreCardObj" type="scoreCard__c" default="{'sobjectType':'scoreCard__c'}"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:attribute name="statusListItems" type="string[]"/>
<aura:attribute name="dupItems" type="string"/>
<aura:attribute name="dupNameNull" type="boolean" default="false"/>
<div class="slds slds-padding-around--medium">
<div class="slds-grid slds-wrap">
<div class="slds-p-horizontal--medium slds-col slds-size_6-of-12 slds-m-bottom--medium">
<div class="slds-form-element">
<label class="slds-form-element__label">Name</label>
<div class="slds-form-element__controller">
<ui:inputText class="slds-input" value="{!v.scoreCardObj.Name}" aura:id="userName"/>
<aura:if isTrue="{!v.dupNameNull}">
<span class="dupName">{!v.dupItems}</span>
</aura:if>
</div>
</div>
</div>
</div>
<div class="slds-grid slds-wrap">
<div class="slds-p-horizontal--medium slds-col slds-size_6-of-12 slds-m-bottom--medium">
<div class="slds-form-element">
<label class="slds-form-element__label">Email</label>
<div class="slds-form-element__controller">
<ui:inputEmail class="slds-input" value="{!v.scoreCardObj.Email__c}" aura:id="userEmail"/>
</div>
</div>
</div>
</div>
<div class="slds-grid slds-wrap">
<div class="slds-p-horizontal--medium slds-col slds-size_6-of-12 slds-m-bottom--medium">
<div class="slds-form-element">
<label class="slds-form-element__label">Phone</label>
<div class="slds-form-element__controller">
<ui:inputPhone class="slds-input" value="{!v.scoreCardObj.Phone_No__c}" aura:id="userPhone"/>
</div>
</div>
</div>
</div>
<div class="slds-p-horizontal--medium slds-col slds-size_6-of-12 slds-m-bottom--medium">
<div class="slds-form-element">
<label class="slds-form-element__label">Target Actuals</label>
<div class="slds-form-element__controller">
<ui:inputSelect class="slds-select" aura:id="targetId" value="{!v.scoreCardObj.targetVSActuals__c}">
<ui:inputSelectOption text="--None--"/>
<aura:iteration items="{!v.statusListItems}" var="statusVar">
<ui:inputSelectOption text="{!statusVar}"/>
</aura:iteration>
</ui:inputSelect>
</div>
</div>
</div>
<div class="slds-form--inline slds-p-horizontal--medium slds-col slds-size_6-of-12 slds-m-bottom--medium">
<div class="slds-text-align--center slds-m-top--medium">
<button class="slds-button slds-button--brand" onclick="{!c.scoreCardAction}">Submit</button>
</div>
</div>
<br/><br/>
<br/> <br/>
<!--Start RelatedTopics Section-->
<div style="border:1px #ddd solid; padding:10px; background:#eee; margin:40px 0;">
<p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/05/thumbsUpLike.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:16px; font-style:italic; display:inline-block; margin-right:5px;">Don't forget to check out:-</span><a href="https://www.w3web.net/" target="_blank" rel="noopener noreferrer" style="text-decoration:none;" data-aura-rendered-by="440:0">An easy way to learn step-by-step online free Salesforce tutorial, To know more Click <span style="color:#ff8000; font-size:18px;" data-aura-rendered-by="442:0">Here..</span></a></strong></p>
<br/><br/>
<p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/07/tickMarkIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:17px; font-style:italic; display:inline-block; margin-right:5px; color:rgb(255 128 0);">You May Also Like →</span> </strong></p>
<div style="display:block; overflow:hidden;">
<div style="width: 50%; float:left; display:inline-block">
<ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;">
<li><a href="https://www.w3web.net/lwc-get-set-lightning-checkbox-value/" target="_blank" rel="noopener noreferrer">How to get selected checkbox value in lwc</a></li>
<li><a href="https://www.w3web.net/display-account-related-contacts-in-lwc/" target="_blank" rel="noopener noreferrer">how to display account related contacts based on AccountId in lwc</a></li>
<li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to create lightning datatable row actions in lwc</a></li>
<li><a href="https://www.w3web.net/if-and-else-condition-in-lwc/" target="_blank" rel="noopener noreferrer">how to use if and else condition in lwc</a></li>
<li><a href="https://www.w3web.net/get-selected-radio-button-value-and-checked-default-in-lwc/" target="_blank" rel="noopener noreferrer">how to display selected radio button value in lwc</a></li>
</ul>
</div>
<div style="width: 50%; float:left; display:inline-block">
<ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;">
<li><a href="https://www.w3web.net/display-account-related-contacts-lwc/" target="_blank" rel="noopener noreferrer">display account related contacts based on account name in lwc</a></li>
<li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to insert a record of account Using apex class in LWC</a></li>
<li><a href="https://www.w3web.net/fetch-picklist-values-dynamic-in-lwc/" target="_blank" rel="noopener noreferrer">how to get picklist values dynamically in lwc</a></li>
<li><a href="https://www.w3web.net/edit-save-and-remove-rows-dynamically-in-lightning-component/" target="_blank" rel="noopener noreferrer">how to edit/save row dynamically in lightning component</a></li>
<li><a href="https://www.w3web.net/update-parent-object-from-child/" target="_blank" rel="noopener noreferrer">update parent field from child using apex trigger</a></li>
</ul>
</div>
<div style="clear:both;"></div>
<br/>
<div class="youtubeIcon">
<a href="https://www.youtube.com/channel/UCW62gTen2zniILj9xE6LmOg" target="_blank" rel="noopener noreferrer"><img src="https://www.w3web.net/wp-content/uploads/2021/11/youtubeIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;"/> <strong>TechW3web:-</strong> To know more, Use this <span style="color: #ff8000; font-weight: bold;">Link</span> </a>
</div>
</div>
</div>
<!--End RelatedTopics Section-->
</div>
</aura:component>
Step 3:- Create Lightning Component : preventDuplicateCmpController.js
From Developer Console >> File >> New >> Lightning Component >> JavaScript Controller
preventDuplicateCmpController.js [JavaScript Controller]
({
doInit : function(component, event, helper) {
helper.statusListItemsView(component,helper);
},
scoreCardAction : function(component, event, helper) {
var regExpEmailformat = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
component.set('v.dupNameNull',false);
var action = component.get('c.insertScoreCardInfo');
var isValidate = true;
var userName = component.find('userName');
var userEmail = component.find('userEmail');
var userPhone = component.find('userPhone');
var targetId = component.find('targetId');
var userNameVal = component.find('userName').get('v.value');
var userEmailVal = component.find('userEmail').get('v.value');
var userPhoneVal = component.find('userPhone').get('v.value');
var targetIdVal = component.find('targetId').get('v.value');
//alert('targetIdVal ' + targetIdVal);
if($A.util.isUndefinedOrNull(userNameVal) || $A.util.isUndefined(userNameVal) || $A.util.isEmpty(userNameVal)){
userName.set("v.errors",[{message:'Name is required'}]);
isValidate = false;
}else{
userName.set("v.errors",null);
}
if(!$A.util.isEmpty(userEmailVal)){
if(userEmailVal.match(regExpEmailformat)){
userEmail.set("v.errors", null);
}else{
userEmail.set("v.errors", [{message: "Please Enter a Valid Email Address"}]);
}
}else{
userEmail.set("v.errors",[{message:'Email is required'}]);
isValidate = false;
}
/*
if($A.util.isUndefinedOrNull(userEmailVal) || $A.util.isUndefined(userEmailVal) || $A.util.isEmpty(userEmailVal)){
userEmail.set("v.errors",[{message:'Email is required'}]);
isValidate = false;
}else{
userEmail.set("v.errors",null);
}
*/
if($A.util.isUndefinedOrNull(userPhoneVal) || $A.util.isUndefined(userPhoneVal) || $A.util.isEmpty(userPhoneVal)){
userPhone.set("v.errors",[{message:'Phone is required'}]);
isValidate = false;
}else{
userPhone.set("v.errors",null);
}
if(targetIdVal == '--None--'){
targetId.set("v.errors",[{message:'Please select target actuals option'}]);
isValidate = false;
}else{
targetId.set("v.errors",null);
}
if(isValidate){
action.setParams({
'nameStr':userNameVal,
'emailStr':userEmailVal,
'phoneStr':userPhoneVal,
'targetStr':targetIdVal
});
action.setCallback(this, function(response){
var state = response.getState();
if(state == "SUCCESS"){
var result = response.getReturnValue();
component.set('v.scoreCardObj.Name','');
component.set('v.scoreCardObj.Email__c','');
component.set('v.scoreCardObj.Phone_No__c','');
component.set('v.scoreCardObj.targetVSActuals__c','--None--');
component.set('v.dupItems', result);
//JSON.stringify(alert('result## ' + result));
if(result == 'Duplicate name Not Allow'){
component.set('v.dupNameNull',true);
//alert('duplicate does not allow11');
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
"title":"Error",
"type":"error",
"message":"Do not allow duplicate name",
});
toastEvent.fire();
}else if(result == 'Inserted successfully'){
component.set('v.dupNameNull',false);
//alert('Form submitted successfully');
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
"title":"Success",
"type":"success",
"message":"The record has been submitted successfully.",
});
toastEvent.fire();
}
}
});
$A.enqueueAction(action);
}
},
})
Step 4:- Create Lightning Component : preventDuplicateCmpHelper.js
From Developer Console >> File >> New >> Lightning Component >> JavaScript Helper
preventDuplicateCmpHelper.js [JavaScript Helper File]
({
statusListItemsView : function(component, event, helper) {
var action = component.get('c.pickList');
action.setParams({"obj":"scoreCard__c", "str":"targetVSActuals__c"});
action.setCallback(this, function(response){
var state = response.getState();
if(state == "SUCCESS"){
var result = response.getReturnValue();
JSON.stringify('result ' + result);
component.set('v.statusListItems',result);
}
});
$A.enqueueAction(action);
},
})
Step 5:- Create Lightning Component Style: preventDuplicateCmp.css
From Developer Console >> File >> New >> Lightning Component >> Component Style CSS
preventDuplicateCmp.css [Style CSS]
.THIS {background:#fff !important;
}
.THIS .slds-input.has-error, .THIS .slds-select.has-error {
background-color: rgb(255, 255, 255);
border-color: rgb(194, 57, 52);
box-shadow: rgb(194, 57, 52) 0 0 0 1px inset;
background-clip: padding-box;
}
.THIS .slds-input.has-error + ul.has-error, .THIS .slds-select.has-error + ul.has-error{border:2px #c23934 solid; border-radius: 3px;}
.THIS .slds-input.has-error + ul.has-error, .THIS .slds-select.has-error + ul.has-error{position:relative; margin:0 0 10px 0; padding:0; list-style:none; display: inline-flex; top:11px; left:0;}
.THIS ul.has-error li.form-element__help{margin:0; padding: 3px 5px; top:10px;}
.THIS ul.has-error li.form-element__help:before{content: ''; width: 0; height: 0; border-left: 5px solid transparent; border-bottom: 10px solid #c23934;
border-right: 5px solid transparent; position: absolute; left: 0px; top:-11px; }
.THIS .dupName{color:#c23934; display:inline-block; margin:3px 0 0 0; border:2px #c23934 solid; padding:2px 3px; position:relative; top:7px;}
.THIS .dupName:before{content: ''; width: 0; height: 0; border-left: 5px solid transparent; border-bottom: 10px solid #c23934;
border-right: 5px solid transparent; position: absolute; left: 0px; top:-11px;}
Step 6:- Create Apex Class : preventDuplicateController.apxc
From Developer Console >> File >> New >> Apex Class
preventDuplicateController.apxc [Apex Class Controller]
public class preventDuplicateController {
@AuraEnabled
public static string insertScoreCardInfo(string nameStr, string emailStr, string phoneStr, string targetStr){
scoreCard__c scoreCardObj = NEW scoreCard__c();
List<scoreCard__c> scoreCardList=[SELECT id, Name FROM scoreCard__c WHERE Name =: nameStr];
system.debug('scoreCardListLength ##2 ' + scoreCardList.size());
IF(scoreCardList.size() > 0){
system.debug('Duplicate name Not Allow');
RETURN 'Duplicate name Not Allow';
}ELSE{
scoreCardObj.Name=nameStr;
scoreCardObj.Email__c=emailStr;
scoreCardObj.Phone_No__c=phoneStr;
scoreCardObj.targetVSActuals__c=targetStr;
INSERT scoreCardObj;
system.debug('Inserted successfully');
RETURN 'Inserted successfully';
}
}
@AuraEnabled
public static List<String> pickList(String obj, String str) {
List<String> regList = NEW List<String>();
Schema.DescribeFieldResult plistvalues = Schema.getGlobalDescribe().get(obj).getDescribe().fields.getMap().get(str).getDescribe();
FOR(PicklistEntry ent:plistvalues.getpicklistvalues()) {
regList.add(ent.getLabel());
}
RETURN regList;
}
}
Further post that would you like to learn in Salesforce
How do you prevent duplicate records in Salesforce Apex?
Preventing duplicate records in Salesforce based on a single field can be achieved using a Set that can store the values of that specific field from all existing records and compare it with the list of new records that are going to be inserted.
How do you prevent duplicate records in Salesforce using validation rule?
We'll check this field in our flow. Next, we need to create the validation rule that will prevent a user from creating the duplicate record. This rule only needs to look at our Prevent Save checkbox. Since validation rules fire when the criteria is true, we only have to add the API name of the field.
How do I bypass duplicates in Salesforce?
For a duplicate rule, when the Alert option is enabled, bypass alerts and save duplicate records by setting this property to true . Prevent duplicate records from being saved by setting this property to false.
Related Topics | You May Also Like
Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
Our Free Courses →
👉 Get Free Course →
📌 Salesforce Administrators 📌 Salesforce Lightning Flow Builder 📌 Salesforce Record Trigger Flow Builder |
👉 Get Free Course →
📌 Aura Lightning Framework 📌 Lightning Web Component (LWC) 📌 Rest APIs Integration |