+ Start a Discussion
Chidanand Magadum 24Chidanand Magadum 24 

Before inserting the record, how to check if the perticular record already exists or not

Hi friends,

I how do i check if the record already exists or not in the database.
If the perticular record already exists then no need to insert it.
Else, insert the record.

Here is my code

Date  d = Date.Today();
List<Account> AllAccounts= new List<Account>([select id,Name,ARR__c,Relationship_Start_Date__c,
                                              (Select Id,Account.Id from Opportunities) from Account]);
for(Account a:AllAccounts)
{
    
    Integer numberDaysDue= a.Relationship_Start_Date__c.daysBetween(d);
    if(numberDaysDue<=60){
       
        Opportunity O= new Opportunity();
        o.StageName='Legal';
        o.Amount=a.ARR__c;
        o.AccountId=a.ID;
        o.Name=o.AccountId  +'Opportunity';
        o.CloseDate=Date.today();
        o.NextStep='Won';
        system.debug('Account Id'+o.AccountId);
        insert o;
      
    }
   
    
    system.debug('Diff==='+numberDaysDue);
 
}
Tejpal KumawatTejpal Kumawat
Hello Chidanand Magadum,

You can write before insert trigger or validation rule using VLOOKUP function.

Can you post your reqirement, on which field you are checking duplicacy?

If this answers your question then hit Like and mark it as solution!
 
Chidanand Magadum 24Chidanand Magadum 24
Hi bro,

I wanna do it using Apex nly. Not on any trigger action. For that account only one opportunity has to get created.  It should not allow to create another opportunity for that account. So how do i achieve this. Plz tell necessary changes in my bcode
Tejpal KumawatTejpal Kumawat
Hello  Chidanand Magadum,

Try this code :

Date  d = Date.Today();

List<Account> AllAccounts= new List<Account>([select id,Name,ARR__c,Relationship_Start_Date__c,
                              (Select Id,Account.Id from Opportunities) from Account]);
for(Account a:AllAccounts){
    if(a.Opportunities.size() == 0){
        Integer numberDaysDue= a.Relationship_Start_Date__c.daysBetween(d);
        if(numberDaysDue<=60){
            Opportunity O= new Opportunity();
            o.StageName='Legal';
            o.Amount=a.ARR__c;
            o.AccountId=a.ID;
            o.Name=o.AccountId  +'Opportunity';
            o.CloseDate=Date.today();
            o.NextStep='Won';
            system.debug('Account Id'+o.AccountId);
            insert o;
        }
        system.debug('Diff==='+numberDaysDue);
    }else{
        //If need throw error message
    }
}

If this answers your question then hit Like and mark it as solution!
 
Tejpal KumawatTejpal Kumawat
Hello Chidanand Magadum,

If you want best approach then you need to write apex trigger :
 
trigger OpportunityTest on Opportunity (before insert) {
    set<string> setAccountId = new set<string>();
    for(Opportunity opp : Trigger.New){
        setAccountId.add(opp.AccountId);
    }
    
    map<Id, Account> mapAccount = new map<Id, Account>([select id, Name,(Select Id,Account.Id from Opportunities) from Account where Id IN: setAccountId]);
    for(Opportunity opp : Trigger.New){
        if(mapAccount.containsKey(opp.AccountId)){
            if(mapAccount.get(opp.AccountId).Opportunities.size() > 0){
                opp.addError('Duplicate record found.');
            }
        }
    }
}


If this answers your question then hit Like and mark it as solution!
 
Tejpal KumawatTejpal Kumawat

Hello Chidanand Magadum,

If this answers your question mark Best Answer it as solution, It will help others!
MayurDev BhavsarMayurDev Bhavsar
Hello  Chidanand Magadum,
try this,

Date  d = Date.Today();
List<Account> AllAccounts= new List<Account>([select id,Name,ARR__c,Relationship_Start_Date__c,
                                              (Select Id,Account.Id from Opportunities) from Account]);
if(AllAccounts.size() ==  0)
{
       Opportunity O= new Opportunity();
        o.StageName='Legal';
        o.Amount=a.ARR__c;
        o.AccountId=a.ID;
        o.Name=o.AccountId  +'Opportunity';
        o.CloseDate=Date.today();
        o.NextStep='Won';
        system.debug('Account Id'+o.AccountId);
        insert o;
}

 
BHANU TEJA PULIPALUPULABHANU TEJA PULIPALUPULA
@TejPal Kumavat

trigger OpportunityTest on Opportunity (before insert) {
   set<string> setAccountId = new set<string>();
    for(Opportunity opp : Trigger.New){
        setAccountId.add(opp.AccountId);
   }
     
    map<Id, Account> mapAccount = new map<Id, Account>([select id, Name,(SelectId,Account.Id from Opportunities) from Account where Id IN: setAccountId]);
    for(Opportunity opp : Trigger.New){
        if(mapAccount.containsKey(opp.AccountId)){
            if(mapAccount.get(opp.AccountId).Opportunities.size() > 0){
                opp.addError('Duplicate record found.');
            }
        }
    }
}
I tried this trigger on Opportunity for finding a duplicate Account. It worked absolutely fine.
But,
If we have a custom object in the place of Account, How to deal with this problem??
The query in the Map says 'Relationship cant be recognized'. 

Actual problem I'm dealing with: On Opportunity object, I have a field called PWC{Custom field} which is lookup(ALocation){custom object}.
I need to write a trigger on Opportunity object to throw an error if duplicate ALocation is selected for PWC field in Opportunity record creation.

Trigger I've written: {Here, Primary_Work_Location__c is field on Opportunity object which is lookup(Associated_Location__c)}
trigger OpportunityNameExists on Opportunity (before insert, before update, after insert, after update) {
    set<String> setPrimaryWorkLocationId = new set<String>();
    for(Opportunity opp : Trigger.New){
        setPrimaryWorkLocationId.add(opp.Primary_Work_Location__c);
    }
   map<Id, Associated_Location__c> mapAssociatedLocation = new map<Id, Associated_Location__c>([select id, Name,(Select Id,Primary_Work_Location__c from Opportunities) from Associated_Location__c where Id IN: setPrimaryWorkLocationId]);
    for(Opportunity opp: Trigger.New){
        if(mapAssociatedLocation.containsKey(opp.Primary_Work_Location__c)){
            if(mapAssociatedLocation.get(opp.Primary_Work_Location__c).Opportunities.size() > 0){
                opp.addError('The Opportunity Name already exist for selected Primary Work Location. Please change it and try to save the opportunity again');
            }
        }
    }  
}

Please help!!!!