+ Start a Discussion
uday kumar yuday kumar y 

I have two objects like Account and Contact if Account Name and Contact Last Name is Same but Account Id is Null

trigger updatepho on Contact (before update){
List<Contact> con = new List<Contact>();
List<Account> acc = [select Id from Account where Name =: con[0].LastName];
    if(con[0].AccountId == null){
        for(Contact c:con){
            c.AccountId = acc[0].Id;
    update con;
My error Description:Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger updatepho caused an unexpected exception, contact your administrator: updatepho: execution of BeforeUpdate caused by: System.ListException: List index out of bounds: 0: Trigger.updatepho: line 3, column 1
Could you please let us know the clear requirement on what do you need ? 
Hello Uday,

What is your requirement Can you tell us in little more depth?
So far this is what I am understanding.
Create a trigger which joints contact to the account whenever it has something to do with Last Name.. 
Let's explore the requirement because it's looks like it is definitely possible with trigger.
Thank You!
Ahmad J. KoubeissyAhmad J. Koubeissy
trigger contactbeforeInsert on Contact (before Insert,before update){
    set<string> ContactLastNames= new set<string>();
    for(contact con:trigger.new){
            if(Trigger.oldMap.get(con.id).LastName != con.lastName){

    map<string,string> mapAccountNameToID = new map<string,string>();
    list<account> Accounts= [select id,name from account where name in: ContactLastNames];
    for(Account acc: Accounts){

    for(contact con:trigger.new){
            con.accountid = mapAccountNameToID.get(con.lastname.toLowerCASE());

Kindly don't forget to Mark as Best Answer if it solves your question.