You need to sign in to do that
Don't have an account?

junction object trigger
HI All,
I have a junction object called locationcontact which is related to location (masterdetail) object and contact(masterdetail).Below the location a related list is placed to enter a location contact .I need to restrict if the user tries to assign a same contact to location (means avoid duplication of same contact to location).I am writing a trigger to solve this ,but unable to fetch rows.
trigger duplocationcontact on location_Contact__c (before insert) {
for (location_Contact__c ci : trigger.new) {
List<location_Contact__c> resultList = [SELECT id FROM location_Contact__c WHERE location__c = :ci.location__c AND Contact__c = :ci.Contact__c.name];
if (!resultList.isEmpty()) {
ci.addError('Duplicate record, a location contact already exists');
}
}
}
I have a junction object called locationcontact which is related to location (masterdetail) object and contact(masterdetail).Below the location a related list is placed to enter a location contact .I need to restrict if the user tries to assign a same contact to location (means avoid duplication of same contact to location).I am writing a trigger to solve this ,but unable to fetch rows.
trigger duplocationcontact on location_Contact__c (before insert) {
for (location_Contact__c ci : trigger.new) {
List<location_Contact__c> resultList = [SELECT id FROM location_Contact__c WHERE location__c = :ci.location__c AND Contact__c = :ci.Contact__c.name];
if (!resultList.isEmpty()) {
ci.addError('Duplicate record, a location contact already exists');
}
}
}
1) Create a text field which should be unique
2) Create a workflow or process builder and populate ContactId_LocationId
If a duplicate record is entered in system this field will throw error. This wasy you can avoid trigger and test class as well.
All Answers
1) Create a text field which should be unique
2) Create a workflow or process builder and populate ContactId_LocationId
If a duplicate record is entered in system this field will throw error. This wasy you can avoid trigger and test class as well.
You dnt need to create trigger for same. You can do the same with above step as venky409 mention you.
1) Create a text field which should be unique
2) Create a workflow or process builder with field update and populate Contact__c+location__c on it.
But if you want to do same by trigger only then your trigger should be like below
Let us know if this will help you
Thanks to both of you for your suggestions.I implemented this one with workflow suggestion .In future if constraints change i will use this trigger.
Thank you,
Krishna.