0

I have this batchclass where I update a checkbox on account based on related assets. How do I set the checkbox to true If 1 of the assets is true and to false if all assets are false.

I would have to loop trough all the related assets but then I would have a loop in an if statement so how do I bulkify this.

Here is what I have so far where the account gets updated with the last value of the Asset in the query:

global Database.QueryLocator start(Database.BatchableContext bc) {
     return Database.getQueryLocator (
         [SELECT account.Name, accountId, Actief__c , account.As__c
          FROM Asset                                                                                    
          WHERE (Actief__c = true AND account.As__c = false)
          OR (Actief__c = false AND account.As__c = true) 
         ]);
 }

 global void execute(Database.BatchableContext bc, List<Asset> scope){        
     Map<Id, Account> accounts = new Map<Id, Account>();
     Account tempRecord;
     for (Asset record: Scope) {
         if(record.AccountId == null) { continue; }

         if((tempRecord = accounts.get(record.AccountId)) == null) {  
             tempRecord = new Account(Id=record.AccountId);
         }
         if(record.Actief__c     !=null && record.account.As__c !=null) {
             tempRecord.As__c = record.Actief__c    ;
             accounts.put(record.AccountId, tempRecord);
         }
     }
     update accounts.values();
 }

1 Answer 1

2

If I need to do this I will make query on Account and using inner query I will query Asset. Now based on checkbox condition I will update the checkbox on accounts.

global Database.QueryLocator start(Database.BatchableContext bc) {
     return Database.getQueryLocator (
         [SELECT As__c,( Select id, Actief__c from Assets WHERE Actief__c = true LIMIT 1)
          FROM Account ];                                                                                  
          );
 }

 global void execute(Database.BatchableContext bc, List<Account> scope){        
     List< Account> accounts = new List< Account>();
     for (Account record: Scope) {
        if(records.Assets.size() > 0 && !record.As__c) {
            record.As__c = true;
            accounts.add(record);
        }else if(records.Assets.size() == 0 && record.As__c) {
            record.As__c = false;
            accounts.add(record);
        }

     }
     update accounts ;
 }

So here I don't need all asset records and I will onl update those account where we need to change checkbox value.

2
  • 2
    I'd want to move that subquery into the execute() method to run on each batch of Accounts.
    – David Reed
    May 3, 2018 at 13:24
  • @DavidReed That depends on number of records. Although no harm of doing it. Thanks. May 3, 2018 at 13:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .