+ Start a Discussion
Siana DcruzSiana Dcruz 

How to compare fields of two different objects!!

Hi all,
I need help in trigger, There are two objects Intake_details and claim. The issue is,some claim records are being created that do not have a corresponding Intake Detail record
A claim record should only be created if its name(claim number) field matches the Intake_details name field. 

Please suggest me how to do this.
Best Answer chosen by Siana Dcruz
Veenesh VikramVeenesh Vikram
A trigger like this will do the Job:
trigger preventinsert on claim__c(before insert){
	Set<String> indicatorNames = new Set<String>();
	Set<String> namesofClaim = new Set<String>();
	for(claim__c claim : trigger.new){
		namesofClaim.add(claim.Name);
	}
	for(Intake_details__c intake : [SELECT Id, Name FROM Intake_details__c Where Name in :namesofClaim]){
		indicatorNames.add(intake.Name);
	}
	for(claim__c claim : trigger.new){
		if(!indicatorNames.contains(claim.Name)){
			claim.addError('CANNOT INSERT');
		}
	}
}

Hope this helps!

Veenesh

All Answers

Veenesh VikramVeenesh Vikram
A trigger like this will do the Job:
trigger preventinsert on claim__c(before insert){
	Set<String> indicatorNames = new Set<String>();
	Set<String> namesofClaim = new Set<String>();
	for(claim__c claim : trigger.new){
		namesofClaim.add(claim.Name);
	}
	for(Intake_details__c intake : [SELECT Id, Name FROM Intake_details__c Where Name in :namesofClaim]){
		indicatorNames.add(intake.Name);
	}
	for(claim__c claim : trigger.new){
		if(!indicatorNames.contains(claim.Name)){
			claim.addError('CANNOT INSERT');
		}
	}
}

Hope this helps!

Veenesh
This was selected as the best answer
Siana DcruzSiana Dcruz
Thanks!!.It worked..
But in my case, IF claim name doesnt match with any of the intakedetail name then I need to a create a intakedetail record with the corresponding claim name.How will I achieve that?
Veenesh VikramVeenesh Vikram
trigger preventinsert on claim__c(before insert){
	Set<String> indicatorNames = new Set<String>();
	Set<String> namesofClaim = new Set<String>();
	List<Intake_details__c> insertList = new List<Intake_details__c>();
	for(claim__c claim : trigger.new){
		namesofClaim.add(claim.Name);
	}
	for(Intake_details__c intake : [SELECT Id, Name FROM Intake_details__c Where Name in :namesofClaim]){
		indicatorNames.add(intake.Name);
	}
	for(claim__c claim : trigger.new){
		if(!indicatorNames.contains(claim.Name)){
			insertList.add(new Intake_details__c(name=claim.Name));
			//claim.addError('CANNOT INSERT');
		}
	}
	if(insertList.size()>0){
		insert insertList;
	}
}

 
Siana DcruzSiana Dcruz
Thanks Veenesh :)