Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
1.1 kB
3
Indexable
Never
public class Helper {
    public static void CheckRecord(list<account> accs) {
        ID IdProp = accs.get(0).ownerid;
        System.debug('ID Vecchio proprietario = ' + IdProp);
        list<AggregateResult> appoggio = [select ownerid, count(id) from account where ownerid =: IdProp group by ownerid];
        Integer numAccount = (Integer) appoggio.get(0).get('expr0');
        System.debug('L account che sta inserendo ha ' + numAccount + ' record');
        if (numAccount > 5){
            list<AggregateResult> app = [select ownerid, count(id) from account group by ownerid having count(id) > 0 order by count(id) ASC LIMIT 1];
            ID NuovoProp = (ID) app.get(0).get('ownerid');
            System.debug('ID nuovo proprietario = ' + NuovoProp);
            for (account acc:accs) {
                if (IdProp == Nuovoprop) acc.addError('Non ci sono altri record di altri account');
                else acc.ownerid = nuovoProp;
            }
        }  
    }
}


trigger TriggerInsert on Account (before insert) {
	Helper.checkRecord(trigger.new);
}