+ Start a Discussion
Pranav ChitransPranav Chitrans 

Trigger to insert Value in lookup field

Want to write a trigger in such a way that when ever A new accoutn is getting created the Lookup filed on acccount with named "Parent Account" should filled withe the account name...along with that create the contact with the same name of account name.. i had written the code.. in which after inserting Account ,Contact is getting created.. but how to perform th logic.. that with the same name.. Parent Account should Populated...
trigger insertContact on Account (after Insert, after Update) 
{
 if(trigger.isInsert && trigger.IsAfter)
 {
  List<Contact> lstCon = new List<Contact>();
  for(Account acc : trigger.New)
  {
   Contact con = new Contact();
   con.LastName = acc.Name;
   con.AccountId = acc.id;   
   lstCon.add(con);
  }
  insert lstCon;
 }
}

 
Shashi PatowaryShashi Patowary
Hi Pranav,

You can set the lookup field in a before trigger itself -
 
trigger updateParent on Account (before Insert, before Update) {

  //Query your parent account
 
   for (Account acc : Trigger.New) {
      acc.parent__c = parentId;
   }

}

Please let me know if this is helpful.

Regards,
Shashi
Pranav ChitransPranav Chitrans
hey Shashi Patowary,
Variable does not exist: ParentId
Shashi PatowaryShashi Patowary
Hi Pranav,

From where are you planning to fetch parent id ? I just put a comment to fetch parent account. Please write a SOQL query to fetch parent account.

regards,
Shashi

 
Pranav ChitransPranav Chitrans
[select id from Accounts where id = : runtimegeneratedId]
 
Naval Sharma4Naval Sharma4
In case if you are trying to assign the same account as a parent account then it will throw an error "A parent account can't be the child of an account it's already a parent of.".
So first you have to query that account id which you will use as a parent of the account record which got inserted.
or create one if you don't found with the same name.
trigger insertContact on Account (after Insert, after Update) { 
   if(trigger.isInsert && trigger.IsAfter) { 
       List<Contact> lstCon = new List<Contact>(); 
       Map<String, Account> accMap = new Map<String,Account>();
       for(Account accRec : [Select, name from account where id != Trigger.newMap.keySet()]){     
           accMap.put(accRec.name, accRec);
       }
       for(Account acc : trigger.New) { 
           Contact con = new Contact(); 
           con.LastName = acc.Name; 
           con.AccountId = acc.id; 
           acc.parent = accMap.get(acc.name);
           lstCon.add(con); 
       } 
       update Trigger.new;
       insert lstCon; 
    } 
}
Pranav ChitransPranav Chitrans
hey Naval Sharma,
I tried your above code.. there are some code minnor in line 5 like after select there will be no comma(,) and after that in the same line where id != : (semicolon will be there..but after editing this.. it shows the error on record page while jao)

Error : Review all error messages below to correct your data.
Apex trigger insertContact caused an unexpected exception, contact your administrator: insertContact: execution of AfterInsert caused by: System.FinalException: Record is read-only: Trigger.insertContact: line 13, column 1
 
Shashi PatowaryShashi Patowary
trigger updateParent on Account (before Insert, before Update) {

Account pAcc = [select id from Accounts where id = : runtimegeneratedId Limit 1];
 
   for (Account acc : Trigger.New) {
      acc.parent__c = pAcc ;
   }

}
Please try this if it works.

Regards,
Shashi
RaghvendraRaghvendra
Updating the Parent Account should be done in Before trigger because you cannot perform th DML operation on same Account record.

To insert a new Contact you need the AccountId, so it should be done in after trigger.
Please see the below code. Hope that help.
 
trigger insertContact on Account (after Insert, after Update, before insert, before update) {  
    if(trigger.IsAfter) {
        List<Contact> lstCon = new List<Contact>();
        for(Account acc : trigger.New) {
			lstCon.add(new Contact(LastName = acc.Name, AccountId = acc.id));
        }
        insert lstCon;
    }
	if(trigger.isBefore){
		Map<String, Account> accMap = new Map<String,Account>();   
		for(Account accRec : [Select name from account where id !=: Trigger.newMap.keySet()]){   
			accMap.put(accRec.name, accRec);   
		}
		acc.parent = accMap.get(acc.name);
	}
}


 
Pranav ChitransPranav Chitrans
hey Raghvendra,
 at line 14 .. how u used acc.parent.. this variable would not be accessibke because the instance u used at line 4 is under the loop which ends on line 6.. so there will be an error on acc.parent...
RaghvendraRaghvendra
You are right. line # 14 must be in a for loop on trigger.new. I wrote this code on the go just to give an idea. Please fix any syntax issues if found.
 
trigger insertContact on Account (after Insert, after Update, before insert, before update) {  
    if(trigger.IsAfter) {
        List<Contact> lstCon = new List<Contact>();
        for(Account acc : trigger.New) {
			lstCon.add(new Contact(LastName = acc.Name, AccountId = acc.id));
        }
        insert lstCon;
    }
	if(trigger.isBefore){
		Map<String, Account> accMap = new Map<String,Account>();   
		for(Account accRec : [Select name from account where id !=: Trigger.newMap.keySet()]){   
			accMap.put(accRec.name, accRec);   
		}
		for(Account acc : trigger.New){
			acc.parent = accMap.get(acc.name);
		}
	}
}

 
Pranav ChitransPranav Chitrans
hey Raghvendra,
its giving error on edit page while sving new Account.
insertContact: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.insertContact: line 11, column 1
RaghvendraRaghvendra
As I said, you have to check for some syntax issues.
 

 

 
RaghvendraRaghvendra
May be you dont have any Account with same name. In that case it would not found any Account in accMap with same name, results in null pointer exception. Before line # 15 put below condition
if(accMap.containsKey(acc.name))

 
Pranav ChitransPranav Chitrans
hey Raghvendra,
it still giving the same error
Pranav ChitransPranav Chitrans
here the final code
trigger ConTest on Account(after insert,after Update)
{
 if(trigger.isInsert && trigger.isAfter)
 {
  List<Contact> lstCon = new List<Contact>();
  for(Account acc : trigger.new)
  {
   Contact con = new Contact();
   con.lastName=acc.Name;
   con.AccountId = acc.Id;
   lstCon.add(con);
  }
  insert(lstCon);
 }
 
 if(trigger.isUpdate && trigger.isAfter)
 {
  Map<Id,Account> mapACC = new Map<Id,Account>([select (select id,name from contacts) from account where id IN: trigger.new]);
  List<Contact> newCon = new List<Contact>();
  for(Account updatedAcc : trigger.New)
  {
   Account oldAcc = trigger.oldMap.get(updatedAcc.Id);
   if(mapACC.ContainsKEY(updatedAcc.Id) && oldAcc.Name != updatedAcc.Name)
   {
    for(Contact con : mapACC.get(updatedAcc.Id).contacts)
    {
     con.lastname = updatedAcc.Name;
     newCon.add(con);
    }
   }
  }
  update newCon;
 }
}