+ Start a Discussion
Mike Reynolds 6Mike Reynolds 6 

Custom Object Trigger, conditionally create parent case when loading children


I've got a custom object called Deposit__c that is related to Case and Account. Each Deposit must have a Case, and an Account. Due to rules in place outside of salesforce, I know this will always be the case. I'm having issues getting things ironed out so I'm hoping someone can see where I've gone wrong...
trigger DepositTrigger on Deposit__c (before insert) {
	Set<String> AcctNums = new Set<String>();
    for(Deposit__c d : Trigger.New){
    List<Case> caseList = [select id from Case where RecordTypeId = '0121a0000001nWh' and LastModifiedDate < LAST_N_DAYS:30 and case.Account.Name in :AcctNums];
    Map<String,Id> accountCaseIdMap = new Map<String,Id>();
    for(Case c : caseList){
    for(Deposit__c d2: Trigger.new){
        if(case.Id != accountCaseIdMap.get(d2.Id)){
            Case newCase = new Case(Account = d2.Account.Name, RecordTypeId = '0121a0000001nWh');
    upsert caseList;
    for(Case c : caseList){
    for(Deposit__c d3 : Trigger.New){
        Case depCase = accountCaseIdMap.get(d3.SBR_ID__c);
        d3.CaseId = depCase;
    update accountCaseIdMap.values;
It is possible that within the same file, multiple deposit__c records will be for the same account. It is also possible that some deposit__c records will not have cases open, while others will. If there is an open case(or a recently closed one) i want to relate the new deposit__c record to the existing case and not create a new one. 

My current issue is that on line 13 I have an Invalid foreign key relationship: Deposit__c.Account. I have no idea why this is happening. Any thoughts?

Thanks in advance. 

Best Answer chosen by Mike Reynolds 6
use if(!accountCaseIdMap.containsKey(d2.case__c))

All Answers

Couple of qns ..
1) Can deposit belong to existing case? or its always new case?
2) If a case can already exist , whats the reference field for that on deposit object?

Account field on case is AccountId. based on answers to questions the logic will change. 
Mike Reynolds 6Mike Reynolds 6
Hey Venky409,

Yes a case could already exist. Either because it was from a previous data load, or from a previous record in the batch. 

The relationship is Deposit__c.Case__c

Use Account__r.Name
Mike Reynolds 6Mike Reynolds 6
Hey Natsu, 

That's awesome! That took care of that error, now I have another one. Line 12 - Comparison arguments must be compatible types: Schema.SObjectField, Id. Any ideas?

Thanks again. 
use if(!accountCaseIdMap.containsKey(d2.case__c))
This was selected as the best answer