1

I need to write a trigger in which If I have an Account named 'Smith' and it doesnt have any related contacts when It is edited, its contact is created. I am doing this way but I am getting an error.

trigger AddRelatedContacts on Account (after insert, after update) 
{
    Set<Id> accIdSet = new Set<Id>();
    List<Contact> conList = new List<Contact>();
    for(Account acc :Trigger.New)
    {
       accIdSet.add(acc.id);
    }

   map<Id,Account> mapAccounts = new map<Id,Account>([Select id, name, (Select id, lastname 
                                                      From Contacts) From Account 
                                                          Where Id IN : accIdSet]);

for(Account acc : Trigger.New)
{
    Account a = new Account();
    a.id = mapAccounts.get(acc.Id);
    if(a.contacts.size <= 0)
    {
        Contact con = new Contact(); 
        con.accountId = a.id;
        con.lastname = a.name;
        conList.add(con);
    }
 }
 insert conList;   

}

Error message is : Error: Compile Error: Illegal assignment from Account to Id at line 17 column 9

1 Answer 1

4

This line a.id = mapAccounts.get(acc.Id);

mapAccounts.get(acc.Id) will return Account object in-order to get the Id

mapAccounts.get(acc.Id).Id

So you code will be like this

a.id = mapAccounts.get(acc.Id).Id;

You can minimize few line of code here

trigger AddRelatedContacts on Account (after insert, after update) 
{
    List<Contact> conList = new List<Contact>();
    map<Id,Account> mapAccounts = new map<Id,Account>([Select id, name,
                                                              (Select id, lastname 
                                                               From Contacts) 
                                                From Account Where Id IN : Trigger.New]);
    for(Account acc : Trigger.New)
    {
        if(mapAccounts.get(acc.Id).contacts.size() <= 0)
        {
            Contact con = new Contact(); 
            con.accountId = acc.Id;
            con.lastname = acc.name;
            conList.add(con);
        }
     }
    insert conList;
}
1
  • 1
    thanx its working..:)
    – Anzar
    Commented May 10, 2016 at 13:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .