I've been working as an admin for my org for the last few months. After my move to Lightning, we needed to use the AccountContactRelation object to be able to mark a contact as the primary contact on the account. I needed a trigger to be able to prevent multiple primary contacts from being checked.
I was able to use the code below and it functions perfectly in my Sandbox environment when I tested it, however it's receiving a 0% code coverage, thus I can't deploy it to Prod. Based on reading and messing around, I was able to sort-of create a test-class, but I'm stuck on where to go from here as I have zero dev experience (except HTML/CSS).
I'd appreciate any help I can get! Thank you!
Trigger code that works in Sandbox:
Trigger PreventMultiplePrimaryContacts on AccountContactRelation (Before Insert, Before Update) {
List<AccountContactRelation> recordsToProcess = New List<AccountContactRelation>();
List<Id> accountIds = New List<Id>();
List<Id> contactIds = New List<Id>();
If(Trigger.isBefore && (Trigger.IsInsert || Trigger.IsUpdate)) {
For(AccountContactRelation EveryRelationshipRecord : Trigger.New) {
If(EveryRelationshipRecord.Primary__c == TRUE) {
recordsToProcess.add(EveryRelationshipRecord);
accountIds.add(EveryRelationshipRecord.AccountId);
contactIds.add(EveryRelationshipRecord.ContactId);
}
}
}
List<AccountContactRelation> existingRecords = [
Select id, ContactId, AccountId, Primary__c
FROM AccountContactRelation
WHERE Primary__c = TRUE
AND Id !=: recordsToProcess
AND AccountId =: accountIds
];
If(recordsToProcess.isEmpty()) return;
For(AccountContactRelation junctionObj :recordsToProcess ) {
For(AccountContactRelation EveryExistingRecord : existingRecords) {
If(junctionObj.AccountId == EveryExistingRecord.AccountId) {
junctionObj.addError('There is already a Primary Contact for this Account. Please uncheck the other contact as primary before continuing.');
}
}
}
}
Test Class code that doesn't work:
@isTest
private class TestAccountContactRelation {
@isTest static void TestAccountContactRelation() {
Account acct = new Account(
Name='HelloWorld'
);
insert acct;
Contact con = new Contact(
AccountId = acct.id,
lastname = 'testdata',
firstname ='testdata1'
);
insert con;
Contact con1 = new Contact(
AccountId = acct.id,
lastname = 'testdata2',
firstname ='testdata2'
);
insert con1;
AccountContactRelation acctcr = new AccountContactRelation(
AccountId = acct.id,
ContactId = con.id,
Primary__c = TRUE
);
insert acctcr;
Test.startTest();
acctcr.Primary__c = True;
update con;
Test.stopTest();
system.asserts(acctcr.AccountId,acct.Id);
}
}