+ Start a Discussion
SkrzyniaSkrzynia 

Set contact as primary if value of field is bigger than another one

Hi. 
I'm new in apex and I need help :).
I have an value field in Contact Object and I need to set primary contact for Account whose value is bigger than another contacts value fields;

For Example
Contact1 has value field = 1;
Contact 2 has value field = 2;

i need to make Contact 2 as a primary contact for account;

Thanks for help.

 
GovindarajGovindaraj
Hi,

Below sample code will help you,
trigger SetPrimaryContact on Contact(after insert,after update) {
	set<Id> accountIdSet = new set<Id>();
	list<AccountContactRole> accConList = new list<AccountContactRole>();
	for(Contact con : trigger.new) {
		accountIdSet.add(con.AccountId);
	}
	list<Contact> contactList = [SELECT AccountId, Value__c FROM Contact WHERE AccountId IN :accountIdSet];
	for(Integer i=0; i<contactList.size(); i++) {
		for(Integer j=i+1;j<contactList.size();j++) {
			if(contactList[i].Value__c  < contactList[j].Value__c) {
				list<Contact> temp = contactList[i];
				contactList[i] = contactList[j];
				contactList[j] = temp;				
			}
		}
	}
	for(Contact conObj : contactList[0]) {
		AccountcontactRole accConObj = new AccountcontactRole();
		accConObj.contactId = conObj.Id;
                accConObj.Role = 'Decision Maker'; //Change whatever you want
                accConObj.AccountId = conObj.AccountId;        
                accConObj.Isprimary = true;
                accConList.add(accConObj);
	}
	insert accConList;
}

* This is just a sample code. Please modify as per your requirement.

Thanks,
Govindaraj.S
GovindarajGovindaraj
Please keep the community clean by closing solved cases. Thanks !