0

I am very new to Apex and am trying to complete the homework for David Liu's Salesforce Development Curriculum Week 4.

Homework: Write a trigger that creates two identical Contacts whenever an Account is created. Make sure >both Contacts are associated with the Account. Use any values for the fields on the Contacts - just make >sure to use variables when populating the fields of each Contact to make sure they are identical.

I have been struggling with this for sometime now so have decided to reach out to the community for some guidance. Again, I am very new to Apex so most of my code could be completely wrong. I would really appreciate some guidance/tips on this.

trigger VariablesCollectionsHomework on Account (after insert) {
List<Contact> newContact = new List<Contact>();

     // Set up variables for Contact
    String firstName = 'David';
    String lastName  = 'Jones';
    String accountId = newContact.AccountId;

    // Populate fields
    newContact.add(firstName, lastName, accountId);
    newContact.add(firstName, lastName, accountId);

}

1 Answer 1

3

After seeing your code, You are trying to add contacts to accounts. So, basically, you have to iterate over accounts which are going to be inserted. You will get them with trigger context variable called trigger.new. Inside the for loop over it, Just create an instance of Contact where you put some mandatory field values and add the contact instance twice in the list of contact defined outside of the for loop. After, iteration, outside the for loop, insert the list of contact. Also, While creating the contact instance, I am associating the contacts with Account using their id.

trigger VariablesCollectionsHomework on Account (after insert) {
    List<Contact> newContacts = new List<Contact>();
    for(Account acc: Trigger.new){
        Contact con = new Contact(FirstName = 'David', LastName = 'Jones', accountId = acc.Id, email = '[email protected]');
        newContacts.add(con);
        newContacts.add(con.clone());
    }
    insert newContacts;
}

You can start with these trails and guides:-

  1. Apex Developer Guide - Salesforce Developers
  2. Get Started with Apex Unit | Salesforce Trailhead
  3. Apex Basics & Database | Salesforce Trailhead
  4. Developer Beginner | Salesforce Trailhead
  5. Get Started with Apex Triggers Unit | Salesforce Trailhead
3
  • 1
    This code will result in an error: System.ListException: Before Insert or Upsert list must not have two identically equal elements. You cannot use the same in-memory object two or more times in a DML insert/upsert list. The fix is simple, just clone() the record. newContacts.add(con.clone());
    – sfdcfox
    Commented Apr 22, 2020 at 11:45
  • Thank you for highlighting the issue. I just edited the answer. Commented Apr 22, 2020 at 14:06
  • Thanks for your help Sanket! Commented Apr 22, 2020 at 20:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .