• Melody4500
  • NEWBIE
  • 0 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 0
    Replies
Hello, 
I am troubleshooting a Trigger.isBefore where there is a List that pulls back almost 10,000 records. This is being triggered from a VF page and when they pick multiple appointments in an execution, it can hit the 50,000+ SOQL rows returned error. I wanted to replace the Trigger.New with Trigger.NewMap but since this is an isBefore trigger, the IDs won't be there so it won't work (if I'm understanding that correctly). Any other recommendations on how I can rewrite to pull back less records or to only run the query once? SOQL Query that is causing the issue is bolded below. 

trigger StudioSlotTriggerAll on Studio_Slot__c (before insert, before update) 
{
    if(Trigger.isBefore)
    {
        if(Trigger.isInsert || Trigger.isUpdate){
            Datetime startDate = Datetime.now();
            Datetime endDate = Datetime.now();
            Set<Id> studioIds = new Set<Id>();
            {
                for(Studio_Slot__c studioSlot : Trigger.new)
                {
                    
                    if(studioSlot.Start_Time__c >= studioSlot.End_Time__c)
                    {
                        studioSlot.addError('Start Date must be before End Date!');
                    }
                    else
                    {
                        if(studioSlot.Start_Time__c > startDate) 
                        {
                            startDate = studioSlot.Start_Time__c;
                        }
                        
                        if(studioSlot.End_Time__c > endDate)
                        {
                            endDate = studioSlot.End_Time__c;
                        }
                    }
                    
                    studioIds.add(studioSlot.Studio__c);
                }
            }
            
            List<Studio_Slot__c> existingStudioSlotList =
                [SELECT Start_Time__c, End_Time__c, Id, Studio__c
                 FROM Studio_Slot__c
                 WHERE Start_Time__c >= :startDate
                 AND End_Time__c <= :endDate
                 ORDER BY Start_Time__c 
                 Limit 10000 
                ];
 
            for(Studio_Slot__c studioSlot : Trigger.new)
            {
                for(Studio_Slot__c existingStudioSlot : existingStudioSlotList)
                {
                    //overlapping studio slots
                    if(studioSlot.Id != existingStudioSlot.Id && studioSlot.Studio__c == existingStudioSlot.Studio__c && (existingStudioSlot.Start_Time__c < studioSlot.End_Time__c && existingStudioSlot.End_Time__c > studioSlot.Start_Time__c))
                    {
                        studioSlot.addError('Studio Slot is overlapping with the existing studio slot(Id): ' + existingStudioSlot.Id);
                    }
                }
            }