+ Start a Discussion
SF Beginner 2019SF Beginner 2019 
How to call this apex class to make it a batch job?
 
public class ApplicationYearsinService{

    public static void YearsinService(List<Application__c> appList){
        //Declares the Variables, List, ID to be used
        Date dat = System.today();
        Integer yr = dat.year();   
        Map<Id, Set<Integer>> setofYear = new Map<Id, Set<Integer>>();
        Set<Id> accountIdSet = new set<Id>();
        
        //Gets the values of the Account(Account__c from the Application
        for(Application__c cs: appList ){
            accountIdSet.add(cs.Account__c);            
        }
        
        //Query in the Application to get the value from the Account
        for(Application__c p : [SELECT ID, Account__c, Received_Date__c from Application__c where Account__c IN : accountIdSet ]){
            if(p.Received_Date__c != null){
                if(setofYear.containskey(p.Account__c)){
                    if(p.Received_Date__c != NULL) {
                        setofYear.get(p.Account__c).add(p.Received_Date__c.Year());
                    }
                }
                else {
                    setofYear.put(p.Account__c, new Set<Integer>{p.Received_Date__c.Year()});
                }     
            }
        }
        
        Map<String, List<Application__c>> appMap = new Map<String ,List<Application__c>>();
        Map<String, Account> lisAcct = new  Map<String, Account>();
        List<Account> acctToUpdate = new  List<Account>();
        List<Account> accountListToLoop = [Select Id, YearsinService__c, (Select Id FROM Applications__r LIMIT 1) from Account where Id=:accountIdSet];
        for(Account acc: accountListToLoop){
            lisAcct.put(acc.Id+'', acc);
        }       
        for(Account act : accountListToLoop ){
            if(setofYear.containskey(act.id)){
                act.YearsinService__c = setofYear.get(act.id).size();
                acctToUpdate.add(act);
                lisAcct.remove(act.Id+'');
            }
            else {
                act.YearsinService__c = 0;
                acctToUpdate.add(act);
            }
        }
        Database.upsert(acctToUpdate, false); 
    }
}

 
Best Answer chosen by SF Beginner 2019
Ajay K DubediAjay K Dubedi
Hi SF,
Write below scheduler for call ApplicationYearsinService class to make it a batch job. And Instead of params pass Application__c list.

global with sharing class ApplicationYearsinService_Scheduler implements Schedulable {

    Public static void SchedulerMethod() {
        string timeinterval = '0 0 0 1/1 ? ';
        System.schedule('Batch Class will run every day at 12:00 AM',timeinterval, new ApplicationYearsinService_Scheduler());
    }
    global void execute(SchedulableContext SC) {
        ApplicationYearsinService.YearsinService(params);
    }

}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
RarLopzRarLopz 
Why does my chart has month names on wedges but the sample example doesn't ? 

In my sandbox I  copied and pasted exact code from the salesforce documentation as shown here https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_charting_overview_simple_example.htm

Created a Apex Controller, Created a Wrapper Class, Created a VFP.
 
The output as shown in this example doesn't have month names on the wedges. However the output I get has month names on the wedges. This example doesn't uses rendererFn property. I am wondering why i see month names and the example shown does'nt?

This is my output 
User-added imageHowever I was expecting to see this 

User-added image

Here the Code exactly as copied from the documentation 
 
<apex:page controller="PieChartController" title="Pie Chart">
    <apex:chart height="350" width="450" data="{!pieData}">
        <apex:pieSeries dataField="data" labelField="name"/>
        <apex:legend position="right"/>
    </apex:chart>
</apex:page>



public class PieChartController {
    public List<PieWedgeData> getPieData() {
        List<PieWedgeData> data = new List<PieWedgeData>();
        data.add(new PieWedgeData('Jan', 30));
        data.add(new PieWedgeData('Feb', 15));
        data.add(new PieWedgeData('Mar', 10));
        data.add(new PieWedgeData('Apr', 20));
        data.add(new PieWedgeData('May', 20));
        data.add(new PieWedgeData('Jun', 5));
        return data;
    }

    // Wrapper class
    public class PieWedgeData {

        public String name { get; set; }
        public Integer data { get; set; }

        public PieWedgeData(String name, Integer data) {
            this.name = name;
            this.data = data;
        }
    }
}

 
Best Answer chosen by RarLopz
Dushyant SonwarDushyant Sonwar
Hi RarLopz,

You need to use apex:chartLabel tag to remove the label.
<apex:chartLabel display="none" />

After using this your code will be something like this below.
<apex:page controller="PieChartController" title="Pie Chart">
    <apex:chart height="350" width="450" data="{!pieData}" >
        <apex:pieSeries dataField="data" labelField="name">
            <apex:chartLabel display="none" />
        </apex:pieSeries>
        <apex:legend position="right"/>
    </apex:chart>
</apex:page>

Hope this helps.
Shruthi GM 6Shruthi GM 6 
"Your Apex code contains field level access checks that are redundant now that you've added 'WITH SECURITY_ENFORCED'. Please check your code again."

Code is:-

@RestResource(urlMapping='/secureApexRest')
global with sharing class SecureApexRest {
    @HttpGet
    global static Contact doGet(){
        Id recordId = RestContext.request.params.get('id');
        Contact result;
        if (recordId == null){
            throw new FunctionalException('Id parameter is required');
        }
        if (Schema.SObjectType.Contact.isAccessible()
            && Schema.SObjectType.Contact.fields.Name.isAccessible()
            && Schema.SObjectType.Contact.fields.Secret_Key__c.isAccessible()){
            List<Contact> results = [SELECT id FROM Contact WHERE Id = :recordId WITH SECURITY_ENFORCED];
            if (!results.isEmpty()) {
                result = results[0];
            }
        } else{
            throw new SecurityException('You don\'t have access to all contact fields required to use this API');
        }
        return result;
    }
    public class FunctionalException extends Exception{}
    public class SecurityException extends Exception{}
}

Kindly suggest me what exactly I need to change in the code.
Thanks inadvance.
Best Answer chosen by Shruthi GM 6
Raj VakatiRaj Vakati
Refer this link 
https://success.salesforce.com/answers?id=9063A000000lSPsQAM

You dont have to provide access to any fields. If you read the challenge, you just have to edit the query to include the new WITH SECURITY_ENFORCED attribute, and remove other field level security checks. 

You need to put the query in a try/catch statement, and catch the System.Query Exception.

Use this code
 
@RestResource(urlMapping='/secureApexRest')
global with sharing class SecureApexRest {
    @HttpGet
    global static Contact doGet(){
        Id recordId = RestContext.request.params.get('id');
        Contact result;
        if (recordId == null){
            throw new FunctionalException('Id parameter is required');
        }
        List<Contact> results;
        try{
            results = [SELECT id, Name, Secret_Key__c FROM Contact WHERE Id = :recordId WITH SECURITY_ENFORCED];
        }catch(QueryException e){}
        
        if (!results.isEmpty()) {
                result = results[0];
        }
        return result;
    }
    public class FunctionalException extends Exception{}
    public class SecurityException extends Exception{}
}

 
TraceyTracey 

I'm trying to copy a new user as contact by using a trigger but I'm getting the following error

 

MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): Contact, original object: User

 

trigger Acceleration_User_Copyto_Contact on User (after insert, after update) {
    
   // Map<String,User> newLead = new Map <String, User>();
    
    system.debug('Acceleration_User_Copyto_Contact Trigger....');
 
    for ( User user : System.Trigger.new)
    {
        if  (user.Email.contains('acceleration'))
        {
            system.debug('Acceleration_User_Copyto_Contact Trigger..2.');
            Integer RecordCount = [select count() from Contact c where c.Email = : user.Email];
            
            system.debug('Acceleration_User_Copyto_Contact Trigger..2a .' + RecordCount);
            
            if (RecordCount == 0)
            {
                String AccountId = '';
                for ( Account a : [Select a.Id From Account a where Name = 'Acceleration']) 
                {
                    system.debug('Acceleration_User_Copyto_Contact Trigger..3.');
                     
                    AccountId = a.Id;
                
                    Contact con = New Contact();
                    con.AccountId = AccountId ;
                    con.Email = user.Email;
                    con.Firstname = User.Firstname;
                    con.Lastname = User.Lastname ;
                    con.User__c = User.Id;
                    insert con;
                }          
            }                   
        }
        
     }
    
    
}

 

Best Answer chosen by Admin (Salesforce Developers) 
wesnoltewesnolte

Hey

 

There you cannot perform DML on what salesforce calls setup objects(User in this case) and non-setup object in the same context. There is a workaround that can be found here although I still had some issues. Let me know if the posted solution works for you, if not mail me and I'll send you mine.

 

Cheers,

Wes 

Peter Davids 4Peter Davids 4 

 
Hi all,

We need to implement the following pattern at my org:
  • callout to external data source
  • if that callout takes too long (according to some configurable threshold), log an error (ie do some DML)
  • if that callout timed out on the remote server, try it again
Recognizing the potential for the dreaded "You have uncommitted work pending. Please commit or rollback before calling out." error, I put the error logging code in a future method, thus isolating the DML from the callouts. However, the error is still being thrown. I reduced the issue down to this pattern:
public static void foo() {
    Http http = new Http();
    HttpRequest req = new Httprequest();
    req.setEndpoint('https://test.salesforce.com'); //whatever endpoint
    req.setMethod('GET');
    http.send(req); //works fine
    bar();
    http.send(req); //throws calloutexception
}

@future public static void bar() {

}
Am I correct to assume that calling a future method counts as a DML operation? Is there any documentation I'm missing somewhere?

 
Best Answer chosen by Peter Davids 4
Peter Davids 4Peter Davids 4
David Autry 4David Autry 4 

Been banging my head against the wall for a bit on this one.  Given a global picklist that is added to two objects can a SOQL query be constructed such that the query will return a collection of objects A or B where the global picklist on each contains one matching value in the set pair?

Given MultipickList__c is a global picklist on ObjectA and ObjectB :

SELECT Id FROM ObjectA WHERE Multipicklist__c INCLUDES(ObjectB.Multipicklist__c)

Thank you.

David

Best Answer chosen by David Autry 4
David Autry 4David Autry 4

Settled on a FOR loop.  Broke ObjectA.Multipicklist__c into an array and used it to query against ObjectB.

 

                string[] multipickA = ObjectA.MultiPickList__c.split(';');
                List<ObjectB> finalList = new List<ObjectB>();
                integer i = 0;
                for (string s : multipickA)
                {
                    List<ObjectB> tempList = [SELECT Id 
                                                          FROM ObjectB
                                                          WHERE MultiPickList__c INCLUDES(:multipickA[i])]
                    finalList.addall(tempList);
                    i++;                    
                }

 

If there is a more elegant solution please let me know.

Thanks all.

Abhiram Sheshadri 9Abhiram Sheshadri 9 
Hi,

I have written the below classes as part of the trailhead challenge for Apex REST callouts.

The class -

public class AnimalLocator {
  
  public static String getAnimalNameById(Integer id) {
    
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+id);
    request.setMethod('GET');
    
    HttpResponse response = http.send(request);
    List<Object> animals; 
    String returnValue; 
    
    // parse the JSON response
    if (response.getStatusCode() == 200) {
      Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
      animals = (List<Object>) result.get('animals');
      System.debug(animals);
    }
    
    if (animals.size() > 0 && animals != NULL && id < animals.size()) {
      returnValue = (String) animals.get(id);
    }
    
    return returnValue;
  } 
    
}

Mock Response Class - 

@isTest
global class AnimalLocatorMock implements HttpCalloutMock {
     // Implement this interface method
    global HTTPResponse respond(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}');
        response.setStatusCode(200);
        return response; 
    }
}

Test Class - 

@isTest
private class AnimalLocatorTest{
    @isTest static void AnimalLocatorMock1() {
        Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
        string result = AnimalLocator.getAnimalNameById(3);
        String expectedResult = 'chicken';
        System.assertEquals(result,expectedResult );
    }
}

I have got 100% code coverage for the main class. But when I check the challenge I get 

Challenge Not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.NullPointerException: Attempt to de-reference a null object

Please tell me if any changes to the code is required. It's really frustrating as I am stuck from past 3-4 days with this unit.

Thanks & Regards,

Abhiram Sheshadri
Best Answer chosen by Abhiram Sheshadri 9
Uvais KomathUvais Komath
public class AnimalLocator{
    public static String getAnimalNameById(Integer x){
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/' + x);
        req.setMethod('GET');
        
        HttpResponse res = http.send(req);
            if (response.getStatusCode() == 200) {
        Map<String, Object> results = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
        Map<String, Object> animal = (Map<String, Object>) results.get('animal');
        return (String)animal.get('name');

}
    }
}
works fine for me
 
Sreenu Reddy 16Sreenu Reddy 16 
sfdc flocks can you give me  help on below code .

Method does not exist or incorrect signature: void put(Decimal, String) from the type Map<Id,String> at line 8 column 24

trigger changeowner on Lead (before insert) {
     Map<Id,String> zipCodeUserMap = new Map<Id,String>();
     List<Zip_Code__c> zipCodes = new List<Zip_Code__c>();
     zipCodes = [Select id,ZipCode__c,Counserlor__c  from Zip_Code__c];
      
      for (Zip_Code__c zc :zipCodes){
        
        zipCodeUserMap.put(zc.ZipCode__c,zc.Counserlor__c);   
     }
       
       
       
       for(Lead l : Trigger.new) 
       {
        if(zipCodeUserMap.containsKey(l.Zip_Code__c)) 
        {
            l.Ownerid = zipCodeUserMap.get(l.Zip_Code__c);
        }
       }
}
Best Answer chosen by Sreenu Reddy 16
Ajay K DubediAjay K Dubedi
Hi Sreenu,
Try this trigger:

trigger changeowner on Lead (before insert) {
    Map<String, Id> zipCodeUserMap = new Map<String, Id>();
    List<Zip_Code__c> zipCodes = new List<Zip_Code__c>();
    zipCodes = [Select id, ZipCode__c, Counserlor__c  from Zip_Code__c WHERE ZipCode__c != null AND Counserlor__c != null];
    if(zipCodes.size() > 0) {
        for (Zip_Code__c zc : zipCodes) {
            zipCodeUserMap.put(String.ValueOf(zc.ZipCode__c), Id.ValueOf(zc.Counserlor__c));   
        }
        for(Lead l : Trigger.new) 
        {
            if(zipCodeUserMap.containsKey(l.Zip_Code__c)) 
            {
                l.Ownerid = zipCodeUserMap.get(l.Zip_Code__c);
            }
        }
    }  
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
Michael Degn JensenMichael Degn Jensen 
Hi,

I am fairly new to working with Aura Components but have managed to build a component which shows all non-completed tasks on the user Home Page.
I have added a checkbox next to each Task and this is where I am stuck. I would like the Task Status to be updatet to 'Completed' when the checkbox i marked (true). How to accomplish this?

Any help is appreciated, thanks!

ApexController:
public class ALTaskController {
    @AuraEnabled
    public static List<Task> getTasks(){
        List<Task> taskList = [SELECT Id,Subject,Description,OwnerId,ActivityDate,WhoId,Priority,Status,Type FROM Task WHERE ActivityDate <= NEXT_N_DAYS:3 AND Status != 'Completed' ORDER BY ActivityDate ASC];
        return taskList;
    }
}
Component:
<aura:component controller="ALTaskController" implements="flexipage:availableForAllPageTypes,force:appHostable" access="global">
	<aura:attribute name="tasks" type="List" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />


        <lightning:card class="accountCard" variant="Narrow" iconName="standard:task" footer="Card Footer">
            <aura:set attribute="title">
                Mine opgaver
            </aura:set>
            <aura:set attribute="actions">
                <lightning:buttonIcon iconName="utility:down" variant="border-filled" alternativeText="Show More"/>
            </aura:set>
            <aura:set attribute="body">
                <p class="slds-p-horizontal_small">
                    <aura:iteration items="{!v.tasks}" var="task"> <!-- Use the Apex model and controller to fetch server side data -->
                    <lightning:tile label="{!task.Subject}" href="{!'/one/one.app?#/sObject/'+ task.Id + '/view'}">
                        <aura:set attribute="media">
							<lightning:input type="checkbox" name="input1" title="Fuldført"/>
                            <!--<lightning:icon iconName="standard:task"/>-->
                        </aura:set>
                        <div class="demo-only demo-only--sizing slds-grid slds-wrap">
                            <div class="slds-size_3-of-12">
                                <div class=""><p class="slds-truncate">Forfaldsdato:</p></div>
                            </div>
                            <div class="slds-size_9-of-12">
                                <div class=""><p class="slds-truncate"><lightning:formattedDateTime value="{!task.ActivityDate}" year="numeric" month="numeric" day="numeric"/></p></div>
                            </div>
                            <div class="slds-size_3-of-12">
                                <div class=""><p class="slds-truncate">Status:</p></div>
                            </div>
                            <div class="slds-size_9-of-12">
                                <div class=""><p class="slds-truncate">{!task.Status}</p></div>
                            </div>
                            <div class="slds-size_3-of-12">
                                <div class=""><p class="slds-truncate">Kommentar:</p></div>
                            </div>
                            <div class="slds-size_9-of-12">
                                <div class="" title="{!task.Description}"><p class="slds-truncate">{!task.Description}</p></div>
                            </div>
                        </div>
                    </lightning:tile>
                    </aura:iteration>
                </p>
            </aura:set>
            <aura:set attribute="footer">
            </aura:set>
        </lightning:card>
</aura:component>
Controller:
({
	doInit: function(component, event, helper) {
        // Fetch the task list from the Apex controller
        helper.getTaskLists(component);
    }
})
Helper:
({
	// Fetch the accounts from the Apex controller
    getTaskLists: function(component) {
        var action = component.get('c.getTasks');
        // Set up the callback
        var self = this;
        action.setCallback(this, function(actionResult) {
            component.set('v.tasks', actionResult.getReturnValue());
        });
        $A.enqueueAction(action);
    }
})
Best Answer chosen by Michael Degn Jensen
Khan AnasKhan Anas (Salesforce Developers) 
Hi Michael,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Apex:
public class ALTaskController {
    
    @AuraEnabled
    public static List<Task> getTasks(){
        List<Task> taskList = [SELECT Id,Subject,Description,OwnerId,ActivityDate,WhoId,Priority,Status,Type FROM Task WHERE ActivityDate <= NEXT_N_DAYS:3 AND Status != 'Completed' ORDER BY ActivityDate ASC];
        return taskList;
    }
    
    @AuraEnabled
    public static void updateDetails(List<String> lstRecordId) {
        List<Task> lstUpdate = new List<Task>();
        for(Task t : [SELECT Id, Status FROM Task WHERE Id IN : lstRecordId]){
            t.Status = 'Completed'; // Add fields which you want to update
            lstUpdate.add(t);
        }
        
        if(lstUpdate.size() > 0){
            update lstUpdate;
        }
        
    }
}

Component:
<aura:component controller="ALTaskController" implements="flexipage:availableForAllPageTypes,force:appHostable" access="global">
    <aura:attribute name="tasks" type="List" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:handler event="force:refreshView" action="{!c.doInit}" />
    
    <lightning:card class="accountCard" variant="Narrow" iconName="standard:task" footer="Card Footer">
        <aura:set attribute="title">
            Mine opgaver
        </aura:set>
        <aura:set attribute="actions">
            <lightning:buttonIcon iconName="utility:down" variant="border-filled" alternativeText="Show More"/>
        </aura:set>
        <aura:set attribute="body">
            <p class="slds-p-horizontal_small">
                <aura:iteration items="{!v.tasks}" var="task"> <!-- Use the Apex model and controller to fetch server side data -->
                    <lightning:tile label="{!task.Subject}" href="{!'/one/one.app?#/sObject/'+ task.Id + '/view'}">
                        <aura:set attribute="media">
                            <lightning:input type="checkbox" 
                                             name="input1" 
                                             title="Fuldført"
                                             value="{!task}"
                                             onchange="{!c.updateStatus}"/>
                            <!--<lightning:icon iconName="standard:task"/>-->
                        </aura:set>
                        <div class="demo-only demo-only--sizing slds-grid slds-wrap">
                            <div class="slds-size_3-of-12">
                                <div class=""><p class="slds-truncate">Forfaldsdato:</p></div>
                            </div>
                            <div class="slds-size_9-of-12">
                                <div class=""><p class="slds-truncate"><lightning:formattedDateTime value="{!task.ActivityDate}" year="numeric" month="numeric" day="numeric"/></p></div>
                            </div>
                            <div class="slds-size_3-of-12">
                                <div class=""><p class="slds-truncate">Status:</p></div>
                            </div>
                            <div class="slds-size_9-of-12">
                                <div class=""><p class="slds-truncate">{!task.Status}</p></div>
                            </div>
                            <div class="slds-size_3-of-12">
                                <div class=""><p class="slds-truncate">Kommentar:</p></div>
                            </div>
                            <div class="slds-size_9-of-12">
                                <div class="" title="{!task.Description}"><p class="slds-truncate">{!task.Description}</p></div>
                            </div>
                        </div>
                    </lightning:tile>
                </aura:iteration>
            </p>
        </aura:set>
        <aura:set attribute="footer">
        </aura:set>
    </lightning:card>
</aura:component>

Controller:
({
	doInit: function(component, event, helper) {
        // Fetch the task list from the Apex controller
        helper.getTaskLists(component);
    },
    
    updateStatus: function(component, event, helper) {
        helper.updateTaskStatus(component, event);
    }
})

Helper:
({
    // Fetch the accounts from the Apex controller
    getTaskLists: function(component) {
        var action = component.get('c.getTasks');
        // Set up the callback
        var self = this;
        action.setCallback(this, function(actionResult) {
            component.set('v.tasks', actionResult.getReturnValue());
        });
        $A.enqueueAction(action);
    },
    
    updateTaskStatus: function(component, event) {
        var rowRecord = event.getSource().get('v.value');
        console.log('rowRecord--->>> ' + JSON.stringify(rowRecord));
        var tid = rowRecord.Id;
        console.log('tid-> ' + tid);
        
        var action = component.get('c.updateDetails');
        action.setParams({
            "lstRecordId": tid
        });
        action.setCallback(this, function(response) {
            
            var state = response.getState();
            if (state === "SUCCESS") {
                console.log(state);
                $A.get('e.force:refreshView').fire();
            }
        });
        $A.enqueueAction(action);
    }
})

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Gaurav Sinha 27Gaurav Sinha 27 
Hi All Veterans
We have a requirement wherein we have to write a trigger on contact after update. There will be a field called IsDeleted in contacts, when that field will be selected the contact will automatically get associated with a private account. Now the challenge is we have to create the  private account dynamically. Before associating the contact we have to check if that pfivate account contains 10000 contacts if yes then create a new private account and associate that contact with the newly created private account else with the previous account, this process will continue.

Thanks in advance...:)
Best Answer chosen by Gaurav Sinha 27
Ravi Dutt SharmaRavi Dutt Sharma
I think this should work. I have not complied it, you may see some compilation errors. Thanks.
 
trigger ContactTrigger on Contact(before update){
	
	List<Account> accList = [SELECT Id,(SELECT Id FROM Contacts) FROM Account WHERE IsPrivate__c = true];
	// list of private accounts with less than 10k contact
	List<Account> eligibleAccounts = new List<Account>();
	// Map of account id vs count of contacts
	Map<Id, Integer> accToContactCount = new Map<Id, Integer>();
	for(Account acc: accList){
	    if(acc.Contacts.size() < 10000){
	        eligibleAccounts.add(acc);
	        accToContactCount.put(acc.Id, acc.Contacts.size());
	    }
	}
	boolean eligibleAccountExists = false;
	Account eligibleAccount;
	if(eligibleAccounts.size() > 0){
		eligibleAccountExists = true;
		eligibleAccount = eligibleAccounts[0];
	}
	for(Contact con: Trigger.new){
		// check if value of IsDeleted is changed from false to true
		if(con.IsDeleted && Trigger.oldMap.get(con.Id).IsDeleted == false) {
			if(eligibleAccountExists && accToContactCount.get(eligibleAccount.Id) < 10000){
				con.AccountId = eligibleAccount.Id;
				Integer existingContactCount = accToContactCount.get(eligibleAccount.Id);
				if(existingContactCount == null){
					existingContactCount = 0;
				}
				accToContactCount.put(eligibleAccount.Id, existingContactCount + 1);
			} else {
				Account acc = new Account(Name = 'Private Account', IsPrivate__c = true);
				insert acc;
				eligibleAccountExists = true;
				eligibleAccount = acc;
				con.AccountId = eligibleAccount.Id;
				Integer existingContactCount = accToContactCount.get(eligibleAccount.Id);
				if(existingContactCount == null){
					existingContactCount = 0;
				}
				accToContactCount.put(eligibleAccount.Id, existingContactCount + 1);
			}
		}
	}
}