• Ramkumar Murugesan
  • NEWBIE
  • 0 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 11
    Replies
Hi Team,

I had issue with processing the results of agreegate query. I want to display the values and counts of whichdoesnt existing in the picklist field value. 

When the agreegate result should not contain the values of availablepicklist values. 

This is not working fine as per query. Can you please help on this. 
 
void checkPickListValues(){
            if(selectedField != null && selectedObject != null){
                UsedPicklistValues = new List<String>();
                String qryStr = 'Select ' + selectedField + ' pData, count(Id) tCount From ' + selectedObject + ' GROUP BY ' + selectedField;
                AggregateResult[] groupedResults =  Database.Query(qryStr);
                Summaries = new List<Summary>();
                for (AggregateResult ar : groupedResults){
                    system.debug(' ar ==>'+ar);
                    UsedPicklistValues.add((String)ar.get('pData'));
                    for (String availablepickval: PicklistValues){
                        
                        
                        if(ar.get('pData') != availablepickval && ar.get('pData')!= null ){                        
                        Summaries.add(new Summary((String)ar.get('pData'),(Integer)ar.get('tCount')));
                         
                        }  
                    }
                }

 
Hi, 

I had issue with processing the results of agreegate query. When the agreegate result should not contain the values of availablepicklist values. 

This is not working fine as per query. Can you please help on this. 
 
void checkPickListValues(){
            if(selectedField != null && selectedObject != null){
                UsedPicklistValues = new List<String>();
                String qryStr = 'Select ' + selectedField + ' pData, count(Id) tCount From ' + selectedObject + ' GROUP BY ' + selectedField;
                AggregateResult[] groupedResults =  Database.Query(qryStr);
                Summaries = new List<Summary>();
                for (AggregateResult ar : groupedResults){
                    system.debug(' ar ==>'+ar);
                    UsedPicklistValues.add((String)ar.get('pData'));
                    for (String availablepickval: PicklistValues){
                        
                        
                        if(ar.get('pData') != availablepickval && ar.get('pData')!= null ){                        
                        Summaries.add(new Summary((String)ar.get('pData'),(Integer)ar.get('tCount')));
                         
                        }  
                    }
                }

 
Hi,

I would like to write a trigger when a accoun after insert and updated, based on the account id and territory assigned to that account. It has to create a records in the related list (TSF Object). It has to check whether the TSF record is already existing or not, if it's not updated, then it has to create it.

TSF.Name = Territory Name
TSF Terriotry = Territory Name
TSF.account= account.id

I have written the code  as below mentioned. can you please modify this and it's not creating the records.
 
trigger INS_UPD_Account_TSF on Account (after insert,after update) {
   
    Set<Id> accountIds = new Set<Id>();         
    if(trigger.isinsert || trigger.isupdate){ 
    for(Account acct : Trigger.new){
      accountIds.add(acct.Id);
    }
}

    // Query Account share records where the Territories changed manually

    list<AccountShare>accShareobj=[SELECT AccountId,UserOrGroupId FROM AccountShare WHERE AccountId=:accountIds and RowCause ='TerritoryManual'];  

    // query the Nestle holidays Record Type              
          RecordType rt=[select Id from RecordType where SObjectType = 'Account' and DeveloperName='Professional_vod' limit 1];
          
          
    // Query Relatedid Using Usergroupid
    
    set<string>accids=new set<string>();
    set<string>usergroupids=new set<string>();
    for(AccountShare accs :accShareobj){
        if(accs.UserOrGroupId!=null && accs.AccountId!=null){
            accids.add(accs.AccountId);
            system.debug('accids--->'+accids);
            usergroupids.add(accs.UserOrGroupId);
            system.debug('accids--->'+accids);
        }
    }
 
    List<Group> glist=[SELECT RelatedId FROM Group Where Id IN:usergroupids];
    set<string>Grelatedid=new set<string>();
    for(Group grobj:glist){
        if(grobj.RelatedId !=null){
            Grelatedid.add(grobj.RelatedId);
        }
    
    }

    List<Territory > tobjlist=[SELECT Name FROM Territory WHERE Id IN:Grelatedid]; 
    set<String> tname= new set<String>();
    for (Territory t:tobjlist)
    {
        tname.add(t.Name);
    }

    set<id> accid= new set<id>();
    List<Account> acclist=[SELECT id FROM Account WHERE Id IN:accids AND RecordTypeId= :rt.Id]; 
    for (Account a:acclist)
    {
        accid.add(a.id);
    }
       
    List<TSF_vod__c> tsfRecords = new List<TSF_vod__c>();
    
    List<TSF_vod__c> existingTSFRecords = [SELECT Account_vod__c,External_Id_vod__c,Territory_vod__c FROM TSF_vod__c Where Territory_vod__c IN: tname AND Account_vod__c IN :accid]; 
    
        for(Account aId : acclist){
     
           for(Territory  ter:tobjlist){
           
           for (TSF_vod__c tsf: existingTSFRecords){
       
           if(tsf.Account_vod__c!=aId.id && tsf.Territory_vod__c!=ter.Name){
               
               TSF_vod__c tsfRecord = new TSF_vod__c();
                tsfRecord.Name = ter.name;
                tsfRecord.Territory_vod__c = ter.Name;
                tsfRecord.Account_vod__c=aId.id;
                tsfRecords.add(tsfRecord);}
           }
        }

    }
    insert tsfRecords;
}

 
Hi,

I would like to write a trigger when a accoun after insert and updated, based on the account id and territory assigned to that account. It has to create a records in the related list (TSF Object). It has to check whether the TSF record is already existing or not, if it's not updated, then it has to create it.

TSF.Name = Territory Name
TSF Terriotry = Territory Name
TSF.account= account.id

I have written the code  as below mentioned. can you please modify this and it's not creating the records.
 
trigger INS_UPD_Account_TSF on Account (after insert,after update) {
   
    Set<Id> accountIds = new Set<Id>();         
    if(trigger.isinsert || trigger.isupdate){ 
    for(Account acct : Trigger.new){
      accountIds.add(acct.Id);
    }
}

    // Query Account share records where the Territories changed manually

    list<AccountShare>accShareobj=[SELECT AccountId,UserOrGroupId FROM AccountShare WHERE AccountId=:accountIds and RowCause ='TerritoryManual'];  

    // query the Nestle holidays Record Type              
          RecordType rt=[select Id from RecordType where SObjectType = 'Account' and DeveloperName='Professional_vod' limit 1];
          
          
    // Query Relatedid Using Usergroupid
    
    set<string>accids=new set<string>();
    set<string>usergroupids=new set<string>();
    for(AccountShare accs :accShareobj){
        if(accs.UserOrGroupId!=null && accs.AccountId!=null){
            accids.add(accs.AccountId);
            system.debug('accids--->'+accids);
            usergroupids.add(accs.UserOrGroupId);
            system.debug('accids--->'+accids);
        }
    }
 
    List<Group> glist=[SELECT RelatedId FROM Group Where Id IN:usergroupids];
    set<string>Grelatedid=new set<string>();
    for(Group grobj:glist){
        if(grobj.RelatedId !=null){
            Grelatedid.add(grobj.RelatedId);
        }
    
    }

    List<Territory > tobjlist=[SELECT Name FROM Territory WHERE Id IN:Grelatedid]; 
    set<String> tname= new set<String>();
    for (Territory t:tobjlist)
    {
        tname.add(t.Name);
    }

    set<id> accid= new set<id>();
    List<Account> acclist=[SELECT id FROM Account WHERE Id IN:accids AND RecordTypeId= :rt.Id]; 
    for (Account a:acclist)
    {
        accid.add(a.id);
    }
       
    List<TSF_vod__c> tsfRecords = new List<TSF_vod__c>();
    
    List<TSF_vod__c> existingTSFRecords = [SELECT Account_vod__c,External_Id_vod__c,Territory_vod__c FROM TSF_vod__c Where Territory_vod__c IN: tname AND Account_vod__c IN :accid]; 
    
        for(Account aId : acclist){
     
           for(Territory  ter:tobjlist){
           
           for (TSF_vod__c tsf: existingTSFRecords){
       
           if(tsf.Account_vod__c!=aId.id && tsf.Territory_vod__c!=ter.Name){
               
               TSF_vod__c tsfRecord = new TSF_vod__c();
                tsfRecord.Name = ter.name;
                tsfRecord.Territory_vod__c = ter.Name;
                tsfRecord.Account_vod__c=aId.id;
                tsfRecords.add(tsfRecord);}
           }
        }

    }
    insert tsfRecords;
}

 
Hello all,

I have a requirement, where i need to create a record TSF in Account Related list whenever the territory is assigned to the account. Based on the territory name assigned to the account. I'm currently using this code. can you please optimize it.

Ex: Acccoun1 is having T1, T2. So i need the TSF records in the related list with the name of T1 and T2.
 
trigger INS_UPD_Account_TSF on Account (after insert,after update) {
   
    Set<Id> accountIds = new Set<Id>();         
    if(trigger.isinsert || trigger.isupdate){ 
    for(Account acct : Trigger.new){
      accountIds.add(acct.Id);
    }
}

list<AccountShare>accShareobj=[SELECT AccountId,UserOrGroupId FROM AccountShare WHERE AccountId=:accountIds and RowCause ='TerritoryManual'];  
    
    set<string>accids=new set<string>();
    set<string>usergroupids=new set<string>();
    for(AccountShare accs :accShareobj){
        if(accs.UserOrGroupId!=null && accs.AccountId!=null){
            accids.add(accs.AccountId);
            system.debug('accids--->'+accids);
            usergroupids.add(accs.UserOrGroupId);
            system.debug('accids--->'+accids);
        }
    }
    
    List<Group> glist=[SELECT RelatedId FROM Group Where Id IN:usergroupids];
    set<string>Grelatedid=new set<string>();
    for(Group grobj:glist){
        if(grobj.RelatedId !=null){
            Grelatedid.add(grobj.RelatedId);
        }
    
    }

    List<Territory > tobjlist=[SELECT Name FROM Territory WHERE Id IN:Grelatedid]; 
    system.debug('tobjlist--->'+tobjlist);      
    
    List<Account> acclist=[SELECT id FROM Account WHERE Id IN:accids]; 
    system.debug('acclist--->'+acclist); 
    
    List<TSF_vod__c> tsfRecords = new List<TSF_vod__c>();
  
    for(Account aId : acclist){
     
      for(Territory  ter:tobjlist){
      
        List<TSF_vod__c> existingTSFRecords = [SELECT Account_vod__c,External_Id_vod__c,Territory_vod__c FROM TSF_vod__c Where Territory_vod__c =:ter.Name and Account_vod__c =:aId.id Limit 1];
       
       if(existingTSFRecords.size()==0)
            {
           TSF_vod__c tsfRecord = new TSF_vod__c(Account_vod__c=aId.id);

            tsfRecord.Name = ter.name;
            tsfRecord.Territory_vod__c = ter.Name;
            System.debug('NEW TSF: ' + tsfRecord.Name);
            tsfRecords.add(tsfRecord);
           }
        }

    }
    insert tsfRecords;
}



 
Hello Friends,

The below apex class is not updating the records properly. Can you please the same
 
global class UserLicense implements Database.Batchable<Sobject>{
    global String Query;

 global Database.QueryLocator start(Database.BatchableContext BC)
    {   
    Query='SELECT Id,IsActive,Market_NES__c,Profile.UserLicense.Name, Name FROM User WHERE IsActive = true';//u can add fields and put where conditions based on requirement
    return Database.getQueryLocator(Query);
    }
 
    global void execute(Database.BatchableContext BC, List<Sobject> scope)
    {
    List <Market_Info_NES__c> ml = new list<Market_Info_NES__c> ();
    ml=Database.Query('SELECT Id,Market_NES__c,Number_of_Admin_Licences_NES__c,Number_of_platform_Licences_NES__c FROM Market_Info_NES__c');
    for(User s : (list<User>)scope)
    {
        Market_Info_NES__c a = new Market_Info_NES__c();
        Integer countAdminLicense =0; 
        Integer countPlatformLicense =0;
        if (a.Market_NES__c==s.Market_NES__c)
        {
            if (s.Profile.UserLicense.Name !='Salesforce Platform') {
                a.Number_of_Admin_Licences_NES__c = countAdminLicense++ ;
            }
            else 
            {   a.Number_of_platform_Licences_NES__c = countPlatformLicense++ ;
            }
        }        
        
        ml.add(a);
    }
    update ml;
    }
 
    global void finish(Database.BatchableContext BC)
    {
             
    }

    
}

 
I would like to collect the license informations from each market by salesforce and salesforce platform license from user object and store those informations based on the market value in a custom object called market info as mentioned in the below. There is no relation between two obejcts only the market picklist list is name in both the object

SELECT Id,IsActive,Market__c,Profile.UserLicense.Name, Name FROM User WHERE IsActive = true

SELECT Market__c,Number_of_Admin_Licences_NES__c,Number_of_platform_Licences_NES__c FROM Market_Info__c

For example: if the market is German , record is available in in the name of german. So  i will collect all the license information either it's admin or license.

can you please help me to write a schedule job and apex class for the same.

Hello Friends,

I would like to collect the license informations from each market by salesforce and salesforce platform license and store those informations based on the market value in a custom object called market info as mentioned in the below

SELECT Id,IsActive,Market__c,Profile.UserLicense.Name, Name FROM User WHERE IsActive = true

SELECT Market__c,Number_of_Admin_Licences_NES__c,Number_of_platform_Licences_NES__c FROM Market_Info__c

For example: if the market is German , record is available in in the name of german. So  i will collect all the license information either it's admin or license.

can you please help me to write a schedule job and apex class for the same.


Visualforce/Apex Error: Attempt to de-reference a null object

When a user trying to attempt to open the visual force tab, he is getting the as ' Visualforce/Apex Error: Attempt to de-reference a null object '
I dont know where is getting null point expection the below visiual force pagecontroller. Please try to helpme to resolve this issue.

public with sharing class EntitySelectionController {

   public List<SelectOption> availableOptions {
        get{
            List<SelectOption> options = new List<SelectOption>();
            for(Territory territory : availableTerritories.values()){
                options.add(new SelectOption(territory.Id, territory.Name));
            }
            options.sort();
            return options;
        }
    }

    public List<SelectOption> selectedOptions { get{
        List<SelectOption> options = new List<SelectOption>();
            for(Territory territory : selectedTerritories.values()){
                options.add(new SelectOption(territory.Id, territory.Name));
            }
            options.sort();
            return options;
        }
    }

    public Map<Id, Territory> territoriesMap {get;set;}

    public Map<Id, Territory> availableTerritories {get;set;}

    public Map<Id, Territory> selectedTerritories {get;set;}

    public Set<String> existingTerritories {get;set;}

    public Set<String> totalTerritoriesToRemove {get;set;}

    public List<String> territoriesToAdd {get;set;}
    public List<String> territoriesToRemove {get;set;}

    public Integer entityCount {get;set;}

    public Territories_Synced__c territoriesSynced {get;set;}

    public Boolean selectionHasChanged {get;set;}

    public Boolean underSyncLimit {
        get{
            _Settings__c settings = _Settings__c.getInstance();
            if(settings.Entity_Sync_Limit__c != null){
                return entityCount <= Integer.valueOf(settings.Entity_Sync_Limit__c);
            } else{
                return true;
            }
        }
    }

    public EntitySelectionController() {
        territoriesMap = new Map<Id, Territory>([select Id, ParentTerritoryID, Name from Territory]);
        selectedTerritories = new Map<Id, Territory>();
        availableTerritories = new Map<Id, Territory>();
        //existingTerritories = new Set<String>();
        territoriesToAdd = new List<String>();
        territoriesToRemove= new List<String>();
        //totalTerritoriesToRemove = new Set<String>();
        entityCount = 0;
        selectionHasChanged = false;
        loadWrappedTerritories();
    }

    public void loadWrappedTerritories(){
        List<UserTerritory> userTerritories = [select TerritoryId From UserTerritory where isActive=true and userId =:UserInfo.getUserId()];

        List<Territory> territories = new List<Territory>();

        for(UserTerritory userTerritory : userTerritories){
            territories.addAll(getTerritoryHierarchy(userTerritory.TerritoryId));
        }
      
        for(Territory territory : territories){
            availableTerritories.put(territory.Id, territory);
        }

        territoriesSynced = Territories_Synced__c.getValues(UserInfo.getUserId());
        if(territoriesSynced == null){
            territoriesSynced = new Territories_Synced__c();
            territoriesSynced.Name = UserInfo.getUserId();
            territoriesSynced.Territory_Names__c = '';
        }
        for(Territory territory : availableTerritories.values()){
            if(territoriesSynced.Territory_Names__c.contains(territory.Name)){
                availableTerritories.remove(territory.Id);
                selectedTerritories.put(territory.Id, territory);
                //existingTerritories.add(territory);
            }
        }
        calculateEntitiesCount(selectedTerritories);
    }

    public List<Territory> getTerritoryHierarchy(Id topTerrId){
        List<Territory> territories = new List<Territory>();

        Territory currentTerr = territoriesMap.get(topTerrId);

        territories.add(currentTerr);

        List<Territory> childTerrs = new List<Territory>();

        for(Territory childTerr : territoriesMap.values()){
            if(childTerr.ParentTerritoryId == currentTerr.Id){
                childTerrs.add(childTerr);
            }
        }

        if(!childTerrs.isEmpty()){
            for(Territory childTerr : childTerrs){
                territories.addAll(getTerritoryHierarchy(childTerr.Id));
            }
        } else{
            return territories;
        }

        return territories;
    }

    public void selectTerritories(){
        if(!territoriesToAdd.isEmpty()){
            for(String territory : territoriesToAdd){
                selectedTerritories.put(territory, availableTerritories.remove(territory));
            }
            calculateEntitiesCount(selectedTerritories);
            territoriesToAdd = new List<String>();
            selectionHasChanged = true;
        }
    }

    public void selectAllTerritories(){
        selectedTerritories.putAll(availableTerritories);
        calculateEntitiesCount(selectedTerritories);
        availableTerritories.clear();
        selectionHasChanged = true;
    }

    public void deselectAllTerritories(){
        availableTerritories.putAll(selectedTerritories);
        entityCount = 0;
        selectedTerritories.clear();
        selectionHasChanged = true;
    }

    public void deselectTerritories(){
        if(!territoriesToRemove.isEmpty()){
            for(String territory : territoriesToRemove){
                availableTerritories.put(territory, selectedTerritories.remove(territory));
            }
            if(!selectedTerritories.isEmpty()){
                calculateEntitiesCount(selectedTerritories);
            } else{
                entityCount = 0;          
            }
            territoriesToRemove = new List<String>();
            selectionHasChanged = true;
        }
    }

    public void calculateEntitiesCount(Map<Id, Territory> territories){
        Map<Id, Group> territoryGroups = new Map<Id, Group>([select Id from Group where RelatedId in :territories.keySet() AND Type='Territory']);
      
        Integer count = [select count() from AccountShare where UserOrGroupId in :territoryGroups.keySet()];
      
        entityCount = count;
    }

    public void updateFilters(){
        /*List<String> tsfsToAdd = new List<String>();
        for(String territory : selectedTerritories){
            if(!existingTerritories.contains(territory)){
                tsfsToAdd.add(territory);
            }
        }*/
        List<String> territoryNames = new List<String>();
        for(Territory territory : selectedTerritories.values()){
            territoryNames.add(territory.Name);
        }

        territoriesSynced.Territory_Names__c = String.join(territoryNames, ',');
        upsert territoriesSynced;

        //First, remove all Entity Sync records for user
        List<Entity_Sync___c> existingSyncs = [select Id from Entity_Sync___c where User___c = :UserInfo.getUserId()];

        delete existingSyncs;

        List<Group> territoryGroups = [select Id from Group where RelatedId in :selectedTerritories.keySet() AND Type='Territory'];
        List<Id> accountIds = new List<Id>();
        if(territoryGroups != null){
            List<Id> territoryGroupIds = new List<Id>();
            for(Group territoryGroup : territorygroups){
                territoryGroupIds.add(territoryGroup.Id);
            }
            List<AccountShare> accountShares = [select AccountId from AccountShare where UserOrGroupId in :territoryGroupIds];
            for(AccountShare accountShare : accountShares){
                accountIds.add(accountShare.AccountId);
            }
        }

        List<Entity_Sync___c> newEntitySyncs = new List<Entity_Sync___c>();
        for(Id accountId : accountIds){
            Entity_Sync___c newEntitySync = new Entity_Sync___c();
            newEntitySync.User___c = UserInfo.getUserId();
            newEntitySync.Entity___c = accountId;
            newEntitySyncs.add(newEntitySync);
        }

        insert newEntitySyncs;
        /*

        List<TSF_vod__c> tsfRecordsToAdd = [select Id, Account_vod__c from TSF_vod__c where Territory_vod__c in :tsfsToAdd];

        for(TSF_vod__c tsf : tsfRecordsToAdd){
            tsf.Sync_Entity___c = true;
        }

        update tsfRecordsToAdd;

        List<TSF_vod__c> tsfRecordsToRemove = [select Id, Territory_vod__c, Sync_Entity___c from TSF_vod__c where Territory_vod__c in :totalTerritoriesToRemove];

        for(TSF_vod__c tsf : tsfRecordsToRemove){
            tsf.Sync_Entity___c = false;
        }

        update tsfRecordsToRemove;
      
        List<Territories_Synced__c> territoriesToRemove = [select Id from Territories_Synced__c where Name in :totalTerritoriesToRemove];

        delete territoriesToRemove;*/
    }
}
The below trigger will create a TSF records in the related list when the account is created online based on territory. But when we creating it's creating through dataload it's not wroking acually. Also if we are changing/ adding the Territory based manually. it's not working properly. That means, it's not creating the TSF record Record in the related list.

public with sharing class AccountCreateTS implements Triggers.HandlerInterface {
  public void handle() {
    Set<Id> accountIds = new Set<Id>();
    for(Account acct : (List<Account>) Trigger.new){
      accountIds.add(acct.Id);
    }

    List<UserTerritory> userTerritories = [select TerritoryId, Id  From UserTerritory where isActive=true and userId =:UserInfo.getUserId()];
    Set<Id> territoryIds = new Set<Id>();
    for(UserTerritory territory : userTerritories){
      territoryIds.add(territory.TerritoryId);
    }
     
    List<Territory> territories = [select Id, Name from Territory where Id in :territoryIds];

    AccountCreateTSFNES.createTSFsForTerritories(territories, accountIds);
  }

  public static void createTSFsForTerritories(List<Territory> territories, Set<Id> accountIds){
    List<TSF__c> tsfRecords = new List<TSF__c>();
    for(Id accountId : accountIds){
      for(Territory territory : territories){
        TSF__c tsfRecord = new TSF__c(Account__c = accountId);

        tsfRecord.Name = territory.Name;
        tsfRecord.Territory__c = territory.Name;

        System.debug('NEW TSF: ' + tsfRecord);
        tsfRecords.add(tsfRecord);
      }

    }

    insert tsfRecords;
  }
}


Hi, 

I had issue with processing the results of agreegate query. When the agreegate result should not contain the values of availablepicklist values. 

This is not working fine as per query. Can you please help on this. 
 
void checkPickListValues(){
            if(selectedField != null && selectedObject != null){
                UsedPicklistValues = new List<String>();
                String qryStr = 'Select ' + selectedField + ' pData, count(Id) tCount From ' + selectedObject + ' GROUP BY ' + selectedField;
                AggregateResult[] groupedResults =  Database.Query(qryStr);
                Summaries = new List<Summary>();
                for (AggregateResult ar : groupedResults){
                    system.debug(' ar ==>'+ar);
                    UsedPicklistValues.add((String)ar.get('pData'));
                    for (String availablepickval: PicklistValues){
                        
                        
                        if(ar.get('pData') != availablepickval && ar.get('pData')!= null ){                        
                        Summaries.add(new Summary((String)ar.get('pData'),(Integer)ar.get('tCount')));
                         
                        }  
                    }
                }

 
Hello all,

I have a requirement, where i need to create a record TSF in Account Related list whenever the territory is assigned to the account. Based on the territory name assigned to the account. I'm currently using this code. can you please optimize it.

Ex: Acccoun1 is having T1, T2. So i need the TSF records in the related list with the name of T1 and T2.
 
trigger INS_UPD_Account_TSF on Account (after insert,after update) {
   
    Set<Id> accountIds = new Set<Id>();         
    if(trigger.isinsert || trigger.isupdate){ 
    for(Account acct : Trigger.new){
      accountIds.add(acct.Id);
    }
}

list<AccountShare>accShareobj=[SELECT AccountId,UserOrGroupId FROM AccountShare WHERE AccountId=:accountIds and RowCause ='TerritoryManual'];  
    
    set<string>accids=new set<string>();
    set<string>usergroupids=new set<string>();
    for(AccountShare accs :accShareobj){
        if(accs.UserOrGroupId!=null && accs.AccountId!=null){
            accids.add(accs.AccountId);
            system.debug('accids--->'+accids);
            usergroupids.add(accs.UserOrGroupId);
            system.debug('accids--->'+accids);
        }
    }
    
    List<Group> glist=[SELECT RelatedId FROM Group Where Id IN:usergroupids];
    set<string>Grelatedid=new set<string>();
    for(Group grobj:glist){
        if(grobj.RelatedId !=null){
            Grelatedid.add(grobj.RelatedId);
        }
    
    }

    List<Territory > tobjlist=[SELECT Name FROM Territory WHERE Id IN:Grelatedid]; 
    system.debug('tobjlist--->'+tobjlist);      
    
    List<Account> acclist=[SELECT id FROM Account WHERE Id IN:accids]; 
    system.debug('acclist--->'+acclist); 
    
    List<TSF_vod__c> tsfRecords = new List<TSF_vod__c>();
  
    for(Account aId : acclist){
     
      for(Territory  ter:tobjlist){
      
        List<TSF_vod__c> existingTSFRecords = [SELECT Account_vod__c,External_Id_vod__c,Territory_vod__c FROM TSF_vod__c Where Territory_vod__c =:ter.Name and Account_vod__c =:aId.id Limit 1];
       
       if(existingTSFRecords.size()==0)
            {
           TSF_vod__c tsfRecord = new TSF_vod__c(Account_vod__c=aId.id);

            tsfRecord.Name = ter.name;
            tsfRecord.Territory_vod__c = ter.Name;
            System.debug('NEW TSF: ' + tsfRecord.Name);
            tsfRecords.add(tsfRecord);
           }
        }

    }
    insert tsfRecords;
}



 
I have 2 objects A and B. B has a lookup to object A. I have a related list of B on layout of A. I want to remove records from the related list based on some criteria. For example, there is a date field on object B and when the date in that field is in the past, I want to remove the record from the related list. Kindly help me achieve this.
Hello Friends,

The below apex class is not updating the records properly. Can you please the same
 
global class UserLicense implements Database.Batchable<Sobject>{
    global String Query;

 global Database.QueryLocator start(Database.BatchableContext BC)
    {   
    Query='SELECT Id,IsActive,Market_NES__c,Profile.UserLicense.Name, Name FROM User WHERE IsActive = true';//u can add fields and put where conditions based on requirement
    return Database.getQueryLocator(Query);
    }
 
    global void execute(Database.BatchableContext BC, List<Sobject> scope)
    {
    List <Market_Info_NES__c> ml = new list<Market_Info_NES__c> ();
    ml=Database.Query('SELECT Id,Market_NES__c,Number_of_Admin_Licences_NES__c,Number_of_platform_Licences_NES__c FROM Market_Info_NES__c');
    for(User s : (list<User>)scope)
    {
        Market_Info_NES__c a = new Market_Info_NES__c();
        Integer countAdminLicense =0; 
        Integer countPlatformLicense =0;
        if (a.Market_NES__c==s.Market_NES__c)
        {
            if (s.Profile.UserLicense.Name !='Salesforce Platform') {
                a.Number_of_Admin_Licences_NES__c = countAdminLicense++ ;
            }
            else 
            {   a.Number_of_platform_Licences_NES__c = countPlatformLicense++ ;
            }
        }        
        
        ml.add(a);
    }
    update ml;
    }
 
    global void finish(Database.BatchableContext BC)
    {
             
    }

    
}

 

Hello Friends,

I would like to collect the license informations from each market by salesforce and salesforce platform license and store those informations based on the market value in a custom object called market info as mentioned in the below

SELECT Id,IsActive,Market__c,Profile.UserLicense.Name, Name FROM User WHERE IsActive = true

SELECT Market__c,Number_of_Admin_Licences_NES__c,Number_of_platform_Licences_NES__c FROM Market_Info__c

For example: if the market is German , record is available in in the name of german. So  i will collect all the license information either it's admin or license.

can you please help me to write a schedule job and apex class for the same.


Visualforce/Apex Error: Attempt to de-reference a null object

When a user trying to attempt to open the visual force tab, he is getting the as ' Visualforce/Apex Error: Attempt to de-reference a null object '
I dont know where is getting null point expection the below visiual force pagecontroller. Please try to helpme to resolve this issue.

public with sharing class EntitySelectionController {

   public List<SelectOption> availableOptions {
        get{
            List<SelectOption> options = new List<SelectOption>();
            for(Territory territory : availableTerritories.values()){
                options.add(new SelectOption(territory.Id, territory.Name));
            }
            options.sort();
            return options;
        }
    }

    public List<SelectOption> selectedOptions { get{
        List<SelectOption> options = new List<SelectOption>();
            for(Territory territory : selectedTerritories.values()){
                options.add(new SelectOption(territory.Id, territory.Name));
            }
            options.sort();
            return options;
        }
    }

    public Map<Id, Territory> territoriesMap {get;set;}

    public Map<Id, Territory> availableTerritories {get;set;}

    public Map<Id, Territory> selectedTerritories {get;set;}

    public Set<String> existingTerritories {get;set;}

    public Set<String> totalTerritoriesToRemove {get;set;}

    public List<String> territoriesToAdd {get;set;}
    public List<String> territoriesToRemove {get;set;}

    public Integer entityCount {get;set;}

    public Territories_Synced__c territoriesSynced {get;set;}

    public Boolean selectionHasChanged {get;set;}

    public Boolean underSyncLimit {
        get{
            _Settings__c settings = _Settings__c.getInstance();
            if(settings.Entity_Sync_Limit__c != null){
                return entityCount <= Integer.valueOf(settings.Entity_Sync_Limit__c);
            } else{
                return true;
            }
        }
    }

    public EntitySelectionController() {
        territoriesMap = new Map<Id, Territory>([select Id, ParentTerritoryID, Name from Territory]);
        selectedTerritories = new Map<Id, Territory>();
        availableTerritories = new Map<Id, Territory>();
        //existingTerritories = new Set<String>();
        territoriesToAdd = new List<String>();
        territoriesToRemove= new List<String>();
        //totalTerritoriesToRemove = new Set<String>();
        entityCount = 0;
        selectionHasChanged = false;
        loadWrappedTerritories();
    }

    public void loadWrappedTerritories(){
        List<UserTerritory> userTerritories = [select TerritoryId From UserTerritory where isActive=true and userId =:UserInfo.getUserId()];

        List<Territory> territories = new List<Territory>();

        for(UserTerritory userTerritory : userTerritories){
            territories.addAll(getTerritoryHierarchy(userTerritory.TerritoryId));
        }
      
        for(Territory territory : territories){
            availableTerritories.put(territory.Id, territory);
        }

        territoriesSynced = Territories_Synced__c.getValues(UserInfo.getUserId());
        if(territoriesSynced == null){
            territoriesSynced = new Territories_Synced__c();
            territoriesSynced.Name = UserInfo.getUserId();
            territoriesSynced.Territory_Names__c = '';
        }
        for(Territory territory : availableTerritories.values()){
            if(territoriesSynced.Territory_Names__c.contains(territory.Name)){
                availableTerritories.remove(territory.Id);
                selectedTerritories.put(territory.Id, territory);
                //existingTerritories.add(territory);
            }
        }
        calculateEntitiesCount(selectedTerritories);
    }

    public List<Territory> getTerritoryHierarchy(Id topTerrId){
        List<Territory> territories = new List<Territory>();

        Territory currentTerr = territoriesMap.get(topTerrId);

        territories.add(currentTerr);

        List<Territory> childTerrs = new List<Territory>();

        for(Territory childTerr : territoriesMap.values()){
            if(childTerr.ParentTerritoryId == currentTerr.Id){
                childTerrs.add(childTerr);
            }
        }

        if(!childTerrs.isEmpty()){
            for(Territory childTerr : childTerrs){
                territories.addAll(getTerritoryHierarchy(childTerr.Id));
            }
        } else{
            return territories;
        }

        return territories;
    }

    public void selectTerritories(){
        if(!territoriesToAdd.isEmpty()){
            for(String territory : territoriesToAdd){
                selectedTerritories.put(territory, availableTerritories.remove(territory));
            }
            calculateEntitiesCount(selectedTerritories);
            territoriesToAdd = new List<String>();
            selectionHasChanged = true;
        }
    }

    public void selectAllTerritories(){
        selectedTerritories.putAll(availableTerritories);
        calculateEntitiesCount(selectedTerritories);
        availableTerritories.clear();
        selectionHasChanged = true;
    }

    public void deselectAllTerritories(){
        availableTerritories.putAll(selectedTerritories);
        entityCount = 0;
        selectedTerritories.clear();
        selectionHasChanged = true;
    }

    public void deselectTerritories(){
        if(!territoriesToRemove.isEmpty()){
            for(String territory : territoriesToRemove){
                availableTerritories.put(territory, selectedTerritories.remove(territory));
            }
            if(!selectedTerritories.isEmpty()){
                calculateEntitiesCount(selectedTerritories);
            } else{
                entityCount = 0;          
            }
            territoriesToRemove = new List<String>();
            selectionHasChanged = true;
        }
    }

    public void calculateEntitiesCount(Map<Id, Territory> territories){
        Map<Id, Group> territoryGroups = new Map<Id, Group>([select Id from Group where RelatedId in :territories.keySet() AND Type='Territory']);
      
        Integer count = [select count() from AccountShare where UserOrGroupId in :territoryGroups.keySet()];
      
        entityCount = count;
    }

    public void updateFilters(){
        /*List<String> tsfsToAdd = new List<String>();
        for(String territory : selectedTerritories){
            if(!existingTerritories.contains(territory)){
                tsfsToAdd.add(territory);
            }
        }*/
        List<String> territoryNames = new List<String>();
        for(Territory territory : selectedTerritories.values()){
            territoryNames.add(territory.Name);
        }

        territoriesSynced.Territory_Names__c = String.join(territoryNames, ',');
        upsert territoriesSynced;

        //First, remove all Entity Sync records for user
        List<Entity_Sync___c> existingSyncs = [select Id from Entity_Sync___c where User___c = :UserInfo.getUserId()];

        delete existingSyncs;

        List<Group> territoryGroups = [select Id from Group where RelatedId in :selectedTerritories.keySet() AND Type='Territory'];
        List<Id> accountIds = new List<Id>();
        if(territoryGroups != null){
            List<Id> territoryGroupIds = new List<Id>();
            for(Group territoryGroup : territorygroups){
                territoryGroupIds.add(territoryGroup.Id);
            }
            List<AccountShare> accountShares = [select AccountId from AccountShare where UserOrGroupId in :territoryGroupIds];
            for(AccountShare accountShare : accountShares){
                accountIds.add(accountShare.AccountId);
            }
        }

        List<Entity_Sync___c> newEntitySyncs = new List<Entity_Sync___c>();
        for(Id accountId : accountIds){
            Entity_Sync___c newEntitySync = new Entity_Sync___c();
            newEntitySync.User___c = UserInfo.getUserId();
            newEntitySync.Entity___c = accountId;
            newEntitySyncs.add(newEntitySync);
        }

        insert newEntitySyncs;
        /*

        List<TSF_vod__c> tsfRecordsToAdd = [select Id, Account_vod__c from TSF_vod__c where Territory_vod__c in :tsfsToAdd];

        for(TSF_vod__c tsf : tsfRecordsToAdd){
            tsf.Sync_Entity___c = true;
        }

        update tsfRecordsToAdd;

        List<TSF_vod__c> tsfRecordsToRemove = [select Id, Territory_vod__c, Sync_Entity___c from TSF_vod__c where Territory_vod__c in :totalTerritoriesToRemove];

        for(TSF_vod__c tsf : tsfRecordsToRemove){
            tsf.Sync_Entity___c = false;
        }

        update tsfRecordsToRemove;
      
        List<Territories_Synced__c> territoriesToRemove = [select Id from Territories_Synced__c where Name in :totalTerritoriesToRemove];

        delete territoriesToRemove;*/
    }
}