0

I have a customObject where users can fill in information for an account,contact, and campaign. I'm trying to write a trigger where once a user can creates this customObject, then an account, contact, and campaign will be created with the populated fields. I've gotten as far as creating the account but now I'm wondering how I can get the account ID in order to create a new contact and campaign that are linked to the newly created Account. My code is shown below.

trigger nameOfTrigger on customObject (after insert, after update) {

List<Account> AccsForInsert = New List<Account>();
List<Contact> ContactsForInsert = New List<Contact>();
List<Campaign> CampaignForInsert = new List<Campaign>();

    if(Trigger.isInsert && trigger.new.size()==1){

        for(customObject z: Trigger.new){

                Account a = new Account
                Contact con = new Contact();
                Campaign cam = new Campaign();

                    a.Name = z.name;
                    a.Emply_for_Ongoing_Edit__c = decimal.valueOf(z.Emply_Size__c);
                    a.BillingStreet = z.Street__c;
                    a.BillingCity = z.city__c;
                    a.BillingState = z.state__c;
                    a.BillingCountry = z.Country__c;
                    a.BillingPostalCode = z.Zip_Postal_Code__c;
                    a.website = z.website__c;

                    AccsForInsert.add(a);

                if(AccsForInsert.size()>0){
                    insert AccsForInsert;
                }   

                    //This is where I'm stuck
                    //con.AccountId = newlyCreatedAccountId
                    con.FirstName = z.first_name__c; 
                    con.LastName = z.last_name__c;
                    con.title = z.title__c;
                    con.email = z.email__c;
                    con.phone = z.phone__c;

                    ContactsForInsert.add(con);

                if(ContactsForUpdate.size()>0){
                    insert ContactsForInsert;
                }  

                /*

                    cam.Co_Sponsoring_Account__c = x.sponsor__c;
                    cam.name = x.name;
                    cam.country = x.country__c;

                    CampaignForInsert.add(cam);

                if(CampaignForInsert.size()>0){
                    insert CampaignForInsert;
                }
                */



            } 

        }
    }

}
1
  • con.AccountId = a.Id; Did this not work? – sfdcFanBoy Dec 31 '15 at 2:17
1

After insert AccsForInsert; is executed, each list element will contain the ID

You can see this in action at the example Apex doc for insert.

and, in the Apex DML doc, there is also

ID Values The insert statement automatically sets the ID value of all new sObject records.

Inserting a record that already has an ID—and therefore already exists in your organization's data—produces an error. See Lists for more information.

The insert and update statements check each batch of records for duplicate ID values. If there are duplicates, the first five are processed. For the sixth and all additional duplicate IDs, the SaveResult for those entries is marked with an error similar to the following: Maximum number of duplicate updates in one batch (5 allowed). Attempt to update Id more than once in this API call: number_of_attempts.

The ID of an updated sObject record cannot be modified in an update statement, but related record IDs can.

as for your non-bulkifed trigger, you're going to need to rewrite it to look something like the following:

if (Trigger.isInsert) {
  Account[] aInsList = new List<Account>();
  Contact[] cInsList = new List<Contact>();
  for (CustomObjZ__c z: Trigger.new)
    aInsList.add(new Account(a.name = z.name, a.nextFld = ..., ...));
  insert aInsList;

  for (Integer i = 0; i < Trigger.new.size(); i++) {
    CustomObjZ__c z = (CustomObjZ__c) Trigger.new[i];
    cInsList.add(new Contact(accountId = aInsList[0].id, firstName = z.firstName, ...));
  }

  insert cInsList;

  ... and so on for the Campaign
}

I've omitted the try-catch blocks and partial success process that you might want to introduce for clarity

3
  • Thanks crop, how would I actually grab that ID though. I've tried assigning it to a var but that didn't work since it's in a list. – Andrew Dec 31 '15 at 0:47
  • well, you have bigger problems in that your trigger is not bulkified; you need to insert Accounts for every customObjectZ that qualifies to have accounts inserted. I'll add some code to give you a start. In the meantime, read up on bulkified triggers in the Apex doc – cropredy Dec 31 '15 at 0:53
  • Thanks for the help, crop. I'll be sure to look more into bulkiFied Code. – Andrew Dec 31 '15 at 21:55
1

Bob Buzzard has a wonderful solution to this by creating an external Id field on the account object to form a relationship between the account and contact object

http://bobbuzzard.blogspot.com/2012/03/create-parent-and-child-records-in-one.html

solution code below

            Account a = new Account(
                DateTime_of_Last_Acct_Batch_Edit__c = datetime.now(),
                Name = z.Partner_Company_Name__c,
                Emply_for_Ongoing_Edit__c = decimal.valueOf(z.Average_Client_Size__c),
                BillingStreet = z.Street__c,
                BillingCity = z.city__c,
                BillingState = z.state__c,
                BillingCountry = z.Country__c,
                BillingPostalCode = z.Zip_Postal_Code__c,
                website = z.website__c,
                **ExternalIdField__c** = string.valueOf(z.id)
            );

            Contact con = new Contact(
                Account = new Account(**ExternalIdField__c** = string.valueOf(z.id)),
                FirstName = z.first_name__c,
                LastName = z.last_name__c,
                title = z.title__c,
                email = z.email__c,
                phone = z.phone__c
            );

            insert new List<Sobject>{a, con};
0

Instead of inserting the list AccsForInsert. I would just insert single account a. And use that Id (a.Id) in contact.

Here's the modified one. Let me know if this helps. (Yes this is not bulkified, but still should help you)

                a.Name = z.name;
                a.Emply_for_Ongoing_Edit__c = decimal.valueOf(z.Emply_Size__c);
                a.BillingStreet = z.Street__c;
                a.BillingCity = z.city__c;
                a.BillingState = z.state__c;
                a.BillingCountry = z.Country__c;
                a.BillingPostalCode = z.Zip_Postal_Code__c;
                a.website = z.website__c;

                insert a;

                //AccsForInsert.add(a);
                /*if(AccsForInsert.size()>0){
                   insert AccsForInsert;
                }*/   


                con.AccountId = a.Id;
                con.FirstName = z.first_name__c; 
                con.LastName = z.last_name__c;
                con.title = z.title__c;
                con.email = z.email__c;
                con.phone = z.phone__c;

                ContactsForInsert.add(con);

            if(ContactsForUpdate.size()>0){
                insert ContactsForInsert;
            }  
1
  • Thanks for the response, Sfdc. This didn't seem to work. I think the contact doesn't know which account to relate to. The account got created, but not the contact. – Andrew Dec 31 '15 at 16:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.