TransWikia.com

Please help. I want to ensure 1 case per lead

Salesforce Asked by Mar Been on November 17, 2021

Ensure only 1 Case with this Type is open
at the same time for every Lead record

trigger createCase on Lead (after insert) {

List <Case> caseToCreate = new List <Case>(); 
Set<Id> oneCasecreated = new Map<Id, Lead>
    ([Select Id From Lead where Id in (Select Lead From Case where Lead != null)]).keySet();

    for(Lead l : Trigger.new){
        if(l.RecordTypeId == '0123t0000005nAYAAY'){
            
            Case c = new Case();
            c.Type = 'Application';
            c.OwnerId='3D00G3t000002cjR5';
            caseToCreate.add(c);

        }
        if(l.RecordTypeId == '0123t0000005nATAAY'){
            
            Case c = new Case();
            c.Type = 'Application';
            c.OwnerId='3D00G3t000002cjRK';
            caseToCreate.add(c);
            
        }
        
    }

try{
    insert caseToCreate;

}
catch (system.Dmlexception e) {
    system.debug (e);
}

}

Error here:

Set<Id> oneCasecreated = new Map<Id, Lead>
       ([Select Id From Lead where Id in (Select Lead From Case where Lead != null)]).keySet();

One Answer

There are several problems here.

([Select Id From Lead where Id in (Select Lead From Case where Lead != null)]).keySet();

There is no field called Lead on Case; the standard reference shows no relationship at all between Lead and Case. If you working with an optional feature, managed package, or custom development that establishes such a relationship, you must query based on the API name of the schema involved.

    if(l.RecordTypeId == '0123t0000005nAYAAY'){

You should never hard-code Salesforce Ids of any kind. You should always use Describe API methods or SOQL queries to obtain the Salesforce Ids you need.

Here, you should be using Describe methods, such as

Schema.DescribeSObjectResult d = Schema.SObjectType.Lead;
Id recordTypeId = d.getRecordTypeInfosByDeveloperName().get('YOUR_RECORD_TYPE').getRecordTypeId();

or similar.

3D00G3t000002cjRK

What is the key prefix 3D0? This is neither a User nor a Group.

try{
    insert caseToCreate;

}
catch (system.Dmlexception e) {
    system.debug (e);
}

You should never catch and swallow an exception like this. If this exception is considered not to threaten the integrity of your data, you should be using a logging and notification framework to bring it to the attention of your system administrator for action. Putting an exception in a debug log does nothing but hide problem behavior and risk your users' trust (and their data).

As an aside,

Ensure only 1 Case with this Type is open at the same time for every Lead record

your trigger does nothing of the kind. This seems to be fulfilling an entirely different requirement.

Answered by David Reed on November 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP