Find your content:

Search form

You are here

how to Create Parent account using child account using trigger?

 
Share

Can some one please help me on this?

My requirement:

Once child account is created, it's respective (parent) account should also be created using trigger. The parent account's name should be "XXX account name"(a custom field on the child account) and it's key is "XXX account name-GSS" (another custom field on the child account).

I m new to triggers. I have created a trigger and parent account is also created, but the problem is that on " Child - Account mapping ", on Child account, "Parent" lookup is not being populated.

My Code:

for(Account ac: trigger.new) {

        newAccountName = ac.XXX_Account_Name__c ;
        newAccountKey = ac.XXX_Account_Name__c +'-'+ac.GSS__c;
        system.debug('---New Account Key --'+newAccountKey );

        acc = new Account();
        acc.name = newAccountName ;
        acc.Account_Key__c = newAccountKey ;

        accMap.put(ac.account_key__c,acc.account_key__c);

        accList.add(acc);

}
upsert accList;

Attribution to: Sandeep_Dobariya

Possible Suggestion/Solution #1

For starters I'm assuming this is an After Trigger. Consider using a static variable, so that the same trigger does not get invoked twice.

You are creating the Parent Account alright, all you need is for the Parent lookup to be set on the child.

trigger AccountAfter on Account(After Insert){

Map<Id, Account> childToParentAccountMap = new Map<Id, Account>{};

for(Account ac: trigger.new) {

        String newAccountName = ac.XXX_Account_Name__c ;
        String newAccountKey = ac.XXX_Account_Name__c +'-'+ac.GSS__c;
        system.debug('---New Account Key --'+newAccountKey );

        Account acc = new Account();
        acc.name = newAccountName ;
        acc.Account_Key__c = newAccountKey ;

        childToParentAccountMap.put(ac.Id, acc); //add to map child Id - Parent Acc

}

if(!childToParentAccountMap.isEmpty())
Database.upsert(childToParentAccountMap.values());

//Now that the parent Accounts have been created, use the Ids to set Parent on Child Accts
List<Account> childAccts = new List<Account>{};
for(Id accId : childToParentAccountMap.keySet())
childAccts.add(new Account(Id=accId, ParentId = childToParentAccountMap.get(accId).Id));

if(!childAccts.isEmpty())
Database.update(childAccts);

}

Attribution to: techtrekker
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/4515

My Block Status

My Block Content