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
Vincent van Drunen LittelVincent van Drunen Littel 

Trigger that uses fields of different objects to create a new record on custom object

Hi, 
I was hoping someone would be able to help me on this one.. 
What I´m trying to do here is to create a new record on object targets using basic information from account and contact.
I need the trigger to create upon creation of a new contact to create a new record on object "target". But this contact is linked to an account and I'm unable to retrieve this information (contact name and account name) I've been checking out SOQL query 

 select id, Name, email, Cargo__c, 
        (select Name from Accounts) 

Which on workbench retrieved the exact info i needed. 
Now trying to implement this in my trigger is the problem, anyone has any idea??

trigger TestTarget on Contact(after insert, after update){
    List targets = new List();
    for (Contact t : trigger.new){
        Target__c newtar = new Target__c();
         select id, Name, email, Cargo__c, 
        (select Name from Accounts)
        from contact;
        newtar.Target__c = acc.Name;
        newtar.Name = con.Name;
        insert tarlist;
   
   }
}

 

Best Answer chosen by Vincent van Drunen Littel
Krishna SambarajuKrishna Sambaraju
You have a master detail relationship with contact (Field: Target__c) and you also created another lookup relationship (field: Name__c) which is not needed.

After reviewing the fields, here is how the trigger should be.
 
trigger TargetsContacts on Contact (after insert) {
	List<Contact> contacts = [select Id, Name, AccountId, Account.Name from Contact Where Id in :Trigger.new];
	List<Target__c> targetList = new List<Target__c>();
    for(Contact con : contacts){
            Target__c target = new Target__c();
            target.Target_del__c = con.AccountId; 
            target.Name = con.Name;
            target.Target__c = con.Id;
            targetList.add(tar);
    }
    if(!targetList.size() > 0){
        try{
            insert targetList;
        } catch(DMLException e){
            system.debug('Following Exceptions occurred'+e.getmessage());
        }
    }
}

 

All Answers

SarfarajSarfaraj
Vincent,

This is what can be done with bare minimum modification of your code,
trigger TestTarget on Contact(after insert, after update){
    List targets = new List();
	List contactList = [select id, Name, email, Cargo__c, Account.Name from contact Where Id in :Trigger.new];
    for (Contact t : contactList){
        Target__c newtar = new Target__c();
        newtar.Target__c = t.Account.Name;
        newtar.Name = t.Name;
        targets.add(tarlist);
   }
   insert targets;
}
Following are some items that you may consider,
  • Create a lookup to Contact in object Target and populate this field value while creating the record.
  • Use the contact value to get the related records from Target object in the contact update operation, and update the records instead of inserting everytime. But this depends on your requirement.
Let me know if this solves your requirement.

--Akram
Vincent van Drunen LittelVincent van Drunen Littel

Hi Akram, 
 

thank you for the quick reply
I got an error from the script you gave 
Error: Compile Error: unexpected token: 'List' at line 2 column 4

What I have been basing my work on is the below.. if that would make any sense
I was trying to add SOQL query to the script below. As this one works but only grabs field info from only 1 object (contact) (what i really want is that it grabs the Contact name and Account name (of that contact)

SOQL query
select id, Name, email, Cargo__c, 
        (select Name from Accounts) 

Script that is working and implemented but not sufficient
trigger TargetsContacts on Contact (after insert) {
List conList = new List();
    for(Contact con : Trigger.New){
            Target__c tar = new Target__c();
            tar.Target__c = con.Id;
            tar.Name = con.Name;
            tar.Telefone__c = con.Phone;
            conList.add(tar);
    }
    if(!conList.IsEmpty()){
        try{
            insert conList;
        } catch(Exception e){
            system.debug('Following Exceptions occured'+e.getmessage());
        }
    }
}

If you know/ would be able to combine these two and I will be very happy 

SarfarajSarfaraj
I have modified your code to meet your requirement,
trigger TargetsContacts on Contact (after insert) {
	List contactList = [select Id, Name, email, Account.Name from Contact Where Id in :Trigger.new];
	List conList = new List();
    for(Contact con : contactList){
            Target__c tar = new Target__c();
            tar.Target__c = con.Id;
            tar.Name = con.Name;
			tar.AccountName__c = con.Account.Name; /*Replace AccountName__c with your desired field name*/
            tar.Telefone__c = con.Phone;
            conList.add(tar);
    }
    if(!conList.IsEmpty()){
        try{
            insert conList;
        } catch(Exception e){
            system.debug('Following Exceptions occured'+e.getmessage());
        }
    }
}

I have assumed you have one custom field AccountName__c in the object Target__c. This will store the name of the account. If you have any other field for this purpose, please replace the api name as applicable or create new field to store the account name.
Vincent van Drunen LittelVincent van Drunen Littel
Again got the same error 

Error: Compile Error: unexpected token: 'List' at line 3 column 4

I added to line 2 but didnt make a chance ...
List conList = new List();


these are all the fields in Target__cUser-added image
SarfarajSarfaraj
Something strange is happening. All angular bracets and contents within them is being deleted. Here is one more attempt with escape characters. If this does not work I will post an image of the code.
trigger TargetsContacts on Contact (after insert) {
	List<Contact> contactList = [select Id, Name, email, Account.Name from Contact Where Id in :Trigger.new];
	List<Target__c> conList = new List<Target__c>();
    for(Contact con : contactList){
            Target__c tar = new Target__c();
            tar.Target__c = con.Id;
            tar.Name = con.Name;
			tar.AccountName__c = con.Account.Name; /*Replace AccountName__c with your desired field name*/
            tar.Telefone__c = con.Phone;
            conList.add(tar);
    }
    if(!conList.IsEmpty()){
        try{
            insert conList;
        } catch(Exception e){
            system.debug('Following Exceptions occured'+e.getmessage());
        }
    }
}

 
Vincent van Drunen LittelVincent van Drunen Littel
Hi Akram,

I'm back to one of the errors i got before which made go look into the SOQL query ...

Error: Compile Error: Invalid field AccountName__c for SObject Target__c at line 8 column 13

It's like it doesnt to agree that AccountName__c exists.. 

Thank you for the help!!
Vincent van Drunen LittelVincent van Drunen Littel
I changed the AccountName__c for Target_del__c, which is the Account Lookup field and received this message when i tested saving a new client.
Never seen this before!
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger TargetsContacts caused an unexpected exception, contact your administrator: TargetsContacts: execution of AfterInsert caused by: System.StringException: Invalid id: Winnie the pooh 2: Trigger.TargetsContacts: line 8, column 1
Krishna SambarajuKrishna Sambaraju
Hi Vincent,

Try this.

trigger TargetsContacts on Contact (after insert) {
    List contacts = [select Id, Name, AccountId, Account.Name from Contact Where Id in :Trigger.new];
    List targetList = new List();
    for(Contact con : contacts){
            Target__c target = new Target__c();
            target.Target_del__c = con.AccountId; //if Target__c is a lookup to Account.target.Target__c = con.Account.Name;
            target.Name = con.Name;
            targetList.add(target);
    }
    if(!targetList.size() > 0){
        try{
            insert targetList;
        } catch(DMLException e){
            system.debug('Following Exceptions occurred'+e.getmessage());
        }
    }
}

Hope this works.
Vincent van Drunen LittelVincent van Drunen Littel
Hi Krishna,

I'm getting this error with that script..

Error: Compile Error: unexpected token: 'List' at line 2 column 4
Vincent van Drunen LittelVincent van Drunen Littel
Still the same error :/
Vincent van Drunen LittelVincent van Drunen Littel
Unfortunately still getting 
Error: Compile Error: unexpected token: 'List' at line 2 column 4
Krishna SambarajuKrishna Sambaraju
There is some issue with the escape characters.
 
trigger TargetsContacts on Contact (after insert) {
	List<Contact> contacts = [select Id, Name, AccountId, Account.Name from Contact Where Id in :Trigger.new];
	List<Target__c> targetList = new List<Target__c>();
    for(Contact con : contacts){
            Target__c target = new Target__c();
            target.Target__c = con.AccountId; 
            target.Name = con.Name;
            targetList.add(tar);
    }
    if(!targetList.size() > 0){
        try{
            insert targetList;
        } catch(DMLException e){
            system.debug('Following Exceptions occurred'+e.getmessage());
        }
    }
}



 
Krishna SambarajuKrishna Sambaraju
Hope the above code works for you now. Change the lookup field accordingly.
Vincent van Drunen LittelVincent van Drunen Littel
The trigger saved successfully, but now when testing, creating a new contact upon save get this error again

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger TargetsContacts caused an unexpected exception, contact your administrator: TargetsContacts: execution of AfterInsert caused by: System.StringException: Invalid id: Acme System S/A: Trigger.TargetsContacts: line 6, column 1

 
Krishna SambarajuKrishna Sambaraju
Did you use the same code above? It seems like it is trying to put the Account Name in the Id field. Make sure you are setting the AccountId to the Account lookup field and not the name of the account.
 
Vincent van Drunen LittelVincent van Drunen Littel

I changed it just a little bit because had some errors, 

trigger TargetsContacts on Contact (after insert) {
    List contacts = [select Id, Name, AccountId, Account.Name from Contact Where Id in :Trigger.new];
    List targetList = new List();
    for(Contact con : contacts){
            Target__c target = new Target__c();
            target.Target__c = con.AccountId; 
            target.Name = con.Name;
            targetList.add(target);
    }
    if(!targetList.IsEmpty()){
        try{
            insert targetList;
        } catch(DMLException e){
            system.debug('Following Exceptions occurred'+e.getmessage());
        }
    }
}

 

Now when I tested saving a new contact, it saved but didnt create a new target.. 

Krishna SambarajuKrishna Sambaraju
What is the relationship between Contact object and the Target__c object. If it is master detail relationship, make sure you set the ContactId on the Target__c object as below.
 
trigger TargetsContacts on Contact (after insert) {
	List<Contact> contacts = [select Id, Name, AccountId, Account.Name from Contact Where Id in :Trigger.new];
	List<Target__c> targetList = new List<Target__c>();
    for(Contact con : contacts){
            Target__c target = new Target__c();
            target.Target__c = con.AccountId; 
            target.Name = con.Name;
            target.Contact__c = con.Id;// change the field Contact__c according to your relationship field.
            targetList.add(tar);
    }
    if(!targetList.size() > 0){
        try{
            insert targetList;
        } catch(DMLException e){
            system.debug('Following Exceptions occurred'+e.getmessage());
        }
    }
}

 
Vincent van Drunen LittelVincent van Drunen Littel

Hi Krishna, changing AccountId to ContactId generates this error
Error: Compile Error: Invalid field ContactId for SObject Contact at line 6 column 32

Contacts is the master detail relationship.. 
A thing i noticed was that with this code looks like the account name of the contact is not "duplicated/created" on object target. 

What i have been doing was using the code you helped me with last week and trying to change it so it would bring account name with the creation.

In a previous post i put a picture of all fields on Target if that might help.

Thanks!

Krishna SambarajuKrishna Sambaraju
You have a master detail relationship with contact (Field: Target__c) and you also created another lookup relationship (field: Name__c) which is not needed.

After reviewing the fields, here is how the trigger should be.
 
trigger TargetsContacts on Contact (after insert) {
	List<Contact> contacts = [select Id, Name, AccountId, Account.Name from Contact Where Id in :Trigger.new];
	List<Target__c> targetList = new List<Target__c>();
    for(Contact con : contacts){
            Target__c target = new Target__c();
            target.Target_del__c = con.AccountId; 
            target.Name = con.Name;
            target.Target__c = con.Id;
            targetList.add(tar);
    }
    if(!targetList.size() > 0){
        try{
            insert targetList;
        } catch(DMLException e){
            system.debug('Following Exceptions occurred'+e.getmessage());
        }
    }
}

 
This was selected as the best answer
Vincent van Drunen LittelVincent van Drunen Littel
Krishna you did it again!!! 

You rock!! 

Thank you so much for once again resolving my problem!!