function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
carmantcarmant 

Trigger - create Case from Account

Hi,

 

I am trying to create a trigger that automatically creates a Case when an Account (PersonAccount) is created that meets certain criteria.

 

I have managed to get the trigger to create the Case, however, struggling to get it to link to Account. The field we normally use to link is the "Contact Name" - a Contact lookup field. Guessing this is because we use PersonAccounts and they are an amalgamation of Accounts & Contacts?

 

Here is what I have so far:

 

trigger CreateCase on Account (after insert) {
  
  List<Case> newcase = new List<Case>();

  Id rtId = [select Id, name from RecordType where name ='My Record Type' and SObjectType='Case' limit 1].Id;

  for (Account acc: Trigger.New) {
    if (acc.Custom_Field__c == 'My Criteria') {
 
      newcase.add(new Case(
            RecordTypeId = rtId,
            Type='My Type',
            Origin='My Origin',
            Status='My Status',

          )
        ); 

      insert newcase;  
    }
  }
}

 

Any help appreciated!

 

Thanks

Best Answer chosen by Admin (Salesforce Developers) 
carmantcarmant

Fixed it with -

 

AccountId = acc.Id

 

 

Thanks for your help.

All Answers

prazonprazon

Try this

 

trigger CreateCase on Account (after insert) {
  
  List<Case> newcase = new List<Case>();

  Id rtId = [select Id, name from RecordType where name ='My Record Type' and SObjectType='Case' limit 1].Id;

  for (Account acc: Trigger.New) {
    if (acc.Custom_Field__c == 'My Criteria') {
 
      newcase.add(new Case(
	    Account = acc.Id
            RecordTypeId = rtId,
            Type='My Type',
            Origin='My Origin',
            Status='My Status',

          )
        ); 

      insert newcase;  
    }
  }
}

 

 

carmantcarmant

Thanks for your suggestion.

 

I tried that before and get a build error -

 

Invalid initial expression type for field Account, expecting: SOBJECT:Account (or single row query result of that type)

 

 

 

carmantcarmant

Fixed it with -

 

AccountId = acc.Id

 

 

Thanks for your help.

This was selected as the best answer