• GlynA
  • PRO
  • 2166 Points
  • Member since 2013
  • Technology Director
  • ClosedWon


  • Chatter
    Feed
  • 65
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 330
    Replies
Hello,

im am trying to create a trigger that will update any accounts employee size from blank to 10 and i am getting an "Illegal assignment from String to Integer" error message. The below code should update any account that has a NULL employee size to 10. Any help would be useful.

trigger UpdateEmployeesize on Account (Before insert,after update) {
    for (account accountinloop: Trigger.new){
        if(accountinloop.NumberOfEmployees== 'NULL'){
            accountinloop.NumberOfEmployees='10';
            }
        

}
}
I have a trigger that will create a Ownership Record when a field is populated on the contact. It takes that field and the contact and creates the association and adds it to the related list.  It is working pretty well except the first time it runs ie. when the field is empty and I put in a value (lookup from the property object) it creates 2 Ownership records. Every other time it only creates one. I do not want the trigger to run if the field is empty obviously because then it would not be able to create the record. I am not sure what I am doing wrong here.  Any help is very much appreciated. 

rigger PropOwned on Contact (after update) {
        for (Contact c : Trigger.new){
        McLabs2__Ownership__c ownNew= new McLabs2__Ownership__c();
        Contact oldContact = Trigger.oldMap.get(c.id);
        if (c.One_Prop_Owned__c != oldContact.One_Prop_Owned__c)
        if (c.One_Prop_Owned__c == null || c.One_Prop_Owned__c == c.One_Prop_Owned__c){
        ownNew.McLabs2__Contact__c = c.id;
        ownNew.McLabs2__Property__c = c.One_Prop_Owned__c;
        insert ownNew;
        }
    }
}
I am helping a non-profit organization and I am very new to salesforce development (i'm an admin). What I am trying to accomplish is we have a contact (Nominee) and on their record a look-up field to another contact (referree). I need to write a trigger that will populate the account that contact (referree) is associated with on the contact (nominee) field referred_by_org__c  at that point in time.

This is my way around historical data - if the referree moves accouts I want to know what account they were associated with at the time they nominated contact (Nominee)

Any help would be very appreciated!
Kiaya
I have three custom objects (A, B, C with A being the parent of B; B being the parent of C).

Goal: Create a single console screen with :
  • all details for Object A
  • all details for the most recent Object B
  • all records for Object C that are related to the most recent Object B
     
1. Is this possible?
2. Can anyone give me a high-level starting point so I can start researching from there

I've tried lots of things with creating different Visualforce pages to display different details from the various Objects, but i just can't get it to work. 
How can I check using APEX if a JSON node exist in the input as in below?

Payload1
{
            "lname": "l1",
            "fname": "f1"
}

Payload2 
{
            "lname": "l1"
}


Thanks
Manohar
I found this trigger and it seems that one of the past developer is doing an update  of an opportunity within the trigger instead with the class.

From what I understood, that the class will still be executing eventhough after the record page has been updated and reloaded for the end-user? Never experience this before, how about anyone here?

trigger Opp on Opportunity (after update) {
    for (Integer i = 0; i < Trigger.old.size(); i++) {
        Opportunity old = Trigger.old[i];
        Opportunity nw = Trigger.new[i];
        Boolean man = false;
      
        if ((nw.Probability == 100) && (old.Probability != nw.Probability)) {
      
            oppClose.createCase(nw.Id, man);
            //Clone statuses indicate different follow-up actions for people.
            if (nw.Clone_Status__c != 'Completed' && nw.Clone_Status__c != 'Non-renewable' && nw.Clone_Status__c != 'Exception') {
            oppClose.cloneOpp(nw.Id);
          
            /*Clone Status field is updated from the trigger instead of the the class. The class runs asynchronsously (ie. in the future)
            * so the results do not show up immediatley in the Opp after closing it won and returning to the saved record.
            * By updating the field in the trigger a flag is set to alert the user and to prevent a subsequent update from
            * triggering the class again if the async execution is delayed.
            */
            Opportunity opp = new Opportunity(
            Id = nw.Id,
            Clone_Status__c = 'Completed');
            update opp;
            }
        }
    }
  • January 15, 2014
  • Like
  • 0
I need a little help making a slight change to an apex class. 

Current code:

if (UnitType == 'New Unit')
       wherestr += 'And Family != \'Refurbished\' ';
   else if (UnitType == 'Refurbished Unit')
       wherestr += 'And Family = \'Refurbished\' ';

Need it to have an OR statement to exclude or include (respectively) a second product family of Spare Parts like whats below, but that isn't correct and is where I need help.

if (UnitType == 'New Unit')
      wherestr += 'And Family != \'Refurbished\'  OR \'Spare Parts\' ';
  else if (UnitType == 'Refurbished Unit')
       wherestr += 'And Family = \'Refurbished\' OR \'Spare Parts\' ';
<apex:page controller="worldcup">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:inputField value="{!wc.Name}"/>
<apex:inputField value="{!wc.who_is_going_to_win__c}"/>
<apex:commandButton action="!{Save}" value="save"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

this is my VF page and the method i have used is :

public class worldcup {

    public worldcup() {

    }

public WorldCup__c wc;

public worldcup (ApexPages.StandardController controller) {
this.wc = (WorldCup__c)Controller.getRecord();
}

public WorldCup__c getwc(){
    return wc;
    }
   
    Public PageReference save(){
   
   WorldCup__c wc=[Select id,Name, who_is_going_to_win__c From WorldCup__c];
  
   upsert wc;
    return null;
    }

}

after i submitted a record on the VF page i recieved an error saying Formula Expression is required on the action attributes. am i missing the save attribute ? 
When an Account is deleted the related Contacts are also removed from Salesforce.  What event eliminates them?  I have created a trigger to capture the ID of the contacts when they are deleted. It is successful when the contacts are deleted individually or merged through the UI.  However, when they are removed with an Account deletion the ID's are not captured.  The "After Delete" trigger on the contact does not seem to fire.

Is there some other kind of event that needs to be monitored?
If you write a apex class and call it in the trigger, will you be able to avoid the governor limits?
Can a profile have multiple Record types?
When we will use before & after triggers?
I have an object where OWD is private, if i want to give access to the manager above me(software engineer) ,No roles are specified... other than sharing rule, how can we achieve?
I currently am updating a custom object's strategic industry based on the user choosing the industry segment, then apex code is looking up the coorrelating strategic industry. Below is the code

Map<string, Industry_Definition__c> imap = new Map<string, Industry_Definition__c>();
   
    for(Industry_Definition__c i : [select id, Market_Segment__c, Strategic_Industry__c from Industry_Definition__c]){
        imap.put(i.Market_Segment__c, i);
        system.debug('##########i.Market_segment__c:'+ i.market_segment__c);
    }
                     
     for( Integer i = 0; i < Trigger.new.size(); i++){
            trigger.new[i].Strategic_Industry__c = imap.get(trigger.new[i].industry_Segment__c).Strategic_Industry__c;
    }

I need to extend thefunctionality to populate the strategic industry on the related account with the same value as the strategic industry on the trigger.new record. I am trying to use the code below to update the account strategic industry
Map<id, Customer_Product_Line_Item__c> cmap = new Map<id, Customer_Product_Line_Item__c>(Trigger.new);
   
    Account[] relatedaccount = new List<Account>(); relatedaccount = [select id, Strategic_Industry__c from account
        where id in:cmap.keyset()];

    for(Account a : relatedaccount){
        a.Strategic_Industry__c = imap.get(cmap.industry_segment__c).Strategic_Industry__c;
    }

The above code is returning the following error:
Error: Compile Error: Initial term of field expression must be a concrete SObject: MAP<Id,Customer_Product_Line_Item__c> at line 20 column 44


Here is the entire trigger:
trigger IndustrytoAcctOpp on Customer_Product_Line_Item__c (Before Insert, Before Update) {

    Map<string, Industry_Definition__c> imap = new Map<string, Industry_Definition__c>();
   
    for(Industry_Definition__c i : [select id, Market_Segment__c, Strategic_Industry__c from Industry_Definition__c]){
        imap.put(i.Market_Segment__c, i);
        system.debug('##########i.Market_segment__c:'+ i.market_segment__c);
    }
                     
     for( Integer i = 0; i < Trigger.new.size(); i++){
            trigger.new[i].Strategic_Industry__c = imap.get(trigger.new[i].industry_Segment__c).Strategic_Industry__c;
    }
   
    Map<id, Customer_Product_Line_Item__c> cmap = new Map<id, Customer_Product_Line_Item__c>(Trigger.new);
   
    Account[] relatedaccount = new List<Account>(); relatedaccount = [select id, Strategic_Industry__c from account
        where id in:cmap.keyset()];

    for(Account a : relatedaccount){
        a.Strategic_Industry__c = imap.get(cmap.industry_segment__c).Strategic_Industry__c;
    }

}

How do I solve this problem?
Thank you
Hi,

I am trying to build a SOQL query and my condition is when Intake date in object 1 is greater than Start date in object 2 and lesser than End date n Object, then I will be getting the id of the record.  Please see my code below:

Object1 obj1 = trigger.new[0];
List<Object2> DateList = [Select id, Start_Date__c, End_Date__c FROM Object2 WHERE obj1.Intake_Date__c > Start_Date__c AND obj1.Intake_Date__c < End_Date__c];

Can someone please suggest a fix to my code?

Thanks!
I have two custom objects I'm trying to access via apex with a VF page overlay for force.com guest user access.  For one, even though I have enabled read/edit permissions in both the guest profile and field level security on the object itself the guest user in my test only has the ability to read, not make edits, and so the dependent methods meant to make adjustments error out.  For the other custom object I have granted the same permissions/field securities, but users cannot even read from the fields.  The class works fine when I test as an admin with the same data, so I know that it's just that the guest user for some reason does not have the necessary access, even though I've granted it.  Were there any recent changes to salesforce anyone knows of which may now be restricting guest user access or would require me to make permission edits somewhere aside from on the object and guest profile?
Here hidden_field__c is a checkbox.

When in the VFP if user changes the checkbox to true in the database it still shows as false and vice-versa

Can someone please point out what's missing in my code.?

This is my simple code

<pre>

public class dataTableCon {

    List<Account> accounts;

    public List<Account> getAccounts() {

        if(accounts == null) accounts = [select name, owner.name,hidden_field__c from account limit 10];

        return accounts;

    }

}

</pre>

<pre>
<apex:page controller="dataTableCon" id="page">
   
    <apex:form >
   
    <apex:pageBlock id="theBlock">
   
    <apex:dataTable value="{!accounts}" var="account" id="theTable" rowClasses="odd,even" styleClass="tableClass">
   
        <apex:column >
            <apex:facet name="header">Private</apex:facet>
            <apex:inputCheckbox value="{!account.hidden_field__c}" >
             <apex:actionSupport event="onchange" rerender="theBlock"/>
           </apex:inputCheckbox>           
        </apex:column>
   
       
        <apex:column >
            <apex:facet name="header">Name</apex:facet>
            <apex:outputText value="{!account.name}"  >
        </apex:column>
   
        <apex:column >
            <apex:facet name="header">Owner</apex:facet>
            <apex:outputText value="{!account.owner.name}"  >
        </apex:column>
       
    </apex:dataTable> 
   
    </apex:pageBlock>
    </apex:form>
</apex:page>  

</pre>
  • January 10, 2014
  • Like
  • 0
Hi All,
        I am using a wrapper class with checkboxes to display a list of conact record with contact phone field and Account name. In this list  upon selection of a checkbox i wanna 2 updates.
1. Contact Phone Field.
2. Contacts Account Name.
Code is pretty standard , taken from wrapper class documentation example ,Its given below:

Apex:
public class wrapperClassController {
    //Our collection of the class/wrapper objects cContact 
    public List<cContact> contactList {get; set;}
    public List<Account> AccountList {get; set;}
    public List<Id> AccountIdList {get; set;}
    //This method uses a simple SOQL query to return a List of Contacts
    public List<cContact> getContacts() {

        if(contactList == null) {
            contactList = new List<cContact>();
            for(Contact c: [select Id, Name, Email, Phone, Contact.Account.Name,Contact.Account.isPersonAccount from Contact limit 10]) {
                // As each contact is processed we create a new cContact object and add it to the contactList
                contactList.add(new cContact(c));
            }
        }
        return contactList;
    }
    public PageReference processSelected() {
    //We create a new list of Contacts that we be populated only with Contacts if they are selected
      List<Contact> selectedContacts = new List<Contact>();
      //We will cycle through our list of cContacts and will check to see if the selected property is set to true, if it is we add the Contact to the selectedContacts list
      for(cContact cCon: getContacts()) {
            if(cCon.selected == true) {
                selectedContacts.add(cCon.con);
            }
        }
      // Now we have our list of selected contacts and can perform any type of logic we want, sending emails, updating a field on the Contact, etc
      System.debug('These are the selected Contacts...');
      for(Contact con: selectedContacts) {
          
            system.debug('aaaaaaaaaaaaaaaaaaaaaaaa'+con);
            
       }

       update selectedContacts;
       contactList=null; // we need this line if we performed a write operation  because getContacts gets a fresh list now
       return null;
   }
   // This is our wrapper/container class. A container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. In this example a wrapper class contains both the standard salesforce object Contact and a Boolean value
    public class cContact {
        public Contact con {get; set;}
        public Boolean selected {get; set;}
        //This is the contructor method. When we create a new cContact object we pass a Contact that is set to the con property. We also set the selected value to false
        public cContact(Contact c) {
        con = c;
        selected = false;
      }
    }


}
///////////////////////////////////////////VF PAGE////////////////////////////////////////////////
<apex:page controller="wrapperClassController">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Process Selected" action="{!processSelected}" rerender="table"/>
            </apex:pageBlockButtons>
            <!-- In our table we are displaying the cContact records -->
            <apex:pageBlockTable value="{!contacts}" var="c" id="table">
            <apex:column >
            <!-- This is our selected Boolean property in our wrapper class -->
            <apex:inputCheckbox value="{!c.selected}"/>
            </apex:column>
            <!-- This is how we access the contact values within our cContact container/wrapper -->
            <apex:column value="{!c.con.Name}" />
            <apex:column value="{!c.con.Email}" />
            <!--<apex:column value="{!c.con.Phone}" />-->
            <apex:column title="Contact Phone" headerValue="Contact Phone">
                 <apex:facet name="Contact Phone">Contact Phone</apex:facet>
                 <apex:inputField value="{!c.con.Phone}" />
           </apex:column>
           <apex:column title="Account Name" headerValue="Account Name">
                 <apex:facet name="Account Name">Account Name</apex:facet>
                 <apex:inputField value="{!c.con.Account.Name}" />
           </apex:column>
           </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Upon click of button phone field is getting updated , plz help me with updation of Account Name as well




Thanks
Shrey Tyagi



Hi ,

In the below code if i try to run i am getting. the error like this (FAQCu Compile Error: Comparison arguments must be compatible types: LIST<String>, String at line 20 column 12)I have hilighted the errior in bold letters in the below code

public class FAQCu {
public List<String> selectedValue {get;set;}
public List<SelectOption> getUserType()
{
  List<SelectOption> options = new List<SelectOption>();  
   Schema.DescribeFieldResult fieldResult =FAQ__c.Users__c.getDescribe();
   List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
     // options.add(new SelectOption('All','All'));
   for( Schema.PicklistEntry f : ple)
   {
      options.add(new SelectOption(f.getLabel(), f.getValue()));
   }  
   return options;
}
public List<FAQ__c> getSearch(){
        System.debug('====selectedValue===='+selectedValue); // You will get the Selected Value here
      
        List<FAQ__c> temp = new List<FAQ__c>();
        String queryString;
       Line 20// if(selectedValue=='AllUsers')
   queryString='SELECT Users__c,Question__c,Answer__cfrom FAQ__c WHERE Users__c =AllUsers';
   else if(selectedValue=='InternalUsers')
   queryString='SELECT Users__c,Question__c,Answer__c from FAQ__c WHERE Users__c =InternalUsers';
   else if(selectedValue=='ExternalUsers')
queryString='SELECT Users__c,Question__c,Answer__c from FAQ__c WHERE Users__c =ExternalUsers';
   temp = Database.query(queryString);
 
      return temp;
      }
    }

and the vf page is:
<apex:page controller="FAQCu">
<apex:form >

<apex:selectList id="users" value="{!selectedValue}" size="1" required="true">
  <apex:selectOptions value="{!userType}"/>
</apex:selectList>

</apex:form>
</apex:page>

Please help me on this

Thanks
Veeraiah
Hey Community!  I've got a class that implements Schedulable.  It has members that are lists of sObjects.  Sometimes these lists can be very large (thousands of records).  When I try to schedule these large instances, it fails, saying that the scheduled object is "too large".  I can't find anything that describes how large a Schedulable class instance can be.  Does anyone out there know?

Thanks in advance,

Glyn Anderson
Sr Developer / Systems Analyst | ClosedWon | closedwon.com
Certified Developer | Certified Advanced Administrator

  • December 29, 2014
  • Like
  • 0
Hello,

im am trying to create a trigger that will update any accounts employee size from blank to 10 and i am getting an "Illegal assignment from String to Integer" error message. The below code should update any account that has a NULL employee size to 10. Any help would be useful.

trigger UpdateEmployeesize on Account (Before insert,after update) {
    for (account accountinloop: Trigger.new){
        if(accountinloop.NumberOfEmployees== 'NULL'){
            accountinloop.NumberOfEmployees='10';
            }
        

}
}
We are trying to access data from ForecastingItem using Apex. The code works fine in Execute Anonymous window of Developer Console. When we try to put it as a method in Apex class, we are unable to do so. 

We have 4 Forecast Types defined and have not changed any picklist values anywhere - it is an out-of-the-box environment. 

Code:
public List<ForecastingItem> getForecastItems(List<Id> userIdList, List<Id> periodIdList, List<Id> forecastTypeList) {

List<ForecastingItem> forecastItemList = [SELECT AmountWithoutAdjustments, AmountWithoutManagerAdjustment, 
ForecastAmount, ForecastCategoryName, ForecastingTypeId, 
ForecastQuantity, HasAdjustment, Id, IsAmount, IsQuantity, 
IsUpToDate, OwnerId, OwnerOnlyAmount, OwnerOnlyQuantity, 
ParentForecastingItemId, PeriodId, ProductFamily, 
QuantityWithoutAdjustments, 
QuantityWithoutManagerAdjustment,
Owner.Name
FROM ForecastingItem
WHERE OwnerId in :userIdList
AND PeriodId in :periodIdList
AND ForecastingTypeId in :forecastTypeList
];

return forecastItemList;


User-added image
 
I'm trying to setup a simple bit of code that recieves a PayPal Instant Payment Notification (IPN) finds the created Opportunity and checks a box called "paid".

The key field in Salesforce is "FormAssemblyID" 
The IPN sends a block of text that includes this parameter: &custom=https://ncoa.tfaforms.net/responses/view/52932682&

My class is supposed to extract this and use it to lookup the right opportunity and a check a box. It's either not finding the right opportunity or its not checking the Paid box when it does and can't figure out which it is.

Here is the opportunity field that it should be finding:   User-added image

And here is my code:

public class IPNHandlerController {

    public PageReference myIPNupdate() {
     try{
        PageReference pageRef = ApexPages.currentPage();
        //Get the value of the 'custom' parameter from current page
        String paramCustom = pageRef.getParameters().get('custom');
        opportunity = [select Id,paid__c from Opportunity where FormAssemblyID__c = :paramCustom ];

        String content = '';
        for(String key : pageRef.getParameters().keySet()){
            //Note that there is no guarantee of order in the parameter key map.
            content += key + ' : ' + pageRef.getParameters().get(key) + '\n';
        }
        opportunity.PayPalInfo__c = content;
        opportunity.paid__c = True;
        update opportunity;

        PageReference newPage = new ApexPages.StandardController(opportunity).view();
        newPage.setRedirect(true);        

        return newPage;
     } catch (System.Exception e){
         //A failure occurred
         system.debug(e);
         return null;
     }
    }

    public Opportunity opportunity {get; set;}

    public IPNHandlerController() {
    }
}

Hello,

I recently created a trigger on Case that updates a couple custom fields when the Case Owner changes.  It works great, except when a User uses the Accept button to change the ownership from a Queue to their account.  When this happens, the trigger executes twice.  I need to catch this behavior and make sure the trigger logic only executes once, but I cannot figure out how to mimic the "Accept" button in my Apex Text Class. 

There are two ways I hope this community could help me:
1) How can I get the Developer Console to generate logs based on my actions using clicks within SF, rather than just from running tests within the developer's console?
2) Or, how can I mimic the 'Accept' button in an Apex test?

Thank you!
-John Gorzynski

Trigger Code:
 

trigger CaseOwnerChangeEscalation on Case (after insert, before update) {  //, before update

/****************************
 * Written by:  John Gorzynski 
 * 				June 04, 2015
 * 
 * This trigger looks at new and modified Cases and sets the GSCC_Queue__c field in order to track Escalations.
 * STEP 1) Determine if the Record Type is a Support Services Case, or if a change in Case Owner or Oracle_SR_Owner_Name__c has occurred.  Only process these cases.
 * STEP 2) Process all Case changes, collect User and Group (Queue) IDs to find the correct value for GSCC_Queue__c
 * 		-) If Owner is Group, use Group.Name.    If Owner is User, use User.GSCC_Queue__c, which is set by Formula Field on the Users table.
 * STEP 3) Once Cases have been updated, check if they moved from Tier 1 to Tier 2 or Tier 3.  If so, increment Case.Escalation_Count__c
 * 		-) If an Escalation happened, add a Case Comment with the User who updated the ticket, regardless of queue, and what Tier change or Tier 3 group assignment occurred. 
 * **************************/
 
/*** Step 1:  Identify Support Services Cases where the Case Owner or Oracle_SR_Owner_Name__c has changed.  Ignore all others.***/
    
    System.debug('[Trigger Start]');
        
        List<Case> caseList = new List<Case>();
        List<Case> oldCases = new List<Case>();
    	List<Case> newCases = new List<Case>();
        List<Group> groupList = new List<Group>();
        List<User> userList = new List<User>();
        Set<Id> ownerIds = new Set<Id>();
    	Set<Id> Tier3Ids = new Set<Id>();
    	Set<Id> rt = new Set<Id>();
    
    	if(Trigger.isInsert){
    		for(Case ci : [SELECT Id, OwnerId, Escalation_Count__c, Oracle_SR_Owner_Name__c, GSCC_Queue__c, RecordTypeId FROM Case WHERE ID IN :Trigger.New]) 
            {   newCases.add(ci);   }
        }
        if(Trigger.isUpdate){
            for(Case cu : Trigger.New)  
            {  newCases.add(cu);  }    
        }
    
    	//Grab all Record Types that include Support Services in the Name field.  Only run trigger on cases with these RecordTypeIds.
   		for(RecordType rec : [Select Id, Name FROM RecordType WHERE Name LIKE '%Support Services%'])
        {  rt.add(rec.Id);  }
    
    	//Filter cases by those with an owner change or Tier 3 change, but only for Support Services cases.
        for(Case c : newCases) 
        {         
            
            //Set beforeUpdate so Trigger.isInsert will avoid a Null Pointer exception.
            Case beforeUpdate = (Trigger.isUpdate) ? System.Trigger.oldMap.get(c.Id) : new Case(); 
			
            String oldTier3 = (beforeUpdate.Oracle_SR_Owner_Name__c!=NULL) ? beforeUpdate.Oracle_SR_Owner_Name__c : '';
            String newTier3 = (c.Oracle_SR_Owner_Name__c!=NULL) ? c.Oracle_SR_Owner_Name__c : '';
            Boolean isOwnerChange = (beforeUpdate.OwnerID != c.OwnerID);  //OwnerID Should never be null
            Boolean isTier3Change = (oldTier3 != newTier3);
            Boolean isTier3 = (c.Oracle_SR_Owner_Name__c!=NULL);  //We only want Tier3 changes to trigger, but always use Tier 3 if set.
            Boolean isSupportRT = false;

            try{
                String newRT = (c.RecordTypeId==NULL) ? '' : c.RecordTypeId;
            	isSupportRT = rt.contains(newRT);  //True if Record Type contains 'Support Services'
            }
            catch (Exception e) { isSupportRT = false; }  //Throws a String Exception: Invalid ID if RecordTypeId is not set.

            
            System.debug('[Pre-Trigger] Old Trigger: GSCC_Queue__c:'+beforeUpdate.GSCC_Queue__c+' | OwnerID:'+beforeUpdate.OwnerID+' | Oracle_SR_Owner_Name__c:'+beforeUpdate.Oracle_SR_Owner_Name__c+' | Escalation_Count__C:'+beforeUpdate.Escalation_Count__C+' ||| New Trigger: GSCC_Queue__c:'+c.GSCC_Queue__c+' | OwnerID:'+c.OwnerID+' | Oracle_SR_Owner_Name__c:'+c.Oracle_SR_Owner_Name__c+' | Escalation_Count__C:'+c.Escalation_Count__C);
            
            if((Trigger.isInsert||isOwnerChange||isTier3Change)&&isSupportRT){
               Decimal newEscalation = (c.Escalation_Count__c!=NULL) ? c.Escalation_Count__c : 0;
               c.Escalation_Count__c = newEscalation; 
               System.debug('[Trig Test]: c.Escalation_Count__c:'+c.Escalation_Count__c+' newEscalation:'+newEscalation);
               caseList.add(c);
               if(!isTier3) ownerIds.add(c.ownerId);  //We don't need OwnerID if Tier 3 is set
               if(isTier3) Tier3Ids.add(c.Id);               
               oldCases.add(beforeUpdate);
            }
            if(!isSupportRT)  System.debug('[Pre-Trigger] Case.RecordType does not include Support Services');  
        }

        System.debug('[Trig] caseList.size():'+caseList.size()+' = OwnerIDs:'+OwnerIds.size()+' + Tier3Ids:'+Tier3Ids.size());

    
/*** Step 2:  For valid Case updates, determine what field changed and set GSCC_Queue__c:
	 -) If new CaseOwner is a Queue, set to Group.name;
	 -) If new CaseOwner is a User, set to User.GSCC_Queue__c (set by Formula Field on User object)
	 -) If Oracle_SR_Owner_Name__c is set, ignore any CaseOwner change and use that value for Tier 3.
***/
   
        if(caseList.size()>0){  
           
            System.debug('[Trig] Cases have recent updates, processing Trigger.');
              
            for(Group g : [SELECT Id, Name FROM Group WHERE Id IN :ownerIds]){ 
                if(g.Name==NULL) g.Name = ''; 
                groupList.add(g); 
            }
                    System.debug('[Trig] groupList.size():'+groupList.size());
            
            for(User u : [SELECT Id,Name,GSCC_Queue__c FROM User WHERE Id IN :ownerIds]){ 
                if(u.GSCC_Queue__c==NULL) u.GSCC_Queue__c = '';  //Prevents Null Pointer Exception if GSCC_Queue__c is not set.
                userList.add(u); 
            }
                     System.debug('[Trig] userList.size():'+userList.size());
            
            //If CaseOwner is a Queue, Assign Queue.Name to Case.GSCC_Queue__c
            
            for(Integer i = 0; i < caseList.size();i++){
                
               if((caseList[i].OwnerId.getSobjectType() == Group.sobjecttype)&&!(Tier3Ids.contains(caseList[i].Id))){
                   for(Integer k=0; k < groupList.size();k++){
                       if(caseList[i].OwnerId == groupList[k].Id){
                            caseList[i].GSCC_Queue__c = groupList[k].Name;
                       }
                    }
                }
                
            	//If CaseOwner is a User, Assign User.GSCC_Queue__c to Case.GSCC_Queue__c
           		//User.GSCC_Queue__c is set manually per Agent in a Formula Field on the User table.
            
                if((caseList[i].OwnerId.getSobjectType() == User.sobjecttype)&&!(Tier3Ids.contains(caseList[i].Id))){
                    for(Integer m=0; m < userList.size(); m++){
                         if(caseList[i].OwnerId == userList[m].Id){
                            caseList[i].GSCC_Queue__c = userList[m].GSCC_Queue__c;
                         }
                     }
                }
                System.debug('[Trig: Assignment Complete] caseList['+i+']: Id:'+caseList[i].Id+' | GSCC_Queue__c:'+caseList[i].GSCC_Queue__c+' | Oracle_SR_Owner_Name__c:'+caseList[i].Oracle_SR_Owner_Name__c+' | Escalation_Count__c:'+caseList[i].Escalation_Count__c);
                
                if(caseList[i].Oracle_SR_Owner_Name__C!=NULL){
					caseList[i].GSCC_Queue__c = (caseList[i].Oracle_SR_Owner_Name__c.contains('Tier 3')) ? caseList[i].Oracle_SR_Owner_Name__c : 'Tier 3 '+caseList[i].Oracle_SR_Owner_Name__c; 
				}
            } //End for loops for setting c.GSCC_Queue__c


/*** Step 3:  If Tier level has increased, increment Case.Escalation_Count__c. and add a Case Comment***/            
            for(Integer j = 0; j < caseList.size();j++){
                String oldQueue = (oldCases[j].GSCC_Queue__c!=NULL) ? oldCases[j].GSCC_Queue__c : '[No GSCC Tier Set]';
                String newQueue = (caseList[j].GSCC_Queue__c!=NULL) ? caseList[j].GSCC_Queue__c : '[No GSCC Tier Set]';
 
                datetime myDateTime = datetime.now();
				
                
                //If GSCC_Queue__c has changed Tier, escalate the case and add a Case Comment
                if((oldQueue.contains('Tier 1')&&newQueue.contains('Tier 2'))||
                   (oldQueue.contains('Tier 2')&&newQueue.contains('Tier 3'))||
                   (oldQueue.contains('Tier 1')&&newQueue.contains('Tier 3'))||
                   (oldQueue=='[No GSCC Tier Set]'&&newQueue.contains('Tier 2'))||
                   (oldQueue=='[No GSCC Tier Set]'&&newQueue.contains('Tier 3'))) 
                    { caseList[j].Escalation_Count__c += 1; 
                      system.debug('[Trig] CaseList['+j+'] Escalated - Escalation_Count__c:'+caseList[j].Escalation_Count__c+', Id:'+ caseList[j].id);
                     
                      CaseComment com = new CaseComment();
                      TimeZone tz = UserInfo.getTimeZone();
                      String strConvertedDate = myDateTime.format('MMMM dd, yyyy hh:mm:ss a z', tz.getId());
                      com.ParentId = caseList[j].id;  
                      com.CommentBody = 'This case was escalated by '+ UserInfo.getName() +' from '+oldQueue+' to '+newQueue+' on '+strConvertedDate;
 
                      system.debug('[Trig] Case Comment:'+com.CommentBody);
                      Insert com;
                    }
               }
            if(Trigger.isInsert) 
            { update caseList; }
        } //End If: caseList.size()>0 or isInsert
}

Test Code:

@isTest static void TestEscalationByOracleSRNameChange() {
 
         //Test Queues and Users have had their values chosen to run ten tests:
            //0) Tier 1 Nav (Tier3 set) -> Tier 2 Nav (Tier 3 No Change)	Result:  Escalation:1   Setting to Tier 2 should be ignored.                                 
			//1) Tier 2 Nav 	        -> Tier 2 Nav (Tier 3 set)    		Result:  Escalation:2   Escalates on Insert to Tier 2 And when Tier 3 is set.  
			//2) Tier 1 Ops (Tier3 set) -> Tier 1 Nav (Tier 3 Change) 		Result:  Escalation:1   Changes within Tier 3 are not another Escalation.
			//3) Tier 2 Ops (Tier3 set) -> Tier 2 Nav (Tier 3 No Change)    Result:  Escalation:1   Setting to Tier 2 should be ignored.
			//4) Record Type set to Professional Services					Result:  No change
			//5) Professional Services w/ Tier 2 Owner + Tier 3 set			Result:  No change, but Oracle_SR_Owner_Name__c was still set.    
			
		//Cases will first be assigned the the Queue List, and then updated to the Owner List to run these tests.
         
        List<Case> cList2 = new List<Case>(); 
        List<ID> QownIDs = new ID[6];
        List<ID> UownIDs = new ID[6];
        List<QueueSobject> mappingObjects = new List<QueueSobject>();

        RecordType rt = [Select Id from RecordType where Name = 'Support Services NAV Case' LIMIT 1]; 
        RecordType rt2 = [Select Id from RecordType where Name = 'Professional Services Case' LIMIT 1];

        List<Group> gList = new List<Group> {
             new Group(Name='Tier 1 GSCC NAV ',Type='Queue'),
             new Group(Name='Tier 2 GSCC NAV ',Type='Queue'),
             new Group(Name='Tier 1 GSCC OPS ',Type='Queue'),
             new Group(Name='Tier 2 GSCC OPS ',Type='Queue'),
             new Group(Name='Tier 1 GSCC NAV ',Type='Queue'),
             new Group(Name='Tier 2 GSCC NAV ',Type='Queue')};
                             
         //Insert Queues
         System.runAs(new User(Id = UserInfo.getUserId())) { insert gList; }
            
         for(Integer i=0; i < gList.size(); i++){ 
            QueueSobject mapObj = new QueueSobject(QueueId = gList[i].Id, SobjectType = 'Case');  
        	mappingObjects.add(mapObj);
        }
     
          //Insert Queue Relational Maps
         System.runAs(new User(Id = UserInfo.getUserId())) { insert mappingObjects; }

             
        List<User> uList = new List<User> {   //createUser generates a User object with all required fields set.  The first parameter gives unique names.  The second parameter is set to GSCC_Queue__c.
			createUser(1,'Tier 2 GSCC NAV'),
			createUser(2,'Tier 2 GSCC NAV'),
			createUser(3,'Tier 1 GSCC NAV'),
			createUser(4,'Tier 2 GSCC NAV'),
            createUser(5,'Tier 1 GSCC NAV'),
            createUser(6,'Tier 2 GSCC NAV')};

         System.runAs(new User(Id = UserInfo.getUserId())) { insert uList; }
                     		
        for(Integer k=0; k < gList.size(); k++){
      			QownIDs[k] = gList[k].ID;
            	UownIDs[k] = uList[k].ID;
        }

        List<case> cList = new List<Case> {
             new Case(OwnerID=QownIDs[0],Subject='Testing Updates',RecordTypeId = rt.Id,Oracle_SR_Owner_Name__c='Tier 3 Group 1',Escalation_Count__c = NULL),
             new Case(OwnerID=QownIDs[1],Subject='Testing Updates',RecordTypeId = rt.Id,Escalation_Count__c = NULL),
             new Case(OwnerID=QownIDs[2],Subject='Testing Updates',RecordTypeId = rt.Id,Oracle_SR_Owner_Name__c='Tier 3 Group 1'',Escalation_Count__c = NULL),
             new Case(OwnerID=QownIDs[3],Subject='Testing Updates',RecordTypeId = rt.Id,Oracle_SR_Owner_Name__c='Tier 3 Group 1'',Escalation_Count__c = NULL),
             new Case(OwnerID=QownIDs[4],Subject='Testing Updates',RecordTypeId = rt2.Id,Escalation_Count__c = NULL),
             new Case(OwnerID=QownIDs[5],Subject='Testing Updates',RecordTypeId = rt2.Id,Escalation_Count__c = NULL)};
             
        System.debug('pre-test cList[0].id:'+cList[0].Id+' - pre-test gList[0].id:'+gList[0].Id);
        System.debug('pre-test c[0]:'+cList[0]);
        System.debug('pre-test g[0]:'+gList[0]);
        System.debug('[TEST] After Insert Setup'); 
        
                 List<Database.SaveResult> srList = new List<Database.SaveResult>();
         System.runAs(new User(Id = UserInfo.getUserId())) { srList = Database.insert(cList,false); }

         for (Database.SaveResult sr : srList){
             if(sr.isSuccess()) {
                 //Operation was Successful
             }
             else {
                 //Operation failed, so get all errors
                 for(Database.Error err : sr.getErrors()) {
                     System.debug('Database Error:'+ err.getMessage());
                     System.debug('Fields that affected this error:'+ err.getFields());
                 }
             }
         }

/*** afterInsert Tests ***
*	 Trigger will execute twice due to also firing beforeUpdate, 
*	 but the second time should result in a caseList.size() of 0, causing the trigger to end before Steps 2 or 3.***/ 
		List<Case> insertTest = new List<Case>();			
         for( Case ct : [SELECT Id,GSCC_Queue__c,Escalation_Count__c,Oracle_SR_Owner_Name__c FROM Case WHERE Id IN :cList]){
             insertTest.add(ct);
         }

                 System.assertEquals('Tier 3 Group 1', insertTest[0].GSCC_Queue__c);
                 System.assertEquals('Tier 2 GSCC NAV', insertTest[1].GSCC_Queue__c);
                 System.assertEquals('Tier 3 Group 1', insertTest[2].GSCC_Queue__c);
                 System.assertEquals('Tier 3 Group 1', insertTest[3].GSCC_Queue__c);
                 System.assertEquals(NULL, insertTest[4].GSCC_Queue__c);
                 System.assertEquals(NULL, insertTest[5].GSCC_Queue__c);
                 System.assertEquals(1, insertTest[0].Escalation_Count__c);
                 System.assertEquals(1, insertTest[1].Escalation_Count__c);
                 System.assertEquals(1, insertTest[2].Escalation_Count__c);
                 System.assertEquals(1, insertTest[3].Escalation_Count__c);
                 System.assertEquals(NULL, insertTest[4].Escalation_Count__c);
                 System.assertEquals(NULL, insertTest[5].Escalation_Count__c);
                 System.assertEquals('Tier 3 Group 1', insertTest[0].Oracle_SR_Owner_Name__c);
                 System.assertEquals('Tier 3 Group 1', insertTest[2].Oracle_SR_Owner_Name__c);
                 System.assertEquals('Tier 3 Group 1', insertTest[3].Oracle_SR_Owner_Name__c);
             
/*** afterInsert Tests end ***/
         
                Integer l=0;
        for(Case c2 : [SELECT Id, GSCC_Queue__c, Escalation_Count__c, OwnerId FROM Case WHERE Subject='Testing Updates']) {
            	c2.OwnerID=UownIDs[l];
            	cList2.add(c2);
            	l++;
        }
				cList2[1].Oracle_SR_Owner_Name__c='Tier 3 Group 2';
				cList2[2].Oracle_SR_Owner_Name__c='Tier 3 Group 2';
				cList2[5].Oracle_SR_Owner_Name__c='Tier 3 Group 2';
             

        List<Database.SaveResult> srList2 = new List<Database.SaveResult>();
		Test.startTest();
         System.runAs(new User(Id = UserInfo.getUserId())) { srList2 = Database.Update(cList2,false); }
        Test.stopTest();   

         for (Database.SaveResult sr2 : srList2){
             if(sr2.isSuccess()) {
                 //Operation was Successful
             }
             else {
                 //Operation failed, so get all errors
                 for(Database.Error err2 : sr2.getErrors()) {
                     System.debug('Database Error:'+ err2.getMessage());
                     System.debug('Fields that affected this error:'+ err2.getFields());
                 }
             }
         }
     
        System.debug('post-test c[0]:'+cList[0]);
        System.debug('post-test cList[0].Id:'+cList[0].Id);
        System.debug('post-test cList[0].GSCC_Queue__c:'+cList[0].GSCC_Queue__c);
        
/*** beforeUpdate Tests ***
*	 Trigger executes a third time for beforeUpdate ***/
         
		List<Case> updateTest = new List<Case>();			
         for( Case ct2 : [SELECT Id,GSCC_Queue__c,Escalation_Count__c,Oracle_SR_Owner_Name__c FROM Case WHERE Id IN :cList2]){
             updateTest.add(ct2);
         }
             
            //0) Tier 1 Nav (Tier3 set) -> Tier 2 Nav (Tier 3 No Change)	Result:  Escalation:1   Setting to Tier 2 should be ignored.                                 
			//1) Tier 2 Nav 	        -> Tier 2 Nav (Tier 3 set)    		Result:  Escalation:2   Escalates on Insert to Tier 2 And when Tier 3 is set.  
			//2) Tier 1 Ops (Tier3 set) -> Tier 1 Nav (Tier 3 Change) 		Result:  Escalation:1   Changes within Tier 3 are not another Escalation.
			//3) Tier 2 Ops (Tier3 set) -> Tier 2 Nav (Tier 3 No Change)    Result:  Escalation:1   Setting to Tier 2 should be ignored.
			//4) Record Type set to Professional Services					Result:  No change
			//5) Professional Services w/ Tier 2 Owner + Tier 3 set			Result:  No change, but Oracle_SR_Owner_Name__c was still set.             
         
         		 System.assertEquals('Tier 3 Group 1', updateTest[0].GSCC_Queue__c);
                 System.assertEquals('Tier 3 Group 2', updateTest[1].GSCC_Queue__c);
                 System.assertEquals('Tier 3 Group 2', updateTest[2].GSCC_Queue__c);
                 System.assertEquals('Tier 3 Group 1', updateTest[3].GSCC_Queue__c);
                 System.assertEquals(NULL, updateTest[4].GSCC_Queue__c);
                 System.assertEquals(NULL, updateTest[5].GSCC_Queue__c);
                 System.assertEquals(1, updateTest[0].Escalation_Count__c);
                 System.assertEquals(2, updateTest[1].Escalation_Count__c);
                 System.assertEquals(1, updateTest[2].Escalation_Count__c);
                 System.assertEquals(1, updateTest[3].Escalation_Count__c);
                 System.assertEquals(NULL, updateTest[4].Escalation_Count__c);
                 System.assertEquals(NULL, updateTest[5].Escalation_Count__c);
                 System.assertEquals('Tier 3 Group 1', updateTest[0].Oracle_SR_Owner_Name__c);         
                 System.assertEquals('Tier 3 Group 2', updateTest[1].Oracle_SR_Owner_Name__c);         
                 System.assertEquals('Tier 3 Group 2', updateTest[2].Oracle_SR_Owner_Name__c);         
                 System.assertEquals('Tier 3 Group 1', updateTest[3].Oracle_SR_Owner_Name__c);         
                 System.assertEquals(NULL, updateTest[4].Oracle_SR_Owner_Name__c);         
                 System.assertEquals('Tier 3 Group 2', updateTest[5].Oracle_SR_Owner_Name__c);      
             
/*** beforeUpdate Tests end ***/

     }

I have a VF page that serves as a data entry screen for regional budgets.  All regions are displayed on the screen, and when a user fills in any of the budget input fields, the record is saved.  The issue is if the user tabs through the data entry fields fast enough, multiple records for the same region are created.  I do not want to make the user wait until the record is created to continue their data entry or use a submit button.  How can I stop multiple records from being created?

 
VF except......
 <apex:column width="80px" headerValue="Estimated Budget"> <apex:inputText size="10" value="{!budgetMap[budget].Estimated_Budget__c}">
    
            <apex:actionSupport event="onchange" action="{!processBudget}" status="topstatus"  rerender="contentLoading"   > 
            <apex:param name="RegionName" value="{!budget}"/>
            
            </apex:actionSupport>
            </apex:inputText>


<apex:column width="80px" headerValue="Discounts"> <apex:inputText size="10" value="{!budgetMap[budget].Discounts__c}"> <apex:actionSupport event="onchange" action="{!processBudget}" status="topstatus" rerender="contentLoading" > <apex:param name="RegionName" value="{!budget}"/> </apex:actionSupport> </apex:inputText> </apex:column>


public void processBudget()
    {//Get Region to be processed
     if(ApexPages.currentPage().getParameters().get('RegionName') != null && ApexPages.currentPage().getParameters().get('RegionName') != '' && ApexPages.currentPage().getParameters().get('RegionName') != 'null')
    {
    //Get budget record from Map- may be an existing record or one not yet inserted
    budget__c budget = budgetMap.get(ApexPages.currentPage().getParameters().get('RegionName'));
    
     Try
        {
          //If record has already been inserted, update it. 
          if(budget.Id <> NULL ) update budget;
           
          //If not yet inserted, insert it.
           else if (budget.Id == NULL) 
           {
           budget = budgetMap.get(ApexPages.currentPage().getParameters().get('RegionName'));
            insert budget;
            //Put the budget back into the Map now that it has an Id
            budgetMap.put(ApexPages.currentPage().getParameters().get('RegionName'), budget);
           }
            
           // ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, budget.Region__r.Name + ' Updated Successfully.'));
        }
        Catch(Exception e)
        {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, e.getMessage()));
            System.debug('ERROR ' + e.getMessage());
            
        }

 
Hi,
Please help me with this requirement

I have 'score' field on objectA and this object has lookup relationship to account.
I want to take average of 'score' field on all objectA records created in current quarter and stamp that value on account.


Thanks in advance
I have a trigger that will create a Ownership Record when a field is populated on the contact. It takes that field and the contact and creates the association and adds it to the related list.  It is working pretty well except the first time it runs ie. when the field is empty and I put in a value (lookup from the property object) it creates 2 Ownership records. Every other time it only creates one. I do not want the trigger to run if the field is empty obviously because then it would not be able to create the record. I am not sure what I am doing wrong here.  Any help is very much appreciated. 

rigger PropOwned on Contact (after update) {
        for (Contact c : Trigger.new){
        McLabs2__Ownership__c ownNew= new McLabs2__Ownership__c();
        Contact oldContact = Trigger.oldMap.get(c.id);
        if (c.One_Prop_Owned__c != oldContact.One_Prop_Owned__c)
        if (c.One_Prop_Owned__c == null || c.One_Prop_Owned__c == c.One_Prop_Owned__c){
        ownNew.McLabs2__Contact__c = c.id;
        ownNew.McLabs2__Property__c = c.One_Prop_Owned__c;
        insert ownNew;
        }
    }
}
I am helping a non-profit organization and I am very new to salesforce development (i'm an admin). What I am trying to accomplish is we have a contact (Nominee) and on their record a look-up field to another contact (referree). I need to write a trigger that will populate the account that contact (referree) is associated with on the contact (nominee) field referred_by_org__c  at that point in time.

This is my way around historical data - if the referree moves accouts I want to know what account they were associated with at the time they nominated contact (Nominee)

Any help would be very appreciated!
Kiaya
Hi,

I need to write a trigger for the following requirement:

My Opportunity is the master of Quotes. An Opp can have many Quotes.
Quotes is parent to the Docusign Status. A quote can have many docusign status. There is a field on Docusign status named "Envelope Status".
There is a field on Opp say "X", the value of this field will be either Completed or Incomplete. This value depends on whether all the Quotes attached to the Opp has their Envelope Status as "Completed" or "Incomplete".
I want to write the trigger such that if all the Quotes on an Opp has Envelope Status as "Completed", the field value of "X" should be completed else even if one of the Quotes is INcomplete then X shold be eqal to Incomplete.
  • January 18, 2014
  • Like
  • 0
I have three custom objects (A, B, C with A being the parent of B; B being the parent of C).

Goal: Create a single console screen with :
  • all details for Object A
  • all details for the most recent Object B
  • all records for Object C that are related to the most recent Object B
     
1. Is this possible?
2. Can anyone give me a high-level starting point so I can start researching from there

I've tried lots of things with creating different Visualforce pages to display different details from the various Objects, but i just can't get it to work. 
Here hidden_field__c is a checkbox.

When in the VFP if user changes the checkbox to true in the database it still shows as false and vice-versa

Can someone please point out what's missing in my code.?

This is my simple code

<pre>

public class dataTableCon {

    List<Account> accounts;

    public List<Account> getAccounts() {

        if(accounts == null) accounts = [select name, owner.name,hidden_field__c from account limit 10];

        return accounts;

    }

}

</pre>

<pre>
<apex:page controller="dataTableCon" id="page">
   
    <apex:form >
   
    <apex:pageBlock id="theBlock">
   
    <apex:dataTable value="{!accounts}" var="account" id="theTable" rowClasses="odd,even" styleClass="tableClass">
   
        <apex:column >
            <apex:facet name="header">Private</apex:facet>
            <apex:inputCheckbox value="{!account.hidden_field__c}" >
             <apex:actionSupport event="onchange" rerender="theBlock"/>
           </apex:inputCheckbox>           
        </apex:column>
   
       
        <apex:column >
            <apex:facet name="header">Name</apex:facet>
            <apex:outputText value="{!account.name}"  >
        </apex:column>
   
        <apex:column >
            <apex:facet name="header">Owner</apex:facet>
            <apex:outputText value="{!account.owner.name}"  >
        </apex:column>
       
    </apex:dataTable> 
   
    </apex:pageBlock>
    </apex:form>
</apex:page>  

</pre>
  • January 10, 2014
  • Like
  • 0
Hi,
I have this error: 
execution of AfterInsert caused by: System.QueryException: Non-selective query against large object type (more than 100000 rows). Consider an indexed filter or contact salesforce.com about custom indexing. Even if a field is indexed a filter might still not be selective when: 1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times):Trigger.TerritoryAccountTeamMemberUpdate: line 62, column 1
It is showing me an error in the query that I am using in the Map.
Below is the code;

trigger TerritoryAccountTeamMemberUpdate on TerritoryAccountTeamMember__c (after insert, after update, after delete) {

     set<Id> terrMembers= new set<Id>();
    //execution of after Insert or update trigger
    if (trigger.isInsert || trigger.isupdate) {
        for (TerritoryAccountTeamMember__c territoryMembers: trigger.new) {
            System.debug('-=TerritoryMembers in the list are: ' + territoryMembers);
            terrMembers.add(territoryMembers.territory__c);
        }
    }
    //execution of after delete trigger
    else if (trigger.isDelete) {
        //Loop through the list of TerritoryAccountTeamMember__c that was deleted
        for (TerritoryAccountTeamMember__c territoryMembers: trigger.old) {
            System.debug('-=-TerritoryMembers in the list are: ' + territoryMembers);           
            terrMembers.add(territoryMembers.territory__c);
        }
    }
   
    if(terrMembers.size() >0) {
        System.debug('=== This is the territory id: ' + terrMembers);
        Map<Id, Account> newMap= new Map<Id, Account>([Select id, ownerId, Territory__c, fmr__c, territory__r.name,                                                                                                                                                         territory__r.Territory_ID__c                            
                                                                                                            from Account where territory__c =: terrMembers]);

                
            System.debug('-=TerritoryAccountTeamMemberUpdate newMap value :' + newMap);
           
            //calling the helper class AccountServices and the methods in it
            //AccountServices.OnBeforeUpdate(newMap);
            AccountServices.OnBeforeUpdate2(newMap);
            AccountServices.OnAfterUpdate(newMap);
    }

}

This trigger runs perfectly fine while I run it in my dev sandbox, but it is throwing me an error in my fullcopy sandbox. Also I ran this code snippet of Map in Developer Console, where it runs smoothly;
Map<Id, Account> newMap= new Map<Id, Account>([Select id, ownerId, Territory__c, fmr__c, territory__r.name, territory__r.Territory_ID__c                                                                                                              from Account where territory__c =: 'territory ID']);
System.debug('newMap Values are: ' + newMap);

Please let me know if you have any suggestions. 

Thanks!
justin~sfdc