You need to sign in to do that
Don't have an account?
Pranav 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; } }
You can set the lookup field in a before trigger itself -
Please let me know if this is helpful.
Regards,
Shashi
Variable does not exist: ParentId
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
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.
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
Regards,
Shashi
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.
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...
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
it still giving the same error