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
gokubigokubi 

Triggers: creating related objects

Before a Contact is created I want to see if it has been related to an existing Custom Object called "ONEN_Household__C". If it hasn't, I want to create that Custom Object, then get the id of the new object, creating the Contact with that reference recorded.

Here's what I've got so far:
Code:
trigger HouseholdCheck on Contact bulk (before insert) {
         
  for (Contact c : Trigger.new) {
    if (c.ONEN_Household__c == NULL) {
      c.Description='No Household';
      insert new ONEN_Household__c (Name=c.firstname + ' ' + c.lastname + ' Household');
    }
  }
}
After I do the insert new ONEN_Household__C, how do I get that new object's Id?

Thanks!

Steve
 

SuperfellSuperfell
Hey Steve, You need to hold a reference to the object you created, its Id will get populated after the create call, so you need something like
ONEN_Household__c hh = ew ONEN_Household__c (Name=c.firstname + ' ' + c.lastname + ' Household');
insert hh;
system.debug('new household id is ' + hh.id);


    
gokubigokubi
Thanks Simon. That got me there. You inadvertantly left the "n" off of "new" in your code, but that's it! Thanks!
gokubigokubi
Man, do you know what you guys are building here? My first Apex trigger replaces 400+ lines of a custom data input S-Control with these 27 lines of code. This is my fist Apex code. It took me 2 hours from when I first opened up the Apex manual.
trigger HouseholdCheck on Contact bulk (before insert) {
    
  for (Contact c : Trigger.new) {
    if (c.ONEN_Household__c == NULL) {
      String RecognitionName;   
      RecognitionName = c.firstname + ' ' + c.lastname;
   
      ONEN_Household__c hh = new ONEN_Household__c (    
        Name=RecognitionName + ' Household',
        Recognition_Name__c=RecognitionName,
        Recognition_Name_Short__c=c.firstname,
        MailingStreet__c=c.MailingStreet,
        MailingCity__c=c.MailingCity,
        MailingState__c=c.MailingState,
        MailingPostalCode__c=c.MailingPostalCode,
        MailingCountry__c=c.MailingCountry    
      );
      insert hh;
      c.ONEN_Household__c = hh.id;
    }
    if (c.AccountId == NULL) {
      Account[] account = [select id from account where Name = 'Individual'];
      c.AccountId = account[0].Id;
    }
  }
}
This is really unbelievable how powerful and easy Apex is. I'm blown away on day 1...

Thanks!