function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
rushirushi 

insert record when account has affiliation

Hello,

 Account object has   territory field and affiliation child objects with lookup relation
how to write a trigger on territory field  object
i.e record has to be  inserted in  territory field  object when the lookup account has affiliation

could  you please give me a snapshot of code

Thanks in advance..
Best Answer chosen by rushi
Anupam RastogiAnupam Rastogi
Hi Rushi,

Here is the modified code.
trigger checkAccount on Territory_Field__c (before insert,before update) {
    
    Map<Id, Id> AccT;
    Map<Id, Id> AccAff;
	
    //--- Create a Map containing the Territory Record Ids and their Account Ids
    for(Territory_Field__c  t : [select Account__c from Territory_Field__c where Id in :trigger.new])
        AccT.put(t.Id, t.Account__c);
    //--- Create a Map containing the Affiliation Record Ids and their Account Ids
	for(Affiliation__c aff : [select Account__c from Affiliation where Account__c in :a]) 
		AccAff.put(aff.Account__c, aff.Id);
    //--- Check if the maps contain the affiliation record for the account of the territory record
    for(Territory_Field__c t : Trigger.new) {
        if(!AccAff.containsKey(AccT.get(t.Id)))
        	//--- Throw Error
    }
}

Thanks
AR

All Answers

Jigar.LakhaniJigar.Lakhani

Hello,

I assume that Account object is parent object, Territory and Affiliation are child object which are related to account object. So we can say that account have multiple territory and affiliation records.
And your requirement is that if any account record have affiliation record insert at the same time territory record should also create.

If my assumption is correct then below is the trigger to created territory reocrd.

May be you need to update object and field API names in below code.

trigger AffiliationTrigger on Affiliation__c (AFTER INSERT) {
	
	// After Insert Trigger
	if (Trigger.IsAfter && Trigger.IsInsert) {
		List<Territory__c> listTerritory = new List<Territory__c>();
		for (Affiliation__c objAffiliation:Trigger.New) {
			if (objAffiliation.Account__c != null) {
				Territory__c objTerritory = new Territory__c();
				objTerritory.Account__c = objAffiliation.Account__c;
				// YOU CAN ASSIGN OTHER FIELDS OF TERRITORY HERE
				listTerritory.Add(objTerritory);
			}
		}
		if (listTerritory != null && listTerritory.size() > 0) {
			Insert listTerritory;
		}
	}
	
}

 


Thanks & Cheers,
Jigar(pateljb90@gmail.com)

 

Anupam RastogiAnupam Rastogi
Hi Rushi,

This is what I understood about your requirement - 

You need to create a new Territory Field record when you are associating an Affiliation record with the Account. Considering this to be correct, you need to create a trigger on the Affiliation object and NOT on the Territory Field object. Because the trigger is happening when the Affiliation record is getting associated with an Account. The sample code should look something like this - 
trigger ActionsOnAffiliation on Affiliation__c (after update) {
    
    for(Affiliation__c aff : Trigger.new)
    {
        Affiliation__c affOldId  = Trigger.oldMap.get(aff.ID);
        Affiliation__c affOld = [select Account__c from Affiliation__c where Id = :affOldId];
        
        //--- Check if the Account field on the Affiliation object changed
        if((aff.Account__c != affOld.Account__c) && (aff.Account__c != ""))
        {
            //--- Write the code that you wish to perform on the 'Territory Field' object 
        }
    }

}

Thanks
AR

If you find this reply useful then please mark it as best answer.
rushirushi
Thank you for taking time
but  my requirement is

when I try to create/update  record on territory field object
the lookup account field must have atleast one affiliation
otherwise the record won't be saved

trigger checkAccount on Territory_Field__c (before insert,before update) {
  
  List<Account> a = [select IDfrom Account where ID in(select Account__c from Affiliation__c) ];
  
  for(Territory_Field__c  c :trigger.new){
  
    for(Account acc : a ){
          if( c.Account__c == acc.id ){
            system.debug('insert is successful');
             break;              
           }}
    
}
 
}

i tried this code
but it is not working
Jigar.LakhaniJigar.Lakhani

Hello,

As per you clearification, I assume that before insert or update any territory field record, you need to check that if account(which is related to inserted/updated territory field record) have any affiliation exist or not. And if there is no any affiliation record exist in selected account then you need to give validation message like please enter affiliation in account, otherwise need to insert territory field record without any validation.

If my assumption is correct, below is apex trigger and apex class code.

Apex Trigger

trigger checkAccount on Territory_Field__c (before insert,before update) {

	// Before Insert Trigger
	if (Trigger.IsBefore && Trigger.IsInsert) {
		List<Territory_Field__c> listTerritory = new List<List<Territory_Field__c>();
		for (Territory_Field__c objTerritory:Trigger.New) {
			if (!String.IsBlank(objTerritory.Account__c)) {
				listTerritory.Add(objTerritory);
			}
		}
		if (listTerritory != null && listTerritory.size() > 0) {
			checkAccountTriggerHandler.validateAccountAffiliation(listTerritory);
		}
	}

	// Before Update Trigger
	if (Trigger.IsBefore && Trigger.IsUpdate) {
		List<Territory_Field__c> listTerritory = new List<List<Territory_Field__c>();
		for (Territory_Field__c objTerritory:Trigger.New) {
			if (objTerritory.Account__c != Trigger.OldMap.get(objTerritory.Id).Account__c) {
				listTerritory.Add(objTerritory);
			}
		}
		if (listTerritory != null && listTerritory.size() > 0) {
			checkAccountTriggerHandler.validateAccountAffiliation(listTerritory);
		}
	}

}


Apex Class

public class checkAccountTriggerHandler{
	
	public static void validateAccountAffiliation(List<Territory_Field__c> listTerritory) {
		
		Set<Id> setAccountId = new Set<Id>();
		for (Territory_Field__c objTerritory:listTerritory) {
			setAccountId.Add(objTerritory.Account__c);
		}
		
		Map<Id,Account> mapAccountWithAffiliation = new Map<Id,Account>([SELECT ID,Name,(SELECT Id,Name FROM Affiliations__r LIMIT 1) FROM Account WHERE Id In:setAccountId]);
		
		if (mapAccountWithAffiliation != null && mapAccountWithAffiliation.size() > 0) {
			for (Territory_Field__c objTerritory:listTerritory) {
				if (mapAccountWithAffiliation.get(objTerritory.Account__c) != null) {
					Account objAccount = mapAccountWithAffiliation.get(objTerritory.Account__c);
					if (objAccount.Affiliations__r == null || (objAccount.Affiliations__r != null && objAccount.Affiliations__r.size() == 0)) {
						objTerritory.AddError('Related account have no affiliations, please add affiliation in account.');
					}
				}
			}
		}
	}
	
}
 

Thanks & Cheers,
Jigar(pateljb90@gmail.com)

Anupam RastogiAnupam Rastogi
Hi Rushi,

Here is the modified code.
trigger checkAccount on Territory_Field__c (before insert,before update) {
    
    Map<Id, Id> AccT;
    Map<Id, Id> AccAff;
	
    //--- Create a Map containing the Territory Record Ids and their Account Ids
    for(Territory_Field__c  t : [select Account__c from Territory_Field__c where Id in :trigger.new])
        AccT.put(t.Id, t.Account__c);
    //--- Create a Map containing the Affiliation Record Ids and their Account Ids
	for(Affiliation__c aff : [select Account__c from Affiliation where Account__c in :a]) 
		AccAff.put(aff.Account__c, aff.Id);
    //--- Check if the maps contain the affiliation record for the account of the territory record
    for(Territory_Field__c t : Trigger.new) {
        if(!AccAff.containsKey(AccT.get(t.Id)))
        	//--- Throw Error
    }
}

Thanks
AR
This was selected as the best answer
rushirushi
Hi Anupam,
Thank you for giving me the idea to use map

 I modified above code like this
 now it is working fine

trigger checkAccount on Territory_Field__c (before insert, before update) {
 Map<ID,ID> mapAff = new Map<ID,ID>();
 List<Affiliation__c > a =[select Account__c ,ID from Affiliation__c where Account__c !=null];
//create a map for affiliation 
 for(Affiliation__c  aff:a){
  mapAff.put(aff.Account__c  ,aff.ID);
 }
 //
 for(Territory_Field__c tf:trigger.new){
  if(!(mapAff.ContainsKey(tf.Account__c)) ){
     f.addError('account dont have affiliation choose another account');
  }
 }
Anupam RastogiAnupam Rastogi
Hi Rushi,

Good that your problem is resolved. 
If my reply helped you solve the problem please mark it as best answer.

Thanks
AR