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
Mr WodaMr Woda 

Help PLS

Create some apex logic for old Accounts, so we can run this logic,get all accounts without 'custom users" then create these 'custom users', link them with the correspondent account and link all opportunities from Account record to the custom user.
Shubham Jain 338Shubham Jain 338
Hi Woda,

Can you please explain the requirement clearly?

1. What do you mean by Account without custom users?
2. What do you mean by linking users to opportunities?

Thanks
Shubham Jain
Mr WodaMr Woda
Hi,  Shubham Jain 338  ''custom users'' its a custom object
 
Shubham Jain 338Shubham Jain 338
Hi Woda,

public class AccountBatch implements Database.Batchable<sObject> {
    
    public Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'SELECT Id, Custom_User__c, (SELECT Id, Custom_User__c FROM Opportunities) FROM Account WHERE Custom_User__c = null';
        return DataBase.getQueryLocator(query);
    }
    
    public void execute(Database.BatchableContext bc, List<Account> records){
        Map<Id, Custom_User__c> customUserMap = new Map<Id, Custom_User__c>();
        for (Account acc : records) {
            Custom_User__c cus = new Custom_User__c();
            cus.Name = acc.Name; // Assign Name as per requirement and populate other fields also as per requirement
            customUserMap.put(acc.Id,cus);
        }
        insert customUserMap.values();
        List<Opportunity> oppListToUpdate = new List<Opportunity>();
        for (Account acc : records) {
            for (Opportunity opp : acc.Opportunities) {
                opp.Custom_User__c = customUserMap.get(acc.Id).Id;
                oppListToUpdate.add(opp);
            }
            acc.Custom_User__c = customUserMap.get(acc.Id).Id;
        }
        update records;
        if (oppListToUpdate.size() > 0) update oppListToUpdate;
    }
    
    public void finish(Database.BatchableContext bc){
        // execute any post-processing operations
    }
}

Please mark this as the best answer if it helps.

Thanks 
Shubham Jain