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
Bob Lee 14Bob Lee 14 

I need help in apex trigger to insert record when checkbox is clicked

I need assistance in working on Trigger. I have a requirement, where I need to insert contact when Checkbox is clicked in account.

Eg: I have 3 checkboxes Electronics, Fashion, Furnitures. If I select 2 checkboxes Electronics and Fashion and save the Account. Then, I need to insert 2 contacts with field selected as Electronics and field selected as Fashion in another record.

I need assistance in this requirement.

Thanks.
Best Answer chosen by Bob Lee 14
sachinarorasfsachinarorasf
Hi Bob,
Please try it with below code:
 
Trigger accountTrigger on Account(after update){
Map<Id, List<String>> mapObj = new Map<Id, List<String>>();
List<Contact> contList = new List<Contact>();

for(Account accObj : trigger.New){
List<String> strList = new List<String>();
if(accObj.check_Elect__c == true){
strList.add('Electronics');
}if(accObj.check_Fash__c == true){
strList.add('Fashion');
}if(accObj.check_Furn__c == true){
strList.add('Furnitures');
}
if(!strList.isEmpty()){
mapObj.put(accObj.Id, strList);
}
}
if(!mapObj.isEmpty()){
Contact contObj;
for(Account accObj : trigger.New){
for(String str : mapObj.get(accObj.Id)){
contObj= new Contact();
contObj.Field__c = str;        // I am assuming Field__c is a picklist field with the values - Electronics,Fashion,Furnitures
contList.add(contObj);
}
}
}
if(!contList.isEmpty())    insert contList;
}
Also, you can take help from below link:
https://developer.salesforce.com/forums#!/feedtype=SINGLE_QUESTION_DETAIL&dc=Apex_Code_Development&criteria=BESTANSWERS&id=9062I000000Xts7QAC

Please mark it as best answer, if you find it helpful.

Thanks.
Sachin Arora