• SFDCDevQA
  • NEWBIE
  • 180 Points
  • Member since 2010

  • Chatter
    Feed
  • 4
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 69
    Questions
  • 137
    Replies
I have a very simple imbedded page and controller that is working in my dev org and has worked in previous sandbox and production orgs but for some reason is not working in the current sandbox I am working in.  Is there a setting somewhere that could be essentially disabling this?  It is on the page layout, the profiles have access to the page and the class, the debug shows that the page is being called and that it is looking at the class but the page is not invoking the MarkRead method from the class and the popups are not working.  Any suggestions or ideas would be GREATLY appreciated.
Thanks,
Amanda

Simple page to product popup alert
<apex:page standardController="Opportunity" extensions="OpportunityAlertExtension">
    <apex:form >
    <apex:actionFunction action="{!markread}" name="MarkRead"/>
    </apex:form>
<script type="text/javascript">
    if({!opp.Territory2id==null && opp.MNVAlert_Shown__c==False && (opp.Kind_HSS_STEM__c==null || opp.Kind_HSS_STEM__c == 'Other')}) {
        window.alert("This Opportunity is neither HSS or STEM. Please correct the Discipline and re-save");
        updateStatus(); 
    else if({!opp.Territory2id==null && opp.MNVAlert_Shown__c==False && (opp.Kind_HSS_STEM__c!=null || opp.Kind_HSS_STEM__c != 'Other')}) {
        window.alert("No territory found for this Opportunity. Please select the correct Owner and Territory manually");
        updateStatus(); 
    }

</script>
</apex:page>

Class called by VF Page
public class OpportunityAlertExtension {

    Public Opportunity opp      {get;set;}
    public OpportunityAlertExtension(ApexPages.StandardController controller) {
        ID oppID = controller.getID();
        System.debug('=== Opportunityid: ' + oppID);

        opp = [Select Id, Name, AccountId, MNVAlert_Shown__c, Kind_HSS_STEM__c, StageName, Territory2ID
            From Opportunity
            Where Id =:oppID ];
            System.debug('=== Opportunity: ' + opp);
    }
    

    public void markread() {
        Opportunity o = this.opp;
        o.MNVAlert_Shown__c = true;
        update o;
        System.debug('=== Opportunity updated: ' + o);
    }
}

Debug log

35.0 APEX_CODE,FINEST;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;WORKFLOW,INFO 09:11:14.220 (220570453)|EXECUTION_STARTED 09:11:14.220 (220604813)|CODE_UNIT_STARTED|[EXTERNAL]|066L0000000EUbm|VF: /apex/Opportunity_Page_Alert 09:11:14.222 (222224285)|CODE_UNIT_STARTED|[EXTERNAL]|01pL0000000R08e|OpportunityAlertExtension <init> 09:11:14.222 (222241587)|SYSTEM_MODE_ENTER|true 09:11:14.222 (222852101)|HEAP_ALLOCATE|[72]|Bytes:3 09:11:14.222 (222914806)|HEAP_ALLOCATE|[77]|Bytes:152 09:11:14.222 (222936341)|HEAP_ALLOCATE|[342]|Bytes:408 09:11:14.222 (222958886)|HEAP_ALLOCATE|[355]|Bytes:408 09:11:14.222 (222980209)|HEAP_ALLOCATE|[467]|Bytes:48 09:11:14.223 (223020906)|HEAP_ALLOCATE|[139]|Bytes:6 09:11:14.223 (223054850)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:80 09:11:14.223 (223062706)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:6 09:11:14.223 (223066970)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:7 09:11:14.223 (223088249)|METHOD_ENTRY|[1]|01pL0000000R08e|OpportunityAlertExtension.OpportunityAlertExtension() 09:11:14.223 (223095331)|STATEMENT_EXECUTE|[1] 09:11:14.223 (223101201)|STATEMENT_EXECUTE|[1] 09:11:14.223 (223108960)|METHOD_EXIT|[1]|OpportunityAlertExtension 09:11:14.223 (223135430)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8 09:11:14.223 (223159106)|VARIABLE_SCOPE_BEGIN|[4]|this|OpportunityAlertExtension|true|false 09:11:14.223 (223209207)|VARIABLE_ASSIGNMENT|[4]|this|{}|0x3d842d34 09:11:14.223 (223218151)|VARIABLE_SCOPE_BEGIN|[4]|controller|ApexPages.StandardController|true|false 09:11:14.223 (223350922)|VARIABLE_ASSIGNMENT|[4]|controller|"StandardController [null]"|0x187a6d2 09:11:14.223 (223363084)|STATEMENT_EXECUTE|[1] 09:11:14.223 (223366109)|STATEMENT_EXECUTE|[3] 09:11:14.223 (223380650)|HEAP_ALLOCATE|[5]|Bytes:6 09:11:14.223 (223416932)|VARIABLE_SCOPE_BEGIN|[2]|this|System.ApexBaseClass|true|false 09:11:14.223 (223438018)|VARIABLE_ASSIGNMENT|[2]|this|{}|0x3d842d34 09:11:14.223 (223453175)|STATEMENT_EXECUTE|[4] 09:11:14.223 (223456112)|STATEMENT_EXECUTE|[5] 09:11:14.223 (223546357)|HEAP_ALLOCATE|[5]|Bytes:15 09:11:14.223 (223583293)|HEAP_ALLOCATE|[5]|Bytes:4 09:11:14.223 (223590521)|VARIABLE_SCOPE_BEGIN|[5]|oppID|Id|false|false 09:11:14.223 (223653581)|VARIABLE_ASSIGNMENT|[5]|oppID|"006L0000008OEtxIAG" 09:11:14.223 (223661826)|STATEMENT_EXECUTE|[6] 09:11:14.223 (223667103)|HEAP_ALLOCATE|[6]|Bytes:19 09:11:14.223 (223731654)|HEAP_ALLOCATE|[6]|Bytes:18 09:11:14.223 (223759313)|HEAP_ALLOCATE|[6]|Bytes:37 09:11:14.223 (223784835)|HEAP_ALLOCATE|[50]|Bytes:5 09:11:14.223 (223807767)|HEAP_ALLOCATE|[56]|Bytes:5 09:11:14.223 (223819243)|HEAP_ALLOCATE|[64]|Bytes:7 09:11:14.223 (223865757)|USER_DEBUG|[6]|DEBUG|=== Opportunityid: 006L0000008OEtxIAG 09:11:14.223 (223876033)|STATEMENT_EXECUTE|[8] 09:11:14.223 (223880912)|HEAP_ALLOCATE|[8]|Bytes:125 09:11:14.223 (223895219)|HEAP_ALLOCATE|[8]|Bytes:4 09:11:14.223 (223908515)|HEAP_ALLOCATE|[8]|Bytes:7 09:11:14.224 (224347471)|SOQL_EXECUTE_BEGIN|[8]|Aggregations:0|SELECT Id, Name, AccountId, MNVAlert_Shown__c, Kind_HSS_STEM__c, StageName, Territory2ID FROM Opportunity WHERE Id = :tmpVar1 09:11:14.229 (229042000)|SOQL_EXECUTE_END|[8]|Rows:1 09:11:14.229 (229073034)|HEAP_ALLOCATE|[8]|Bytes:8 09:11:14.229 (229093831)|HEAP_ALLOCATE|[8]|Bytes:195 09:11:14.229 (229184597)|HEAP_ALLOCATE|[8]|Bytes:8 09:11:14.229 (229195789)|HEAP_ALLOCATE|[8]|Bytes:37 09:11:14.229 (229291244)|HEAP_ALLOCATE|[8]|Bytes:28 09:11:14.229 (229357008)|VARIABLE_ASSIGNMENT|[-1]|this|{}|0x3d842d34 09:11:14.229 (229394199)|VARIABLE_ASSIGNMENT|[-1]|value|{"s":1,"v":{"Id":"006L0000008OEtxIAG","Name":"Department1: QAI_Tes (24 more) ...","AccountId":"001L000000mWIJXIA4","MNVAlert_Shown__c":false,"StageName":"Prospecting","RecordTypeId":"012L0000000DKZ8IAO"}}|0x7f306188 09:11:14.229 (229419832)|VARIABLE_ASSIGNMENT|[3]|this.opp|{"s":1,"v":{"Id":"006L0000008OEtxIAG","Name":"Department1: QAI_Tes (24 more) ...","AccountId":"001L000000mWIJXIA4","MNVAlert_Shown__c":false,"StageName":"Prospecting","RecordTypeId":"012L0000000DKZ8IAO"}}|0x3d842d34 09:11:14.229 (229433864)|STATEMENT_EXECUTE|[11] 09:11:14.229 (229439674)|HEAP_ALLOCATE|[11]|Bytes:17 09:11:14.229 (229489763)|VARIABLE_ASSIGNMENT|[-1]|this|{"opp":"0x7f306188"}|0x3d842d34 09:11:14.229 (229572569)|HEAP_ALLOCATE|[11]|Bytes:197 09:11:14.229 (229597405)|HEAP_ALLOCATE|[11]|Bytes:214 09:11:14.229 (229611763)|USER_DEBUG|[11]|DEBUG|=== Opportunity: Opportunity:{Id=006L0000008OEtxIAG, Name=Department1: QAI_Test_Account1: Spring: 2015, AccountId=001L000000mWIJXIA4, MNVAlert_Shown__c=false, StageName=Prospecting, RecordTypeId=012L0000000DKZ8IAO} 09:11:14.230 (230279368)|CODE_UNIT_FINISHED|OpportunityAlertExtension <init> 09:11:14.260 (260066812)|CODE_UNIT_STARTED|[EXTERNAL]|01pL0000000R08e|OpportunityAlertExtension get(opp) 09:11:14.260 (260093022)|SYSTEM_MODE_ENTER|true 09:11:14.260 (260115204)|CODE_UNIT_STARTED|[EXTERNAL]|01pL0000000R08e|opp 09:11:14.260 (260142455)|CODE_UNIT_FINISHED|opp 09:11:14.260 (260165264)|CODE_UNIT_FINISHED|OpportunityAlertExtension get(opp) 09:11:14.262 (262142347)|VF_SERIALIZE_VIEWSTATE_BEGIN|066L0000000EUbm 09:11:14.263 (263460613)|VF_SERIALIZE_VIEWSTATE_END 09:11:14.266 (266971105)|CUMULATIVE_LIMIT_USAGE 09:11:14.266 (266971105)|LIMIT_USAGE_FOR_NS|(default)| Number of SOQL queries: 1 out of 100 Number of query rows: 1 out of 50000 Number of SOSL queries: 0 out of 20 Number of DML statements: 0 out of 150 Number of DML rows: 0 out of 10000 Maximum CPU time: 0 out of 10000 Maximum heap size: 0 out of 6000000 Number of callouts: 0 out of 100 Number of Email Invocations: 0 out of 10 Number of future calls: 0 out of 50 Number of queueable jobs added to the queue: 0 out of 50 Number of Mobile Apex push calls: 0 out of 10 09:11:14.266 (266971105)|CUMULATIVE_LIMIT_USAGE_END 09:11:14.267 (267009070)|CODE_UNIT_FINISHED|VF: /apex/Opportunity_Page_Alert 09:11:14.268 (268270387)|EXECUTION_FINISHED
 
I am trying to figure out why this is exceeding the CPU Time Limit.  It is bulked with 200 records in the test class and works fine but updating even 50 records in real life gives me CPU Time Limit exceeded errors.  It is only telling me there is an error for the whole Class and not a specific section of the class.  Can anyone please give me some pointers on how I can pinpoint exactly what part of the class is exceeding the CPU Time Limit? I've tried doing the standard things to lower CPU usage but it just keeps going up exponentially in real time but not in the test classes.  It won't let me post the whole code here but you can see it at https://gist.github.com/e43a5f3537d48e26a3b1.git

Thanks,
Amanda
I am trying to use the contains method on a string field in my relationship query for the list below but I get Compile Error: unexpected token: 'HSS'.  To get to the field it is going from UserTerritory2Association to Territory2 to Territory2Type. (Child to Parent to Parent all standard objects) If I just say WHERE Territory2.Territory2Type.DeveloperName = 'HSS' then it works fine but I don't want to have to specify every single type.  Instead I want to say if the type MasterLabel contains certain characters then it should grab those.  Why is it not letting me use the contains method?

Thanks,
Amanda

List<userterritory2association> userTerritoryAssociations = [
                                                                            Select id, UserID, territory2Id, RoleInTerritory2, Territory2.Territory2Type.Priority, Territory2.Territory2Type.MasterLabel from userterritory2association Where Territory2.Territory2Type.MasterLabel.contains( 'HSS' )
                                                                            ];
I'm trying to populate a text field on Account with the Territory names (original territories, not Enterprise Territories or Territories2).  In order to do this you have to map through Account to Account Share to Group to Territory and then back.  I've got the mapping done I think but the navigating back is proving quite difficult, especially since my map for Account Share involves a list inside a map.  I also need the Territories that have been both mapped and Listed to show up in my field as just a string (IE Territory 1, Territory 2, Territory 3, etc).  How can I do this?  Currently line 75 is giving me an error of Incompatible key type List<AccountShare> for Map<Id,Id> at line 75 column 43.  I did the Account Shares map with a List because just having the Account ID, Group ID on the accountShare was deduplicating by the account ID and leaving me with just 1 record everytime instead of multiples.  I tried vastly simplifying line 75 to just MapofTerritories.values(); (which I don't think would bulk at all) and got the error of Illegal assignment from List<String> to String at line 75 column 12 so there's an issue there of having it list them out no matter if I get back to the correct account or not.
Thank you for your help

trigger AccountTerritories on Account (before update){
    if(Trigger.isBefore){
        Set<Id> setOfAccountIds = new Set<Id>();

        for(Account acct : Trigger.New){
            if(Trigger.isUpdate){
                if(acct.Id != null){
                    setOfAccountIds.add(acct.Id);
                }
            }
        }
 
        if(setOfAccountIds.size() > 0){

        /* Declaration of collection data types */
        Map<id,List<AccountShare>> MapOfAccountShare = new    Map<id,List<AccountShare>>();
       Map<Id, Id> mapOfGroup = new Map<Id, Id>();
       Map<Id, String> mapOfTerritories = new Map<Id, String>();


//Query in Account Share object
    /*
    Those Accounts which are assigned via Territory Assignment Rules.
You can query those Accounts by filtering RowCause = 'Territory' in AccountShare object query.
    */
    List<AccountShare> listOfAccountShare =
    [Select Id, UserOrGroupId, AccountId, RowCause from AccountShare where AccountId IN :setOfAccountIds];
    System.debug('=== contents of listOfAccountShare: ' + listOfAccountShare);
    System.debug('=== size of listOfAccountShare: ' + listOfAccountShare.size());
    List<Id> Groupids = new List<Id>();
    for(AccountShare a :listofAccountShare){
    Groupids.add(a.UserOrGroupId);
    }

    //Map of Account Share

  for(AccountShare acctShare : listOfAccountShare ){
        if (MapOfAccountShare.containsKey(acctShare.AccountID))
            {
        MapOfAccountShare.get(acctShare.AccountID). add(acctShare);
        }
        else{
        MapOfAccountShare.put(acctShare.AccountID, new  List <AccountShare> { acctShare });
        }  
        }  
    System.debug('=== all AccountShare keys in the map: ' + mapOfAccountShare.keySet());  
    System.debug('=== all AccountShare values in the map (as a List): ' + mapOfAccountShare.values());
    System.debug('=== size of mapOfAccountShare: ' + mapOfAccountShare.size());

    //Query in Group object            
    List<Group> listOfGroup = [Select Id, RelatedId from Group where Type='Territory' and Id IN :GroupIDs];
    System.debug('=== contents of listOfGroup: ' + listOfGroup);
    System.debug('=== size of listOfGroup: ' + listOfGroup.size());
//Map of Group object
    for(Group groupRecord : listOfGroup){
    mapOfGroup.put(groupRecord.Id, groupRecord.RelatedId);        
    }
    System.debug('=== all Group keys in the map: ' + mapOfGroup.keySet());  
    System.debug('=== all Group values in the map (as a List): ' + mapOfGroup.values());
    System.debug('=== size of MapOfGroup: ' + mapOfGroup.size());

    //Query in Territory object
    List<Territory> listOfTerritory = [Select Id, Name from Territory where Id IN :mapOfGroup.Values()];
    System.debug('=== contents of listOfTerritories: ' + listOfTerritory);
    System.debug('=== size of listOfTerritories: ' + listOfTerritory.size());
    //Map of Territory object
    
    for(Territory Territories : listOfTerritory){
    mapOfTerritories.put(Territories.Id, Territories.Name);
    System.debug('=== all Territories keys in the map: ' + mapOfTerritories.keySet());  
    System.debug('=== all Territories values in the map (as a List): ' + mapOfTerritories.values());  
    System.debug('=== size of MapOfTerritories: ' + mapOfTerritories.size());
    }
    for (Account updatedAccount : Trigger.new) {
    String territory = MapofTerritories.get(mapofGroup.get(mapofAccountShare.get(updatedaccount.id )));
    updatedAccount.territories__c = territory;
    }
 
}

}
}
I am trying to bulk my test class and running into issues.  I finally seem to have gotten past whatever was causing my DML error (I added a limit of 200 rows) but now it's still giving me an error on the UPDATE (not insert) saying that my demo doesn't have a demo date when they all clearly do because they inserted just fine.  What totally obvious thing am I clearly missing?
Thanks,
Amanda

    static testMethod void TestDemoSpecialisttoOppTeamSL() {
        
        //inserting a user
         Map<String,ID> profiles = new Map<String,ID>();
        List<Profile> ps = [select id, name from Profile where name =
        'Standard User' or name = 'System Administrator'];
            for(Profile p : ps){
                profiles.put(p.name, p.id);
            }

OMITTING a bunch of code here that doesn't seem to be part of the issue...this is where my bulking begins.
        
        // Insert 100 Demos
    List<Demo__c> Demos = new List<Demo__c>();
    for (Integer i = 0; i < 200; i++) {
        Demo__c demo = new Demo__c();
        demo.name = 'Test Demo' + i;
        demo.Contact__c = cont[0].id;
        demo.Opportunity__c = opp.id;
        demo.demo_date__c = Date.newInstance(2020,12,01);
        demo.Sales_Rep_Notes__c = 'Testing new demo creation';
        demos.add(demo);
    }
    insert Demos;      
        // Switch to test context
        Test.startTest();
    demos = [SELECT Id, Demo_Given_By__c FROM Demo__c limit 200];    
        //update demo to include demo specialist
        for (Demo__c demo : demos) {
          demo.Demo_Given_by__c = users[4].id;
    }
    update demos;       
 
        // check that the Opportunity Team Members were created
        List<OpportunityTeammember> newOTM = [Select otm.Id From OpportunityTeamMember otm where OpportunityID = :opp.id];
        System.assertEquals(newOTM.size(),2);
                
        // Switch back to runtime context
        Test.stopTest();       
 
    }
I'm trying to Query all of the Territories associated with an account record (old Territory not Territory2) in order to put them in a custom text field. First I am trying to do the steps of going from Account to AccountShare to Group to Territory but based on my debug it seems to be breaking from going from the list to the map on AccountShares.  The the debug list shows all the AccountShares that it should when I test update an account but then the debug on the map for Account shares only shows one AccountShare and not the correct one.  So once that map only gives one then all the rest only give one.  Can someone direct me as to what I'm doing wrong that is causing the map of the list to vary from the list itself?
Thanks

trigger AccountTerritories on Account (before update){
    if(Trigger.isBefore){
        Set<Id> setOfAccountIds = new Set<Id>();

        for(Account acct : Trigger.New){
            if(Trigger.isUpdate){
                if(acct.Id != null){
                    setOfAccountIds.add(acct.Id);
                }
            }
        }
 
        if(setOfAccountIds.size() > 0){

        /* Declaration of collection data types */
Map<Id, Id> mapOfAccountShare = new Map<Id, Id>();
       Map<Id, Id> mapOfGroup = new Map<Id, Id>();
       Map<Id, Territory> mapOfUserTerritory = new Map<Id, Territory>();


//Query in Account Share object

    List<AccountShare> listOfAccountShare =
    [Select Id, UserOrGroupId, AccountId, RowCause from AccountShare where AccountId IN :setOfAccountIds];
    System.debug('=== contents of listOfAccountShare: ' + listOfAccountShare);

//Map of Account Share
    for(AccountShare acctShare : listOfAccountShare){
    mapOfAccountShare.put(acctShare.AccountId, acctShare.UserOrGroupId);        
    }      
    System.debug('=== all AccountShare keys in the map: ' + mapOfAccountShare.keySet());  
    System.debug('=== all AccountShare values in the map (as a List): ' + mapOfAccountShare.values());

    //Query in Group object            
    List<Group> listOfGroup = [Select Id, RelatedId from Group where Type='Territory' and Id IN :mapOfAccountShare.Values()];
    System.debug('=== contents of listOfGroup: ' + listOfGroup);
//Map of Group object
    for(Group groupRecord : listOfGroup){
    mapOfGroup.put(groupRecord.Id, groupRecord.RelatedId);        
    }
    System.debug('=== all Group keys in the map: ' + mapOfGroup.keySet());  
    System.debug('=== all Group values in the map (as a List): ' + mapOfGroup.values());

    //Query in Territory object
    Map<Id, Territory> mapOfTerritories =
    new Map<Id, Territory>([select id, name, ParentTerritoryId from Territory where Id IN:mapOfGroup.Values() ]);  
    System.debug('=== all Territories keys in the map: ' + mapOfTerritories.keySet());  
    System.debug('=== all Territories values in the map (as a List): ' + mapOfTerritories.values());  


 
}

}
}

 
I'm receiving a null reference error only when uploading and strangely not always when uploading.  The error is pointing to line 110 but I'm not sure that is the actual issue because records are fine individually and sometimes they don't cause problems at all.  So maybe its getting confused when cross referencing the lists?   I can't seem to find a reason for why in the upload they are causing this null reference error but not individually.  At first I thought my qualification that it end if there were no eligible account team records was the issue but I've tried that and it worked on an individual one.  Even a small group of 20 records sometimes gets stopped on upload.  I'm concerned I may have bulked it improperly and that is what is causing the error.  Any help would be greatly appreciated, even if it is to say that I did bulk it correctly and I need to look elsewhere at another code or something that could be causing the actual problem.

Thanks so much,
Amanda

trigger ProductCopyActTeamtoOpportunity on OpportunityLineItem (after insert) {

List<OpportunityTeamMember> oppTeamMembersList = new List<OpportunityTeamMember>();

//Get Account ID from Opportunity when products are added

List<OpportunityLineItem> OLIAccountIDs = new List<OpportunityLineItem>([SELECT Opportunity.AccountId, OpportunityID, Quantity, Product2.Family FROM OpportunityLineItem WHERE Id IN: Trigger.newMap.keySet()]);
Set<Id> accountIds = new Set<Id>();
for(OpportunityLineItem oli : OLIAccountIDs){
    accountIds.add(oli.Opportunity.AccountId);
}

Map< Id , Id > OpportunityLineItemIdToAccountId = new Map< Id , Id >();
for(OpportunityLineItem oli :OLIAccountIDs)  {
    if(oli.Quantity > 0.0)   {
        OpportunityLineItemIdToAccountId.put(oli.opportunityid,  oli.opportunity.accountid );
        System.Debug(oli.quantity);
        System.Debug(oli.id);
        System.debug(oli.opportunityid);
        system.debug(oli.opportunity.accountid);
    }
}

    
//Map from Account ID to get Standard Account Team Members
Map<id, List<AccountTeamMember > > accountIdToAccountTeamMembers = new    Map<id,  List<AccountTeamMember > > ();
for(AccountTeamMember accountTeamMember : [SELECT a.UserId,a.User.Name,a.TeamMemberRole, a.Id, a.AccountId
                        FROM AccountTeamMember a
                        WHERE a.TeamMemberRole IN ('Partner', 'Partner Manager','QB', 'QB Manager') AND
                        a.AccountId in :OpportunityLineItemIdToAccountId.values() ])   {

    
        List<AccountTeamMember > accountTeamMembers = ( accountIdToAccountTeamMembers.get(accountTeamMember.Accountid) == null) ?
                                                       new  List<AccountTeamMember >() :
                                                       accountIdToAccountTeamMembers.get(accountTeamMember.Accountid);

        accountTeamMembers.add(accountTeamMember);
        accountIdToAccountTeamMembers.put(accountTeamMember.Accountid, accountTeamMembers);
        system.debug(accountIdToAccountTeamMembers.size());
         }

//Map Account ID for Hayden McNeil

Map< Id , Id > HMspecialistOpportunityIDtoAccountID = new Map< Id , Id >();
for(OpportunityLineItem oli :OLIAccountIDs)  {
    // check if any of the product families we care about are used
    if(oli.Product2.Family == 'Hayden-McNeil')   {
        HMspecialistOpportunityIDtoAccountID.put(oli.opportunityid,  oli.Opportunity.AccountId );
        System.Debug(oli.quantity);
        System.Debug(oli.Product2.Family);
        System.Debug(oli.id);
        System.debug(oli.opportunityid);
        system.debug(oli.opportunity.accountid);
    }
}

//Map from Account ID to get Specialists for HM
Map<id, List<AccountTeamMember > > HMspecialistaccountIdToAccountTeamMembers = new    Map<id,  List<AccountTeamMember > > ();
for(AccountTeamMember HMspecialistaccountTeamMember : [SELECT a.UserId,a.User.Name,a.TeamMemberRole, a.Id, a.AccountId
                        FROM AccountTeamMember a
                        WHERE a.TeamMemberRole IN ('HM Specialist','HM Specialist Manager') AND
                        a.AccountId in :HMspecialistOpportunityIDtoAccountID.values() ]) {

        List<AccountTeamMember > HMspecialistaccountTeamMembers = ( HMspecialistaccountIdToAccountTeamMembers.get(HMspecialistaccountTeamMember.Accountid) == null) ?
                                                       new  List<AccountTeamMember >() :
                                                       HMspecialistaccountIdToAccountTeamMembers.get(HMspecialistaccountTeamMember.Accountid);

        HMspecialistaccountTeamMembers.add(HMspecialistaccountTeamMember);
        HMspecialistaccountIdToAccountTeamMembers.put(HMspecialistaccountTeamMember.Accountid, HMspecialistaccountTeamMembers);
}

//Map Account ID for iClicker

Map< Id , Id > iClickerspecialistOpportunityIDtoAccountID = new Map< Id , Id >();
for(OpportunityLineItem oli :OLIAccountIDs)  {
    // check if any of the product families we care about are used
    if(oli.Product2.Family == 'i>clicker')   {
        iClickerspecialistOpportunityIDtoAccountID.put(oli.opportunityid,  oli.Opportunity.AccountId );
        System.Debug(oli.quantity);
        System.Debug(oli.Product2.Family);
        System.Debug(oli.id);
        System.debug(oli.opportunityid);
        system.debug(oli.opportunity.accountid);
    }
}

//Map from Account ID to get Specialists for iClicker
Map<id, List<AccountTeamMember > > iClickerspecialistaccountIdToAccountTeamMembers = new    Map<id,  List<AccountTeamMember > > ();
for(AccountTeamMember iClickerspecialistaccountTeamMember : [SELECT a.UserId,a.User.Name,a.TeamMemberRole, a.Id, a.AccountId
                        FROM AccountTeamMember a
                        WHERE a.TeamMemberRole IN ('Reef Specialist','Reef Specialist Manager') AND
                        a.AccountId in :iClickerspecialistOpportunityIDtoAccountID.values() ]) {

        List<AccountTeamMember > iClickerspecialistaccountTeamMembers = ( iClickerspecialistaccountIdToAccountTeamMembers.get(iClickerspecialistaccountTeamMember.Accountid) == null) ?
                                                       new  List<AccountTeamMember >() :
                                                       iClickerspecialistaccountIdToAccountTeamMembers.get(iClickerspecialistaccountTeamMember.Accountid);

        iClickerspecialistaccountTeamMembers.add(iClickerspecialistaccountTeamMember);
        iClickerspecialistaccountIdToAccountTeamMembers.put(iClickerspecialistaccountTeamMember.Accountid, iClickerspecialistaccountTeamMembers);
}
    if( accountIdToAccountTeamMembers.keySet().size()> 0 ) // if there are no eligible Account Team records, end
{

for(OpportunityLineItem oli :OLIAccountIDs) {
    if(oli.quantity > 0.0)   {
        Id accountId  = OpportunityLineItemIdToAccountId.get(oli.opportunityid);
        System.debug(accountid);
        System.Debug(oli.product2.Family);
        system.debug(accountidtoaccountteammembers.get(accountid));
        for ( AccountTeamMember accountTeamMember : accountIdToAccountTeamMembers.get(accountId) )  {
            OpportunityTeamMember opportunityTeamMember  = new OpportunityTeamMember();
            opportunityTeamMember.UserId = accountTeamMember.UserId;
            opportunityTeamMember.TeamMemberRole = accountTeamMember.TeamMemberRole;
            system.debug (accountTeamMember.TeamMemberRole);
            opportunityTeamMember.OpportunityId = oli.opportunityID;
            oppTeamMembersList.add(opportunityTeamMember);
        }
     }
     if(oli.Product2.Family == 'Hayden-McNeil')   {
        System.Debug(oli.product2.Family);
        Id HMaccountId  = HMspecialistOpportunityIDtoAccountID.get(oli.opportunityId);
        System.Debug(HMaccountId);
        for ( AccountTeamMember accountTeamMember : HMspecialistaccountIdToAccountTeamMembers.get(HMaccountId) )  {
            OpportunityTeamMember opportunityTeamMember  = new OpportunityTeamMember();
            opportunityTeamMember.UserId = accountTeamMember.UserId;
            opportunityTeamMember.TeamMemberRole = accountTeamMember.TeamMemberRole;
            system.debug (accountTeamMember.TeamMemberRole);
            opportunityTeamMember.OpportunityId = oli.opportunityID;
            oppTeamMembersList.add(opportunityTeamMember);
        }
     }
     if(oli.Product2.Family == 'i>clicker')   {
        System.Debug(oli.product2.Family);
        Id iClickeraccountId  = iClickerspecialistOpportunityIDtoAccountID.get(oli.opportunityId);
        System.Debug(iClickeraccountId);
        for ( AccountTeamMember accountTeamMember : iClickerspecialistaccountIdToAccountTeamMembers.get(iClickeraccountId) )  {
            OpportunityTeamMember opportunityTeamMember  = new OpportunityTeamMember();
            opportunityTeamMember.UserId = accountTeamMember.UserId;
            opportunityTeamMember.TeamMemberRole = accountTeamMember.TeamMemberRole;
            system.debug (accountTeamMember.TeamMemberRole);
            opportunityTeamMember.OpportunityId = oli.opportunityID;
            oppTeamMembersList.add(opportunityTeamMember);
        }
     }
}

insert oppTeamMembersList;
}
}
I'm receiving a null reference error only when uploading.  I can't seem to find a reason for why in the upload they are causing this null reference error but not individually.  At first I thought my qualification that it end if there were no eligible account team records was the issue but I've tried that and it worked on an individual one.  Even a small group of 20 records gets stopped on upload.  It will only insert them individually. I guess I must have bulked this improperly but I'm not sure where the hangup is steming from.  The error is pointing to line 110 but I'm not sure that is the actual issue because like I said the records are fine individually.  So maybe its getting confused when cross referencing the lists?  Any help would be greatly appreciated.

Thanks so much,
Amanda

trigger ProductCopyActTeamtoOpportunity on OpportunityLineItem (after insert) {

List<OpportunityTeamMember> oppTeamMembersList = new List<OpportunityTeamMember>();

//Get Account ID from Opportunity when products are added

List<OpportunityLineItem> OLIAccountIDs = new List<OpportunityLineItem>([SELECT Opportunity.AccountId, OpportunityID, Quantity, Product2.Family FROM OpportunityLineItem WHERE Id IN: Trigger.newMap.keySet()]);
Set<Id> accountIds = new Set<Id>();
for(OpportunityLineItem oli : OLIAccountIDs){
    accountIds.add(oli.Opportunity.AccountId);
}

Map< Id , Id > OpportunityLineItemIdToAccountId = new Map< Id , Id >();
for(OpportunityLineItem oli :OLIAccountIDs)  {
    if(oli.Quantity > 0.0)   {
        OpportunityLineItemIdToAccountId.put(oli.opportunityid,  oli.opportunity.accountid );
        System.Debug(oli.quantity);
        System.Debug(oli.id);
        System.debug(oli.opportunityid);
        system.debug(oli.opportunity.accountid);
    }
}

    
//Map from Account ID to get Standard Account Team Members
Map<id, List<AccountTeamMember > > accountIdToAccountTeamMembers = new    Map<id,  List<AccountTeamMember > > ();
for(AccountTeamMember accountTeamMember : [SELECT a.UserId,a.User.Name,a.TeamMemberRole, a.Id, a.AccountId
                        FROM AccountTeamMember a
                        WHERE a.TeamMemberRole IN ('Partner', 'Partner Manager','QB', 'QB Manager') AND
                        a.AccountId in :OpportunityLineItemIdToAccountId.values() ])   {

    
        List<AccountTeamMember > accountTeamMembers = ( accountIdToAccountTeamMembers.get(accountTeamMember.Accountid) == null) ?
                                                       new  List<AccountTeamMember >() :
                                                       accountIdToAccountTeamMembers.get(accountTeamMember.Accountid);

        accountTeamMembers.add(accountTeamMember);
        accountIdToAccountTeamMembers.put(accountTeamMember.Accountid, accountTeamMembers);
        system.debug(accountIdToAccountTeamMembers.size());
         }

//Map Account ID for Hayden McNeil

Map< Id , Id > HMspecialistOpportunityIDtoAccountID = new Map< Id , Id >();
for(OpportunityLineItem oli :OLIAccountIDs)  {
    // check if any of the product families we care about are used
    if(oli.Product2.Family == 'Hayden-McNeil')   {
        HMspecialistOpportunityIDtoAccountID.put(oli.opportunityid,  oli.Opportunity.AccountId );
        System.Debug(oli.quantity);
        System.Debug(oli.Product2.Family);
        System.Debug(oli.id);
        System.debug(oli.opportunityid);
        system.debug(oli.opportunity.accountid);
    }
}

//Map from Account ID to get Specialists for HM
Map<id, List<AccountTeamMember > > HMspecialistaccountIdToAccountTeamMembers = new    Map<id,  List<AccountTeamMember > > ();
for(AccountTeamMember HMspecialistaccountTeamMember : [SELECT a.UserId,a.User.Name,a.TeamMemberRole, a.Id, a.AccountId
                        FROM AccountTeamMember a
                        WHERE a.TeamMemberRole IN ('HM Specialist','HM Specialist Manager') AND
                        a.AccountId in :HMspecialistOpportunityIDtoAccountID.values() ]) {

        List<AccountTeamMember > HMspecialistaccountTeamMembers = ( HMspecialistaccountIdToAccountTeamMembers.get(HMspecialistaccountTeamMember.Accountid) == null) ?
                                                       new  List<AccountTeamMember >() :
                                                       HMspecialistaccountIdToAccountTeamMembers.get(HMspecialistaccountTeamMember.Accountid);

        HMspecialistaccountTeamMembers.add(HMspecialistaccountTeamMember);
        HMspecialistaccountIdToAccountTeamMembers.put(HMspecialistaccountTeamMember.Accountid, HMspecialistaccountTeamMembers);
}

//Map Account ID for iClicker

Map< Id , Id > iClickerspecialistOpportunityIDtoAccountID = new Map< Id , Id >();
for(OpportunityLineItem oli :OLIAccountIDs)  {
    // check if any of the product families we care about are used
    if(oli.Product2.Family == 'i>clicker')   {
        iClickerspecialistOpportunityIDtoAccountID.put(oli.opportunityid,  oli.Opportunity.AccountId );
        System.Debug(oli.quantity);
        System.Debug(oli.Product2.Family);
        System.Debug(oli.id);
        System.debug(oli.opportunityid);
        system.debug(oli.opportunity.accountid);
    }
}

//Map from Account ID to get Specialists for iClicker
Map<id, List<AccountTeamMember > > iClickerspecialistaccountIdToAccountTeamMembers = new    Map<id,  List<AccountTeamMember > > ();
for(AccountTeamMember iClickerspecialistaccountTeamMember : [SELECT a.UserId,a.User.Name,a.TeamMemberRole, a.Id, a.AccountId
                        FROM AccountTeamMember a
                        WHERE a.TeamMemberRole IN ('Reef Specialist','Reef Specialist Manager') AND
                        a.AccountId in :iClickerspecialistOpportunityIDtoAccountID.values() ]) {

        List<AccountTeamMember > iClickerspecialistaccountTeamMembers = ( iClickerspecialistaccountIdToAccountTeamMembers.get(iClickerspecialistaccountTeamMember.Accountid) == null) ?
                                                       new  List<AccountTeamMember >() :
                                                       iClickerspecialistaccountIdToAccountTeamMembers.get(iClickerspecialistaccountTeamMember.Accountid);

        iClickerspecialistaccountTeamMembers.add(iClickerspecialistaccountTeamMember);
        iClickerspecialistaccountIdToAccountTeamMembers.put(iClickerspecialistaccountTeamMember.Accountid, iClickerspecialistaccountTeamMembers);
}
    if( accountIdToAccountTeamMembers.keySet().size()> 0 ) // if there are no eligible Account Team records, end
{

for(OpportunityLineItem oli :OLIAccountIDs) {
    if(oli.quantity > 0.0)   {
        Id accountId  = OpportunityLineItemIdToAccountId.get(oli.opportunityid);
        System.debug(accountid);
        System.Debug(oli.product2.Family);
        system.debug(accountidtoaccountteammembers.get(accountid));
        for ( AccountTeamMember accountTeamMember : accountIdToAccountTeamMembers.get(accountId) )  {
            OpportunityTeamMember opportunityTeamMember  = new OpportunityTeamMember();
            opportunityTeamMember.UserId = accountTeamMember.UserId;
            opportunityTeamMember.TeamMemberRole = accountTeamMember.TeamMemberRole;
            system.debug (accountTeamMember.TeamMemberRole);
            opportunityTeamMember.OpportunityId = oli.opportunityID;
            oppTeamMembersList.add(opportunityTeamMember);
        }
     }
     if(oli.Product2.Family == 'Hayden-McNeil')   {
        System.Debug(oli.product2.Family);
        Id HMaccountId  = HMspecialistOpportunityIDtoAccountID.get(oli.opportunityId);
        System.Debug(HMaccountId);
        for ( AccountTeamMember accountTeamMember : HMspecialistaccountIdToAccountTeamMembers.get(HMaccountId) )  {
            OpportunityTeamMember opportunityTeamMember  = new OpportunityTeamMember();
            opportunityTeamMember.UserId = accountTeamMember.UserId;
            opportunityTeamMember.TeamMemberRole = accountTeamMember.TeamMemberRole;
            system.debug (accountTeamMember.TeamMemberRole);
            opportunityTeamMember.OpportunityId = oli.opportunityID;
            oppTeamMembersList.add(opportunityTeamMember);
        }
     }
     if(oli.Product2.Family == 'i>clicker')   {
        System.Debug(oli.product2.Family);
        Id iClickeraccountId  = iClickerspecialistOpportunityIDtoAccountID.get(oli.opportunityId);
        System.Debug(iClickeraccountId);
        for ( AccountTeamMember accountTeamMember : iClickerspecialistaccountIdToAccountTeamMembers.get(iClickeraccountId) )  {
            OpportunityTeamMember opportunityTeamMember  = new OpportunityTeamMember();
            opportunityTeamMember.UserId = accountTeamMember.UserId;
            opportunityTeamMember.TeamMemberRole = accountTeamMember.TeamMemberRole;
            system.debug (accountTeamMember.TeamMemberRole);
            opportunityTeamMember.OpportunityId = oli.opportunityID;
            oppTeamMembersList.add(opportunityTeamMember);
        }
     }
}

insert oppTeamMembersList;
}
}
 
So I have a class that uses a VF button which essentially works like a trigger to create a new opportunity with line items and takes the user to the new opportunities standard edit page.  So once the user sees anything after hitting the "Clone" button the opportunity and line items have all been created.  At this point if they hit cancel from the edit page it doesn't actually cancel anything - the cloned opp and it's line items are all still there.  It just takes them to the Cloned Opp's detail page.  Is there a way to use Savepoints to tell it if they hit cancel at that point in time I want it to go back to my save point?  I have a save point in my controller class but most examples use an error, which I'm not wanting to use an error.  I've also seen "On Cancel" used when a full VF page is used but in this case they are just being taken to the standard edit page of the new opportunity via
return new PageReference('/'+newOpp.id+'/e?retURL=%2F'+newOpp.id);
perhaps there is something I can add to this return new PageReference that could somehow contain the rollback?

Thanks,
Amanda
I have a custom button which uses a controller class to clone an opportunity.  I'd like it to only allow the clone if certain criteria are met but I am running into an issue that if the criteria are not met I receive an error saying
"Visualforce ErrorHelp for this Page
System.NullPointerException: Attempt to de-reference a null object
Error is in expression '{!cloneWithItems}' in component <apex:page> in page opportunity_clone: Class.OpportunityCloneWithItemsController.cloneWithItems: line 157, column 1"
that line is
return new PageReference('/'+newOpp.id+'/e?retURL=%2F'+newOpp.id);
I tried adding in
  if(newopp.id != null){
      return new PageReference('/'+newOpp.id+'/e?retURL=%2F'+newOpp.id);
        }else{
      ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, 'The Opportunity could not be cloned');
      ApexPages.addMessage(msg);
But then I get "Compile Error: Non-void method might not return a value or might have statement after a return statement."
I understand that the reason I'm getting the first error is that if my criteria are NOT met then there will be no newOpp so it will be null, but I'm not clear on why it won't allow me to add a .message or if there is a way to just change the error that users see when they've tried to use the button incorrectly.  I'd prefer they just see a standard error saying "This Opportunity Cannot be Cloned" instead of the whole VF page error that references the class.

Thanks so much,
Amanda
 
I can't believe no one out there has wanted to do this but I've searched and searched and haven't found anything similar.  Specifically when converting a lead with an opportunity we'd like it to immedietly go to the add product page for the opportunity or at least just the page for the opportunity that was just created.  It seems like there should be some way to do this.  Something must tell it that it was just at the lead page and is now at the account page even if it's an existing account.  I just can't find how.  If anyone has any ideas on this I would love to hear them.

Thanks,
Amanda
Can anyone please help me understand why this is hitting SOQL limits?  I repurposed a previously working trigger that I had to do pretty much the same thing again but with a little bit more if then statements and a couple oldmap.get statements.  The prior trigger would allow you to import opportunities and update a date field and that would make the trigger go off with no problems.  But now this one doing pretty much the same thing with a checkbox is hitting SOQL statements when I try to do the import update to a special checkbox field.  Any ideas?

Thanks so much,
Amanda

trigger CloneOpportunityRollover on Opportunity (after Update) {
    
    List <Opportunity> opportunities = [select Id, Name, Type, LeadSource, Roll_Manually__c, Textbook__c, Description, Subject__c, Term_Use__c, Opportunity_Rolled__c,
    Opportunity_Rolled_From__c, AccountID, StageName, Term__c, CloseDate, Account.Academic_Calendar__c, Account.Winter_Course_Start_Date__c, Opportunity_Type__c,
    Account.Spring_Course_Start_Date__c, Account.Summer_Course_Start_Date__c, Account.Fall_Course_Start_Date__c, (select Id, opportunity.term__c,
    opportunity.stagename, opportunity.Term_Use__c, opportunity.account.Academic_Calendar__c,unitprice, Quantity, PricebookEntryID, Description From
    OpportunityLineItems), (Select Id, Contactid, IsPrimary, Role From OpportunityContactRoles) from Opportunity where ID IN :Trigger.newMap.keySet()];
    
    
    List<Opportunity> opportunitiesToUpdate = new List<Opportunity>{};
    List<Opportunity> newOpportunities = new List<Opportunity>{};
    List<OpportunityLineItem> newOpportunityLineitems = new List<OpportunityLineItem>{};
    List<opportunitycontactrole> newOpportunityContactRoles = new List<opportunitycontactrole>{};
    Integer CurrentYear = Date.Today().Year();
    
    
    

    for(Opportunity opp : opportunities){
    Integer CloseDateMonth = Opp.CloseDate.Month();
        if (((trigger.oldMap.get(Opp.id).StageName != null && opp.StageName == 'Commitment' &&  opp.Stagename != trigger.oldMap.get(Opp.id).StageName)  || opp.Roll_Manually__c == True) && Opp.Opportunity_Rolled__c == False && (Opp.Opportunity_Type__c == 'Hayden-McNeil' ||
        Opp.Opportunity_Type__c == 'Sapling Learning' || Opp.Opportunity_Type__c == 'Late Nite Labs' || Opp.Opportunity_Type__c == 'Nature Ed' ||
        Opp.Opportunity_Type__c == 'i>clicker')) {
            Opportunity newOpp;
            
            
//          try {
            
                newOpp = opp.clone(false);
                if (Opp.Term_Use__c == 'Used Each Term') {
                                
                    if (opp.term__c == 'Fall' && opp.account.Academic_Calendar__c == 'Semester') {
                        newOpp.Term__c = 'Spring';
                        if (opp.account.Spring_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Spring_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 1, 1) ;}
                    } else if (opp.term__c == 'Winter' && (opp.account.Academic_Calendar__c == 'Quarter' || opp.account.Academic_Calendar__c == 'Trimester')) {
                        newOpp.Term__c = 'Spring';
                        if (opp.account.Spring_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Spring_Course_Start_Date__c;
                        } else if (opp.closedate.month()==1 || opp.closedate.month()==2){
                        newOpp.CloseDate = date.newInstance(opp.CloseDate.Year(), 3, 1) ;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 3, 1) ;}
                    } else if ( opp.term__c == 'Spring' && opp.account.Academic_Calendar__c == 'Semester' )  {
                        newOpp.Term__c = 'Fall';
                        if (opp.account.Fall_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Fall_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year(), 9, 1) ;}
                    } else if ( opp.term__c == 'Fall' && (opp.account.Academic_Calendar__c == 'Quarter' || opp.account.Academic_Calendar__c == 'Trimester'))  {
                        newOpp.Term__c = 'Winter';
                        if (opp.account.Winter_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Winter_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 1, 1);}
                    } else if ( opp.term__c == 'Spring' && (opp.account.Academic_Calendar__c == 'Quarter' || opp.account.Academic_Calendar__c == 'Trimester'))  {
                        newOpp.Term__c = 'Summer';
                        if (opp.account.Summer_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Summer_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year(), 5, 1);}
                    } else if (opp.term__c == 'Summer') {
                        newOpp.Term__c = 'Summer';
                        if (opp.account.Summer_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Summer_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 5, 1) ;}
                    }
                } else if (Opp.Term_Use__c == 'Single Term') {
                                
                    if ( opp.term__c == 'Spring' && opp.account.Academic_Calendar__c == 'Semester') {
                        newOpp.Term__c = 'Spring';
                        if (opp.account.Spring_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Spring_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 1, 1);}
                    } else if (opp.term__c == 'Fall' && (opp.account.Academic_Calendar__c == 'Quarter' || opp.account.Academic_Calendar__c == 'Trimester'))  {
                        newOpp.Term__c = 'Spring';
                        if (opp.account.Spring_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Spring_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 3, 1);}
                    } else if (opp.term__c == 'Fall' && opp.account.Academic_Calendar__c == 'Semester')  {
                        newOpp.Term__c = 'Fall';
                        if (opp.account.Fall_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Fall_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 9, 1);}
                    } else if (opp.term__c == 'Spring' && (opp.account.Academic_Calendar__c == 'Quarter' || opp.account.Academic_Calendar__c == 'Trimester'))  {
                        newOpp.Term__c = 'Fall';
                        if (opp.account.Fall_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Fall_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year(), 9, 1);}
                    } else if ( opp.term__c == 'Summer' && (opp.account.Academic_Calendar__c == 'Quarter' || opp.account.Academic_Calendar__c == 'Trimester'))  {
                        newOpp.Term__c = 'Summer';
                        if (opp.account.Summer_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Summer_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 5, 1);}
                    } else if (( opp.term__c == 'Winter' && (opp.account.Academic_Calendar__c == 'Quarter' || opp.account.Academic_Calendar__c == 'Trimester')) || ( opp.term__c == 'Fall' && opp.account.Academic_Calendar__c == 'Trimester'))  {
                        newOpp.Term__c = 'Summer';
                        if (opp.account.Summer_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Summer_Course_Start_Date__c;
                        } else if (opp.closedate.month()==1 || opp.closedate.month()==2){
                        newOpp.CloseDate = date.newInstance(opp.CloseDate.Year(), 5, 1) ;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 5, 1) ;}
                    } else if (opp.term__c == 'Summer' && opp.account.Academic_Calendar__c == 'Semester') {
                        newOpp.Term__c = 'Summer';
                        if (opp.account.Summer_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Summer_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 5, 1) ;}
                    }
               }
                newOpp.Type = 'Renewal';
                newOpp.Name = opp.Name;
                newOpp.StageName = 'In Closing';
                newOpp.Roll_Manually__c = False;
                newOpp.Opportunity_Rolled__c = False;
                newOpp.Opportunity_Rolled_From__c = opp.ID;
                newOpportunities.add(newOpp);
                opp.Opportunity_Rolled__c = True;
                opportunitiesToUpdate.add(opp);
                
//          } catch (Exception e){
//              //ApexPages.addMessages(e);
//              opportunitiesToUpdate = new List<Opportunity>{};
//              newOpportunities = new List<Opportunity>{};
//              newOpportunityLineitems = new List<OpportunityLineItem>{};
//              newOpportunityContactRoles = new List<opportunitycontactrole>{};
//          }
    }}
    
    // setup the save point for rollback
    Savepoint sp = Database.setSavepoint();

//  try {
    
        insert newOpportunities;
        update opportunitiesToUpdate;
        
        Integer size = newOpportunities.size();
        
        for(Integer i = 0; i < size; i++){
            
            Opportunity opp = opportunitiesToUpdate.get(i);
            Opportunity newOpp = newOpportunities.get(i);
            
            List<OpportunityLineItem> lineItems = opp.OpportunityLineItems;
            //System.debug(lineItems.size=' + 'lineItems.size());
            for (OpportunityLineItem oli : lineItems) {
                 OpportunityLineItem newoli = oli.clone(false);
                 Decimal rounddown = oli.quantity *.8;
                    Decimal roundeddown = Rounddown.setScale(0, RoundingMode.DOWN);
                    system.debug(roundeddown);
                 Decimal roundup = oli.quantity *1.2;
                    Decimal roundedup = Roundup.setScale(0, RoundingMode.UP);
                    system.debug(roundedup);
                                                 
                    if ( oli.opportunity.term__c == 'Fall' && oli.opportunity.account.Academic_Calendar__c == 'Semester' && oli.opportunity.Term_Use__c=='Used Each Term'  ) {
                        newOli.Quantity = roundeddown;
                    } else if ( oli.opportunity.term__c == 'Spring' && oli.opportunity.account.Academic_Calendar__c == 'Semester' && oli.opportunity.Term_Use__c=='Used Each Term') {
                        newOli.Quantity = roundedup;
                    }
                 newoli.OpportunityID = newOpp.id;
                 newOpportunityLineitems.add(newoli);
            }
            
            List<opportunitycontactrole> roles = opp.opportunitycontactroles;
            //System.debug("roles.size=" + roles.size());
            for (opportunitycontactrole ocr : roles) {
                 opportunitycontactrole newocr = ocr.clone(false);
                 newocr.Opportunityid = newOpp.id;
                 newOpportunityContactRoles.add(newocr);
            }
        }

        
        insert newOpportunityLineitems;
        insert newopportunitycontactroles;


//  } catch (Exception e){
//      // roll everything back in case of error
//      Database.rollback(sp);
//      //ApexPages.addMessages(e);
//  }
}
I'm trying to do a popup alert that just lets people know that a record has been created when they do a certain action.  It's kind of an FYI thing.  So I tried a VF page embedded in the Opp layout and that worked but it showed up everytime they went to the record once it met the criteria.  So then I tried adding a controller to the page that would check a box saying that the alert was shown.  The controller works and checks the box but now the popup doesn't show.  Is there any way to get BOTH of these working as one solution?

Thanks so much!
Amanda

Here's the first VF page I tried which works to show the popup:
<apex:page standardcontroller="Opportunity" rendered="{!Opportunity.stagename=='Commitment' && Opportunity.Opportunity_Rolled__c==True && Opportunity.Alert_Shown__c==False}" >
  <script type="text/javascript">
  {
  window.alert("This Opportunity has Been Rolled to the next applicable Semester");
  }
  </script>
</apex:page>

And here's the second one I tried that will check the box but not actually show the alert.

<apex:page standardController="Opportunity" action="{!markread}" extensions="CloneAlertExtension">
<script type="text/javascript">
if({!Opportunity.stagename=='Commitment' && Opportunity.Opportunity_Rolled__c==True && Opportunity.Alert_Shown__c==False}) {
    window.alert("This Opportunity has Been Rolled to the next applicable Semester");
}
</script>
</apex:page>

public with sharing class CloneAlertExtension {
    ApexPages.StandardController controller;
    public CloneAlertExtension(ApexPages.StandardController controller) {
        this.controller = controller;
    }
    public void markread() {
        Opportunity o = (Opportunity)controller.getRecord();
        o.Alert_Shown__c = true;
        update o;
    }
}
I'm trying to write the test class on this trigger and have suddenly hit the System.LimitException.  Why is this hitting SOQL limits at line 3?  My starting line essentially.  It's part of a list so shouldn't that prevent the SOQL limit?

Thanks so much,
Amanda Howell

trigger CloneOpportunityRollover on Opportunity (after Insert, after Update) {
   
    List <Opportunity> opportunities = [select Id, Name, Type, LeadSource, Course_Type__c, Opportunity_Rolled__c, Opportunity_Rolled_From__c, AccountID, New_Subject__c, StageName, Term__c, CloseDate, Account.Academic_Term__c, Account.Winter_Course_Start_Date__c, Account.Spring_Course_Start_Date__c, Account.Summer_Course_Start_Date__c, Account.Fall_Course_Start_Date__c, (select Id, opportunity.term__c, opportunity.stagename, opportunity.course_type__c, opportunity.account.Academic_Term__c,unitprice, Quantity, PricebookEntryID, Description From OpportunityLineItems), (Select Id, Contactid, IsPrimary, Role From OpportunityContactRoles) from Opportunity where ID IN :Trigger.newMap.keySet()];
   
   
    List<Opportunity> opportunitiesToUpdate = new List<Opportunity>{};
    List<Opportunity> newOpportunities = new List<Opportunity>{};
    List<OpportunityLineItem> newOpportunityLineitems = new List<OpportunityLineItem>{};
    List<opportunitycontactrole> newOpportunityContactRoles = new List<opportunitycontactrole>{};


    for(Opportunity opp : opportunities){

        if (opp.StageName == 'Commitment' && Opp.Opportunity_Rolled__c == False) {
            Opportunity newOpp;
           
//          try {
           
                newOpp = opp.clone(false);
                if (Opp.StageName == 'Commitment' && Opp.Opportunity_Rolled__c == False && Opp.Course_Type__c == 'Standard') {
                               
                    if ( (opp.term__c == 'Fall' && (opp.account.Academic_Term__c == 'Semester' || opp.account.Academic_Term__c == 'Trimester' )) || (opp.term__c == 'Winter' && opp.account.Academic_Term__c == 'Quarter')) {
                        newOpp.Term__c = 'Spring';
                        newOpp.CloseDate = opp.account.Spring_Course_Start_Date__c;
                        newOpp.Name = opp.Name + ' Spring ' + opp.account.Spring_Course_Start_Date__c.year();
                    } else if ( (opp.term__c == 'Spring' && opp.account.Academic_Term__c == 'Semester') || (opp.term__c == 'Summer' && (opp.account.Academic_Term__c == 'Quarter' || opp.account.Academic_Term__c == 'Trimester')) )  {
                        newOpp.Term__c = 'Fall';
                        newOpp.CloseDate = opp.account.Fall_Course_Start_Date__c;
                        newOpp.Name = opp.Name + ' Fall ' + opp.account.Fall_Course_Start_Date__c.year();
                    } else if ( opp.term__c == 'Fall' && opp.account.Academic_Term__c == 'Quarter')  {
                        newOpp.Term__c = 'Winter';
                        newOpp.CloseDate = opp.account.Winter_Course_Start_Date__c;
                        newOpp.Name = opp.Name + ' Winter ' + opp.account.Winter_Course_Start_Date__c.year();
                    } else if ( opp.term__c == 'Spring' && (opp.account.Academic_Term__c == 'Quarter' || opp.account.Academic_Term__c == 'Trimester'))  {
                        newOpp.Term__c = 'Summer';
                        newOpp.CloseDate = opp.account.Summer_Course_Start_Date__c;
                        newOpp.Name = opp.Name + ' Summer ' + opp.account.Summer_Course_Start_Date__c.year();
                    }
                } else if (Opp.StageName == 'Commitment' && Opp.Opportunity_Rolled__c == False && Opp.Course_Type__c == 'Single Semester') {
                               
                    if ( (opp.term__c == 'Spring' && opp.account.Academic_Term__c == 'Semester') || ( opp.term__c == 'Summer' && opp.account.Academic_Term__c == 'Trimester') || (opp.term__c == 'Fall' && opp.account.Academic_Term__c == 'Quarter') ) {
                        newOpp.Term__c = 'Spring';
                        newOpp.CloseDate = opp.account.Spring_Course_Start_Date__c;
                        newOpp.Name = opp.Name + ' Spring ' + opp.account.Spring_Course_Start_Date__c.year();
                    } else if ( (opp.term__c == 'Fall' && opp.account.Academic_Term__c == 'Semester') || (opp.term__c == 'Spring' && (opp.account.Academic_Term__c == 'Quarter' || opp.account.Academic_Term__c == 'Trimester'))  )  {
                        newOpp.Term__c = 'Fall';
                        newOpp.CloseDate = opp.account.Fall_Course_Start_Date__c;
                        newOpp.Name = opp.Name + ' Fall ' + opp.account.Fall_Course_Start_Date__c.year();
                    } else if ( opp.term__c == 'Summer' && opp.account.Academic_Term__c == 'Quarter')  {
                        newOpp.Term__c = 'Winter';
                        newOpp.CloseDate = opp.account.Winter_Course_Start_Date__c;
                        newOpp.Name = opp.Name + ' Winter ' + opp.account.Winter_Course_Start_Date__c.year();
                    } else if (( opp.term__c == 'Winter' && opp.account.Academic_Term__c == 'Quarter') || ( opp.term__c == 'Fall' && opp.account.Academic_Term__c == 'Trimester'))  {
                        newOpp.Term__c = 'Summer';
                        newOpp.CloseDate = opp.account.Summer_Course_Start_Date__c;
                        newOpp.Name = opp.Name + ' Summer ' + opp.account.Summer_Course_Start_Date__c.year();
                    }
               }
                newOpp.Type = 'Renewal';
                newOpp.StageName = 'Prospecting';
                newOpp.Opportunity_Rolled__c = False;
                newOpp.Opportunity_Rolled_From__c = opp.ID;
                newOpportunities.add(newOpp);
                opp.Opportunity_Rolled__c = True;
                opportunitiesToUpdate.add(opp);
               
//          } catch (Exception e){
//              //ApexPages.addMessages(e);
//              opportunitiesToUpdate = new List<Opportunity>{};
//              newOpportunities = new List<Opportunity>{};
//              newOpportunityLineitems = new List<OpportunityLineItem>{};
//              newOpportunityContactRoles = new List<opportunitycontactrole>{};
//          }
    }}
   
    // setup the save point for rollback
    Savepoint sp = Database.setSavepoint();

//  try {
   
        insert newOpportunities;
        update opportunitiesToUpdate;
       
        Integer size = newOpportunities.size();
       
        for(Integer i = 0; i < size; i++){
           
            Opportunity opp = opportunitiesToUpdate.get(i);
            Opportunity newOpp = newOpportunities.get(i);
           
            List<OpportunityLineItem> lineItems = opp.OpportunityLineItems;
            //System.debug(lineItems.size=' + 'lineItems.size());
            for (OpportunityLineItem oli : lineItems) {
                 OpportunityLineItem newoli = oli.clone(false);
                 Decimal rounddown = oli.quantity *.8;
                    Decimal roundeddown = Rounddown.setScale(0, RoundingMode.DOWN);
                    system.debug(roundeddown);
                 Decimal roundup = oli.quantity *1.2;
                    Decimal roundedup = Roundup.setScale(0, RoundingMode.UP);
                    system.debug(roundedup);
                                                
                    if ( oli.opportunity.term__c == 'Fall' && oli.opportunity.account.Academic_Term__c == 'Semester' && oli.opportunity.course_type__c=='Standard' ) {
                        newOli.Quantity = roundeddown;
                    } else if ( oli.opportunity.term__c == 'Spring' && oli.opportunity.account.Academic_Term__c == 'Semester' && oli.opportunity.course_type__c=='Standard' )  {
                        newOli.Quantity = roundedup;
                    } else if ( oli.opportunity.term__c == 'Fall' && oli.opportunity.account.Academic_Term__c == 'Quarter' && oli.opportunity.course_type__c=='Standard' )  {
                        newOli.Quantity = roundeddown;
                    } else if ( oli.opportunity.term__c == 'Winter' && oli.opportunity.account.Academic_Term__c == 'Quarter' && oli.opportunity.course_type__c=='Standard' )  {
                        newOli.Quantity = roundeddown;
                    } else if ( oli.opportunity.term__c == 'Spring' && oli.opportunity.account.Academic_Term__c == 'Quarter' && oli.opportunity.course_type__c=='Standard' )  {
                        newOli.Quantity = roundeddown;
                    } else if ( oli.opportunity.term__c == 'Summer' && oli.opportunity.account.Academic_Term__c == 'Quarter' && oli.opportunity.course_type__c=='Standard' )  {
                        newOli.Quantity = roundedup;
                    } else if ( oli.opportunity.term__c == 'Fall' && oli.opportunity.account.Academic_Term__c == 'Trimester' && oli.opportunity.course_type__c=='Standard' )  {
                        newOli.Quantity = roundeddown;
                    } else if ( oli.opportunity.term__c == 'Spring' && oli.opportunity.account.Academic_Term__c == 'Trimester' && oli.opportunity.course_type__c=='Standard' )  {
                        newOli.Quantity = roundeddown;
                    } else if ( oli.opportunity.term__c == 'Summer' && oli.opportunity.account.Academic_Term__c == 'Trimester' && oli.opportunity.course_type__c=='Standard' )  {
                        newOli.Quantity = roundedup;
                    }
                 newoli.OpportunityID = newOpp.id;
                 newOpportunityLineitems.add(newoli);
            }
           
            List<opportunitycontactrole> roles = opp.opportunitycontactroles;
            //System.debug("roles.size=" + roles.size());
            for (opportunitycontactrole ocr : roles) {
                 opportunitycontactrole newocr = ocr.clone(false);
                 newocr.Opportunityid = newOpp.id;
                 newOpportunityContactRoles.add(newocr);
            }
        }

       
        insert newOpportunityLineitems;
        insert newopportunitycontactroles;


//  } catch (Exception e){
//      // roll everything back in case of error
//      Database.rollback(sp);
//      //ApexPages.addMessages(e);
//  }
}
I'm hitting the error that Initial term of field expression must be a concrete SObject: LIST<UserTerritory> at line 8 column 79 in my Test class.  I'm trying to call the list but apparently I'm doing something wrong.  Can someone please help me get the Territory ID out of the list of TerritoryUsers?

Thanks so much,
Amanda

@IsTest(SeeAllData=true)
public class TestOpportunityTerritory {

  static testMethod void testOpportunityTerritory() {
    user u = [select id from User where name = 'Will Culbertson'];
   
    List <UserTerritory> ut = [Select ut.UserId, ut.TerritoryId From UserTerritory ut Where ut.userId =:u.Id];
    List <Territory> t = [select t.id, t.name from Territory t where t.id IN :ut.territoryid];
    Account a = new Account(Name='Test Account');
        insert a;    
       
        test.startTest();
        System.RunAs(u){
       
        //Perform the dml action on which trigger gets fired , like insert, update ,delete , undelete, in your case you have to update the opportunity record that you created in above 
       Opportunity o = new Opportunity(Name='Test Opportunity',closedate=system.today(), stagename='Prospecting', AccountID=a.id, ownerid=u.id);
        insert o; 
       
        test.stopTest();
       
        for(Opportunity opp:[SELECT Territoryid FROM Opportunity
            WHERE CreatedDate = TODAY
            and CreatedById = :u.id])
       
       
        System.assertEquals(ut.TerritoryID, opp.territoryid);
}
}      
}
Not sure if this is a VF issue or Apex Code issue but I'm trying to create a table where the first two rows are opps related to the account and the next row(s) are for creating new opps.  I originally just had the table creating new opps and it worked fine but now we want to see a few existing ones as well to prevent duplicates.  So it must be something to do with my existing opps list...I just can't figure it out.  The controller saves fine but the VF page says Error: Unknown property 'VisualforceArrayList.CloseDate'.  If I remove closedate from the vf page it just gives the same error with the next field.  Somebody please help me figure this out.

Controller:
public class ForecastOpportunitiesController
{
public Account theAcc {get;set;}
public List<ForecastOpportunitiesWrapper> wrappers {get; set;}
public Opportunity[] existingopps {get;set;} { existingopps = new List<Opportunity>(); }
Public string accrecordId {get;set;}
public static Integer toDelIdent {get; set;}
public static Integer addCount {get; set;}

private Integer nextIdent=1;

public ForecastOpportunitiesController(ApexPages.StandardsetController controller)

{
  accrecordid = ApexPages.CurrentPage().getparameters().get('id');

  // Query current opportunities
  existingopps = [
            select Id, Accountid, Name, Stagename, CloseDate
            from Opportunity
            where Accountid = :accrecordid order by CloseDate DESC Limit 2
        ];
      
  wrappers=new List<ForecastOpportunitiesWrapper>();
  for (Integer idx=0; idx<3; idx++)
  {
   wrappers.add(new ForecastOpportunitiesWrapper(nextIdent++));
  }
}

public void delWrapper()
{
  Integer toDelPos=-1;
  for (Integer idx=0; idx<wrappers.size(); idx++)
  {
   if (wrappers[idx].ident==toDelIdent)
   {
    toDelPos=idx;
   }
  }
 
  if (-1!=toDelPos)
  {
   wrappers.remove(toDelPos);
  }
}

public void addRows()
{
  for (Integer idx=0; idx<addCount; idx++)
  {
   wrappers.add(new ForecastOpportunitiesWrapper(nextIdent++));
  }
}

public PageReference save()
{
  List<Opportunity> opps=new List<Opportunity>();
  for (ForecastOpportunitiesWrapper wrap : wrappers)
  {
   opps.add(wrap.opp);
  }
 
  insert opps;
 
  return new PageReference('/' + ApexPages.currentPage().getParameters().get('Id'));
}

public PageReference onCancel(){

        // If user hits cancel we commit no changes and return them to the Account 
        return new PageReference('/' + ApexPages.currentPage().getParameters().get('Id'));
    }

public class ForecastOpportunitiesWrapper
{
  Public string recordId {get;set;}
  public Opportunity opp {get; private set;}
  public Integer ident {get; private set;}
 
  public ForecastOpportunitiesWrapper(Integer inIdent)
  {
   recordid = ApexPages.CurrentPage().getparameters().get('id');
   ident=inIdent;
   opp=new Opportunity(name='Forecast' + ident, Accountid=recordid, stagename='Forecast');
  }
}
}

VF Page:
<apex:page standardController="Opportunity"  recordSetVar="opps" extensions="ForecastOpportunitiesController" tabstyle="Opportunity">
<apex:form >
<apex:pageBlock title="Bulk Opportunity Create">
      <apex:pageBlockTable value="{!existingopps}" var="opps" id="wtable">
         <apex:column headerValue="Close Date">
            <apex:inputField value="{!opps.CloseDate}"/>
         </apex:column>
         <apex:column headerValue="Name">
            <apex:outputtext value="{!opps.Name}"/>
         </apex:column>
         <apex:column headerValue="Quantity">
            <apex:inputField value="{!opps.TotalOpportunityQuantity}" required="true"/>
         </apex:column>
         <apex:column headerValue="Stage">
            <apex:outputtext value="{!opps.StageName}"/>
         </apex:column>
      </apex:pageBlockTable>
   </apex:pageBlock>
   <apex:pageBlock title="Bulk Opportunity Create">
      <apex:pageBlockTable value="{!wrappers}" var="wrapper" id="wtable">
    <!--       <apex:column headerValue="Ident">-->
          <!--    <apex:outputText value="{!wrapper.ident}"/>-->
<!--           </apex:column>-->
         <apex:column headerValue="Close Date">
            <apex:inputField value="{!wrapper.opp.CloseDate}"/>
         </apex:column>
         <apex:column headerValue="Name">
            <apex:outputtext value="{!wrapper.opp.Name}"/>
         </apex:column>
         <apex:column headerValue="Quantity">
            <apex:inputField value="{!wrapper.opp.TotalOpportunityQuantity}" required="true"/>
         </apex:column>
         <apex:column headerValue="Stage">
            <apex:outputtext value="{!wrapper.opp.StageName}"/>
         </apex:column>
   <!--      <apex:column headerValue="Account"> -->
   <!--           <apex:outputtext value="{!wrapper.opp.Accountid}"/> -->
         <!--  </apex:column> -->
<!--          <apex:column headerValue="Action">-->
       <!--       <apex:commandButton value="Delete" action="{!delWrapper}" rerender="wtable">-->
             <!--    <apex:param name="toDelIdent" value="{!wrapper.ident}" assignTo="{!toDelIdent}"/>-->
<!--              </apex:commandButton>-->
      <!--     </apex:column>-->
      </apex:pageBlockTable>
    <apex:commandButton value="Add Row" action="{!addRows}" rerender="wtable">
      <apex:param name="addCount" value="1" assignTo="{!addCount}"/>
      </apex:commandButton>
      <apex:commandButton value="Save" action="{!save}"/>
       <apex:commandButton action="{!onCancel}" value="Cancel" immediate="true"/>
   </apex:pageBlock>
</apex:form>
</apex:page>

Wrapper:
public class ForecastOpportunitiesWrapper
{

Public string recordId {get;set;}
public Opportunity opp {get; private set;}
public Integer ident {get; private set;}

public ForecastOpportunitiesWrapper(Integer inIdent)

{
  recordid = ApexPages.CurrentPage().getparameters().get('id');
  ident=inIdent;
  opp=new Opportunity(name='Forecast' + ident, accountid=recordid, stagename='Forecast');

 
}
}
I'm trying to create a table where the first two rows are opps related to the account and the next row(s) are for creating new opps.  I originally just had the table creating new opps and it worked fine but now we want to see a few existing ones as well to prevent duplicates.  So it must be something to do with my existing opps list...I just can't figure it out.  The controller saves fine but the VF page says Error: Unknown property 'VisualforceArrayList.CloseDate'.  If I remove closedate from the vf page it just gives the same error with the next field.  Somebody please help me figure this out.

Controller:
public class ForecastOpportunitiesController
{
public Account theAcc {get;set;}
public List<ForecastOpportunitiesWrapper> wrappers {get; set;}
public Opportunity[] existingopps {get;set;} { existingopps = new List<Opportunity>(); }
Public string accrecordId {get;set;}
public static Integer toDelIdent {get; set;}
public static Integer addCount {get; set;}

private Integer nextIdent=1;
 
public ForecastOpportunitiesController(ApexPages.StandardsetController controller)

{
  accrecordid = ApexPages.CurrentPage().getparameters().get('id');
 
  // Query current opportunities
  existingopps = [
            select Id, Accountid, Name, Stagename, CloseDate
            from Opportunity
            where Accountid = :accrecordid order by CloseDate DESC Limit 2
        ];
       
  wrappers=new List<ForecastOpportunitiesWrapper>();
  for (Integer idx=0; idx<3; idx++)
  {
   wrappers.add(new ForecastOpportunitiesWrapper(nextIdent++));
  }
}
 
public void delWrapper()
{
  Integer toDelPos=-1;
  for (Integer idx=0; idx<wrappers.size(); idx++)
  {
   if (wrappers[idx].ident==toDelIdent)
   {
    toDelPos=idx;
   }
  }
  
  if (-1!=toDelPos)
  {
   wrappers.remove(toDelPos);
  }
}
 
public void addRows()
{
  for (Integer idx=0; idx<addCount; idx++)
  {
   wrappers.add(new ForecastOpportunitiesWrapper(nextIdent++));
  }
}
 
public PageReference save()
{
  List<Opportunity> opps=new List<Opportunity>();
  for (ForecastOpportunitiesWrapper wrap : wrappers)
  {
   opps.add(wrap.opp);
  }
  
  insert opps;
  
  return new PageReference('/' + ApexPages.currentPage().getParameters().get('Id'));
}

public PageReference onCancel(){

        // If user hits cancel we commit no changes and return them to the Account  
        return new PageReference('/' + ApexPages.currentPage().getParameters().get('Id'));
    }
 
public class ForecastOpportunitiesWrapper
{
  Public string recordId {get;set;}
  public Opportunity opp {get; private set;}
  public Integer ident {get; private set;}
  
  public ForecastOpportunitiesWrapper(Integer inIdent)
  {
   recordid = ApexPages.CurrentPage().getparameters().get('id');
   ident=inIdent;
   opp=new Opportunity(name='Forecast' + ident, Accountid=recordid, stagename='Forecast');
  }
}
}

VF Page:
<apex:page standardController="Opportunity"  recordSetVar="opps" extensions="ForecastOpportunitiesController" tabstyle="Opportunity">
<apex:form >
<apex:pageBlock title="Bulk Opportunity Create">
      <apex:pageBlockTable value="{!existingopps}" var="opps" id="wtable">
         <apex:column headerValue="Close Date">
            <apex:inputField value="{!opps.CloseDate}"/>
         </apex:column>
         <apex:column headerValue="Name">
            <apex:outputtext value="{!opps.Name}"/>
         </apex:column>
         <apex:column headerValue="Quantity">
            <apex:inputField value="{!opps.TotalOpportunityQuantity}" required="true"/>
         </apex:column>
         <apex:column headerValue="Stage">
            <apex:outputtext value="{!opps.StageName}"/>
         </apex:column>
      </apex:pageBlockTable>
   </apex:pageBlock>
   <apex:pageBlock title="Bulk Opportunity Create">
      <apex:pageBlockTable value="{!wrappers}" var="wrapper" id="wtable">
    <!--       <apex:column headerValue="Ident">-->
          <!--    <apex:outputText value="{!wrapper.ident}"/>-->
<!--           </apex:column>-->
         <apex:column headerValue="Close Date">
            <apex:inputField value="{!wrapper.opp.CloseDate}"/>
         </apex:column>
         <apex:column headerValue="Name">
            <apex:outputtext value="{!wrapper.opp.Name}"/>
         </apex:column>
         <apex:column headerValue="Quantity">
            <apex:inputField value="{!wrapper.opp.TotalOpportunityQuantity}" required="true"/>
         </apex:column>
         <apex:column headerValue="Stage">
            <apex:outputtext value="{!wrapper.opp.StageName}"/>
         </apex:column>
   <!--      <apex:column headerValue="Account"> -->
   <!--           <apex:outputtext value="{!wrapper.opp.Accountid}"/> -->
         <!--  </apex:column> -->
<!--          <apex:column headerValue="Action">-->
       <!--       <apex:commandButton value="Delete" action="{!delWrapper}" rerender="wtable">-->
             <!--    <apex:param name="toDelIdent" value="{!wrapper.ident}" assignTo="{!toDelIdent}"/>-->
<!--              </apex:commandButton>-->
      <!--     </apex:column>-->
      </apex:pageBlockTable>
    <apex:commandButton value="Add Row" action="{!addRows}" rerender="wtable">
      <apex:param name="addCount" value="1" assignTo="{!addCount}"/>
      </apex:commandButton>
      <apex:commandButton value="Save" action="{!save}"/>
       <apex:commandButton action="{!onCancel}" value="Cancel" immediate="true"/>
   </apex:pageBlock>
</apex:form>
</apex:page>

Wrapper:
public class ForecastOpportunitiesWrapper
{

Public string recordId {get;set;}
public Opportunity opp {get; private set;}
public Integer ident {get; private set;}
 
public ForecastOpportunitiesWrapper(Integer inIdent)

{
  recordid = ApexPages.CurrentPage().getparameters().get('id');
  ident=inIdent;
  opp=new Opportunity(name='Forecast' + ident, accountid=recordid, stagename='Forecast');
 
  
}
}

I have a Class that is working perfectly in real life (as in be a user and go through the steps and everything works fine) but my test class keeps failing because somehow it is getting more than the one line that it should be for Chosen Contacts at the beginning.  It's actually getting more than 2 chosen contacts which is more contacts than even exist so the whole thing doesn't make sense. I can't figure out why.   If someone could please take a peak and see what could be causing this issue that would be wonderful.  I've been spinning for over a week.  I have another class and test class that is almost exactly the same and it works just fine but this one is doing strange things for some reason I can't figure out.  I know a user in real life has no problems but the test is somehow creating indefinite starting records or something.

 

Thanks,

Amanda

 

Class

public with sharing class QuoteContactEntryExtension {

    public Quote theQuote {get;set;} { theQuote = new Quote(); }
    public String searchString {get;set;}
    public Quote_Contact__c[] chosencontacts {get;set;} { chosencontacts = new List<Quote_Contact__c>(); }
    public OpportunityContactRole[] availablecontacts {get;set;} { availableContacts = new List<OpportunityContactRole>(); }
    public Opportunity theOpp {get;set;} { theOpp = new Opportunity();}
    
    public String toSelect {get; set;}
    public String toUnselect {get; set;}
    public Decimal Total {get;set;}
    
    public Boolean overLimit {get;set;}
    
    private Quote_Contact__c[] forDeletion = new Quote_Contact__c[]{};


    public QuoteContactEntryExtension(ApexPages.StandardsetController controller) {

        Id QuoteID = ApexPages.currentPage().getParameters().get('id');

        // Get information about the Quote being worked on
        theQuote = [select Id, OpportunityID, Opportunity.Name from Quote where Id = :QuoteID limit 1];
       
        
        // If demo contacts were previously selected need to put them in the "selected contacts" section to start with
        chosencontacts = [
            select Id, Contact__c, Adoption_Agreement__c
            from Quote_Contact__c
            where Adoption_Agreement__c = :QuoteID
        ];
        
        theopp = thequote.opportunity;

        updateAvailableList();

    }
    
    // this is the 'action' method on the page
    public PageReference OpportunityCheck(){
        //if there is only one Opportunity we go with it and save the opp
            if(theQuote.OpportunityId != theopp.id){
                try{
                    theQuote.OpportunityId = theopp.id;
                    update(theQuote);
                }
                catch(Exception e){
                    ApexPages.addMessages(e);
                }
            }
            
            return null;
    
    }
       
    
    public void updateAvailableList() {
        
        // We dynamically build a query string and exclude items already in the shopping cart
        String qString = 'select Id, ContactId, OpportunityId from OpportunityContactRole where OpportunityId = \'' + theOpp.Id + '\'';
                
        // note that we are looking for the search string entered by the user in the First Name OR Last Name
        // modify this to search other fields if desired
        if(searchString!=null){
            qString+= ' and (OpportunityContactRole.Contact.FirstName like \'%' + searchString + '%\' or OpportunityContactRole.Contact.LastName like \'%' + searchString + '%\')';
        }
        
        Set<Id> selectedEntries = new Set<Id>();
        for(Quote_Contact__c d:chosencontacts){
            selectedEntries.add(d.contact__c);
        }
        
        if(selectedEntries.size()>0){
            qString += ' and ContactId not in :selectedEntries';
/*
            String tempFilter = ' and Id not in (';
            for(Id i : selectedEntries){
                tempFilter+= '\'' + (String)i + '\',';
            }
            String extraFilter = tempFilter.substring(0,tempFilter.length()-1);
            extraFilter+= ')';
            
            qString+= extraFilter;*/
        }
        
        qString+= ' order by OpportunityContactRole.Contact.Name';
        qString+= ' limit 101';
        
        system.debug('qString:' +qString);        
        availablecontacts = database.query(qString);
        
        // We only display up to 100 results... if there are more than we let the user know (see vf page)
        if(availablecontacts.size()==101){
            availablecontacts.remove(100);
            overLimit = true;
        }
        else{
            overLimit=false;
        }
    }
    
    public void addTochosencontacts(){
    
        // This function runs when a user hits "select" button next to a contact
    
        for(opportunitycontactrole d : availablecontacts){
            if((String)d.Id==toSelect){
                chosencontacts.add(new Quote_Contact__c(Adoption_Agreement__c=theQuote.Id, contact__c=d.contactid));
                break;
            }
        }
        
        updateAvailableList();  
    }
    

    public PageReference removeFromchosencontacts(){
    
        // This function runs when a user hits "remove" on an item in the "Chosen Contacts" section
    
        Integer count = 0;
    
        for(Quote_Contact__c d : chosencontacts){
            if((String)d.contact__c==toUnselect){
            
                if(d.Id!=null)
                    forDeletion.add(d);
            
                chosencontacts.remove(count);
                break;
            }
            count++;
        }
        
        updateAvailableList();
        
        return null;
    }

    public PageReference onSave(){
    
        // If previously selected contacts are now removed, we need to delete them
        if(forDeletion.size()>0)
            delete(forDeletion);
    
        // Previously selected contacts may have new information, so we use upsert here
 try{
      if (chosencontacts.size() > 0)        
          upsert(chosencontacts);
       }
        catch(Exception e){
            ApexPages.addMessages(e);
            return null;
        }
             
        // After save return the user to the Quote
        return new PageReference('/' + ApexPages.currentPage().getParameters().get('Id'));
    }
    
    public PageReference onCancel(){
 
        // If user hits cancel we commit no changes and return them to the Quote   
        return new PageReference('/' + ApexPages.currentPage().getParameters().get('Id'));
    }
    
 
}

 

 

 

Test Class

@istest
private class TestQuoteContactEntryExtension{

static testMethod void theTests(){

{

//Create Test Data

Account a=new Account(Name='Test Account');
    insert a;
Contact c = new Contact(FirstName='John',LastName='Doe', AccountID=a.id);
    insert c;
Contact c2 = new Contact(FirstName='Jane',Lastname='Doe',AccountID=a.id);
    insert c2;
Opportunity o = new Opportunity(Name='Test Opportunity',Academic_Term__c='Spring',closedate=system.today(), stagename='Confirmed Teaching/Class Schedule',Probability=0.05, accountID=a.id);
    insert o;      
OpportunityContactRole ocr = new OpportunityContactRole (Opportunityid = o.id, Contactid=c.id, role='Decision Maker', isPrimary=True) ;     
    insert ocr;  
OpportunityContactRole ocr2 = new OpportunityContactRole (Opportunityid = o.id, Contactid=c2.id, role='Decision Maker', isPrimary=False) ;     
    insert ocr2;  
Quote q = new Quote (Name='Test Demo', Opportunityid=o.id);
    insert q;
Quote_Contact__c qcc = new Quote_Contact__c (Adoption_Agreement__c=q.id, contact__c=c.id);
    insert qcc;

     
        ////////////////////////////////////////
        //  test QuoteContactEntry
        ////////////////////////////////////////
        
// load the page       
        PageReference pageRef = Page.Quote_Contact_Entry;
        pageRef.getParameters().put('Id',qcc.Adoption_Agreement__c);
        Test.setCurrentPageReference(pageRef);
        
 List<Quote> quotes = new List<quote>();
    quotes.add( [ Select Id, Opportunityid From Quote Where Id = : qcc.Adoption_Agreement__c ] );       
        
        QuoteContactEntryExtension qCEE = new QuoteContactEntryExtension(new ApexPages.StandardSetController( quotes ));
        

        // we know that there is at least one line item, so we confirm
        Integer startCount = qCEE.chosencontacts.size();
        system.assert(startCount>0);

        //test search functionality without finding anything
        qCEE.searchString = 'michaelforce is a hip cat';
        qCEE.updateAvailableList();
        system.assert(qCEE.availablecontacts.size()==0);
        
        //test remove from shopping cart
        qCEE.toUnselect = qcc.contact__c;
        qCEE.removeFromchosencontacts();
        system.assert(qCEE.chosencontacts.size()==startCount-1);
        
        //test save and reload extension
        qCEE.onSave();
        qCEE = new QuoteContactEntryExtension(new ApexPages.StandardSetController(quotes));
        system.assert(qCEE.chosencontacts.size()==startCount-1);
        
        // test search again, this time we will find something
        qCEE.searchString = qcc.Contact__r.FirstName;
        qCEE.updateAvailableList();
        system.assert(qCEE.availablecontacts.size()>0);       

        // test add to Shopping Cart function
       qCEE.toSelect = qCEE.availablecontacts[0].Id;
       qCEE.addTochosencontacts();
       system.assert(qCEE.chosencontacts.size()==startCount);
                
        // test save method
        
        qCEE.onSave();
        
        // query line items to confirm that the save worked
        Quote_Contact__c[] qcc2 = [select Id from Quote_Contact__c where Adoption_Agreement__c = :qcc.Adoption_Agreement__c];
       system.assert(qcc2.size()==startCount);
        
        // test on new quote to make sure redirect is happening
        Quote newQuote = new Quote(Name='New Quote2', Opportunityid= o.id);
        insert(newQuote);
        qCEE = new QuoteContactEntryExtension(new ApexPages.StandardSetController(quotes));
        
        // final quick check of cancel button
        System.assert(qCEE.onCancel()!=null);
        
        
        ////////////////////////////////////////
        //  test redirect page
        ////////////////////////////////////////
        
        // load the page
        pageRef = Page.QuoteContactRedirect;
        pageRef.getParameters().put('Id',qcc2[0].Id);
        Test.setCurrentPageReference(pageRef);

        // load the extension and confirm that redirect function returns something
        QuoteContactRedirectExtension qcrE = new QuoteContactRedirectExtension(new ApexPages.StandardController(qcc2[0]));
        System.assert(qcrE.redirect()!=null);
     
    }
}
}

I am trying to instantiate my controller in my test class but I had to do the controller class slightly differently then others that I've done in the past and so I can't figure out how to get it define in the test class.

 

My controllerclass  says this for the page controller

private Id demoId;

    private ApexPages.StandardController controller;

    public DemoContactEntryExtension(ApexPages.StandardController controller) {
        this.controller = controller;

        // get the id of the demo
        demoId = controller.getId();

 

my test class says this:

 

//Create Test Data

Account a=new Account(Name='Test Account');
    insert a;
Contact c = new Contact(FirstName='John',LastName='Doe', AccountID=a.id);
    insert c;
Opportunity o = new Opportunity(Name='Test Opportunity',closedate=system.today(), stagename='Confirmed Teaching/Class Schedule',Probability=0.95, accountID=a.id);
    insert o;      
OpportunityContactRole ocr = new OpportunityContactRole (Opportunityid = o.id, Contactid=c.id, role='Decision Maker', isPrimary=True) ;     
    insert ocr;  
Demo__c demo = new Demo__c (Primary_Opportunity__c=o.id, Name='Test Demo');
    insert demo;
Demo_Opportunity__c doc = new Demo_Opportunity__c (Opportunity__c=o.id, Demo__c=demo.id);
    insert doc;
Demo_Contact__c dcc = new Demo_Contact__c (Contact__c=c.id, demo__c=demo.id);
    insert dcc;

     
        ////////////////////////////////////////
        //  test DemoContactEntry
        ////////////////////////////////////////
        
           // load the page             
        PageReference pageRef = Page.Demo_Contact_Entry;
        pageRef.getParameters().put('Id',dcc.demo__c);
        Test.setCurrentPageReference(pageRef);
    // load the extension
        
        DemoContactEntryExtension dCEE = new DemoContactEntryExtension(new ApexPages.StandardController(dcc.demo__c));
        

If anyone knows how I can change this to instantiate the controller that would be great.

 

Thanks,

Amanda

This is driving me crazy.  It works in "real life" - meaning if I go to a record and try it myself it works but in my test class it insists that the assert for the search fails.  The code for the search in the controller itself is this:

    public void updateAvailableList() {
        
        // We dynamically build a query string and exclude items already in the shopping cart
        String qString = 'select Id, ContactId, OpportunityId from OpportunityContactRole where OpportunityId = \'' + theOpp.Id + '\'';
                
        // note that we are looking for the search string entered by the user in the First Name OR Last Name
        // modify this to search other fields if desired
        if(searchString!=null){
            qString+= ' and (OpportunityContactRole.Contact.FirstName like \'%' + searchString + '%\' or OpportunityContactRole.Contact.LastName like \'%' + searchString + '%\')';
        }

 

and my test class is saying the following - which is almost exactly the same as another test class and controller I have that does assert just fine.  Driving me crazy.

 

        // test search again, this time we will find something
        qCEE.searchString = c2.FirstName;
        qCEE.updateAvailableList();
        system.assert(qCEE.availablecontacts.size()>0);      

 

 

the c2.FirstName is part of my records created at the beginning of the test class as:

Account a=new Account(Name='Test Account');
    insert a;
Contact c = new Contact(FirstName='John',LastName='Doe', AccountID=a.id);
    insert c;
Contact c2 = new Contact(FirstName='Jane',Lastname='Doe',AccountID=a.id);
    insert c2;
Opportunity o = new Opportunity(Name='Test Opportunity',closedate=system.today(), stagename='Confirmed Teaching/Class Schedule',Probability=0.95, accountID=a.id);
    insert o;      
OpportunityContactRole ocr = new OpportunityContactRole (Opportunityid = o.id, Contactid=c.id, role='Decision Maker', isPrimary=True) ;     
    insert ocr;  
OpportunityContactRole ocr2 = new OpportunityContactRole (Opportunityid = o.id, Contactid=c2.id, role='Decision Maker', isPrimary=False) ;     
    insert ocr2;  
Quote q = new Quote (Name='Test Demo', Opportunityid=o.id);
    insert q;
Quote_Contact__c qcc = new Quote_Contact__c (Adoption_Agreement__c=q.id, contact__c=c.id);
    insert qcc;

 

 

If anyone sees what I'm doing wrong that would be awesome.  I can't remove the assertion because then the next part fails as well.

 

Thanks,

Amanda

I have a very simple imbedded page and controller that is working in my dev org and has worked in previous sandbox and production orgs but for some reason is not working in the current sandbox I am working in.  Is there a setting somewhere that could be essentially disabling this?  It is on the page layout, the profiles have access to the page and the class, the debug shows that the page is being called and that it is looking at the class but the page is not invoking the MarkRead method from the class and the popups are not working.  Any suggestions or ideas would be GREATLY appreciated.
Thanks,
Amanda

Simple page to product popup alert
<apex:page standardController="Opportunity" extensions="OpportunityAlertExtension">
    <apex:form >
    <apex:actionFunction action="{!markread}" name="MarkRead"/>
    </apex:form>
<script type="text/javascript">
    if({!opp.Territory2id==null && opp.MNVAlert_Shown__c==False && (opp.Kind_HSS_STEM__c==null || opp.Kind_HSS_STEM__c == 'Other')}) {
        window.alert("This Opportunity is neither HSS or STEM. Please correct the Discipline and re-save");
        updateStatus(); 
    else if({!opp.Territory2id==null && opp.MNVAlert_Shown__c==False && (opp.Kind_HSS_STEM__c!=null || opp.Kind_HSS_STEM__c != 'Other')}) {
        window.alert("No territory found for this Opportunity. Please select the correct Owner and Territory manually");
        updateStatus(); 
    }

</script>
</apex:page>

Class called by VF Page
public class OpportunityAlertExtension {

    Public Opportunity opp      {get;set;}
    public OpportunityAlertExtension(ApexPages.StandardController controller) {
        ID oppID = controller.getID();
        System.debug('=== Opportunityid: ' + oppID);

        opp = [Select Id, Name, AccountId, MNVAlert_Shown__c, Kind_HSS_STEM__c, StageName, Territory2ID
            From Opportunity
            Where Id =:oppID ];
            System.debug('=== Opportunity: ' + opp);
    }
    

    public void markread() {
        Opportunity o = this.opp;
        o.MNVAlert_Shown__c = true;
        update o;
        System.debug('=== Opportunity updated: ' + o);
    }
}

Debug log

35.0 APEX_CODE,FINEST;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;SYSTEM,DEBUG;VALIDATION,INFO;VISUALFORCE,INFO;WORKFLOW,INFO 09:11:14.220 (220570453)|EXECUTION_STARTED 09:11:14.220 (220604813)|CODE_UNIT_STARTED|[EXTERNAL]|066L0000000EUbm|VF: /apex/Opportunity_Page_Alert 09:11:14.222 (222224285)|CODE_UNIT_STARTED|[EXTERNAL]|01pL0000000R08e|OpportunityAlertExtension <init> 09:11:14.222 (222241587)|SYSTEM_MODE_ENTER|true 09:11:14.222 (222852101)|HEAP_ALLOCATE|[72]|Bytes:3 09:11:14.222 (222914806)|HEAP_ALLOCATE|[77]|Bytes:152 09:11:14.222 (222936341)|HEAP_ALLOCATE|[342]|Bytes:408 09:11:14.222 (222958886)|HEAP_ALLOCATE|[355]|Bytes:408 09:11:14.222 (222980209)|HEAP_ALLOCATE|[467]|Bytes:48 09:11:14.223 (223020906)|HEAP_ALLOCATE|[139]|Bytes:6 09:11:14.223 (223054850)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:80 09:11:14.223 (223062706)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:6 09:11:14.223 (223066970)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:7 09:11:14.223 (223088249)|METHOD_ENTRY|[1]|01pL0000000R08e|OpportunityAlertExtension.OpportunityAlertExtension() 09:11:14.223 (223095331)|STATEMENT_EXECUTE|[1] 09:11:14.223 (223101201)|STATEMENT_EXECUTE|[1] 09:11:14.223 (223108960)|METHOD_EXIT|[1]|OpportunityAlertExtension 09:11:14.223 (223135430)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:8 09:11:14.223 (223159106)|VARIABLE_SCOPE_BEGIN|[4]|this|OpportunityAlertExtension|true|false 09:11:14.223 (223209207)|VARIABLE_ASSIGNMENT|[4]|this|{}|0x3d842d34 09:11:14.223 (223218151)|VARIABLE_SCOPE_BEGIN|[4]|controller|ApexPages.StandardController|true|false 09:11:14.223 (223350922)|VARIABLE_ASSIGNMENT|[4]|controller|"StandardController [null]"|0x187a6d2 09:11:14.223 (223363084)|STATEMENT_EXECUTE|[1] 09:11:14.223 (223366109)|STATEMENT_EXECUTE|[3] 09:11:14.223 (223380650)|HEAP_ALLOCATE|[5]|Bytes:6 09:11:14.223 (223416932)|VARIABLE_SCOPE_BEGIN|[2]|this|System.ApexBaseClass|true|false 09:11:14.223 (223438018)|VARIABLE_ASSIGNMENT|[2]|this|{}|0x3d842d34 09:11:14.223 (223453175)|STATEMENT_EXECUTE|[4] 09:11:14.223 (223456112)|STATEMENT_EXECUTE|[5] 09:11:14.223 (223546357)|HEAP_ALLOCATE|[5]|Bytes:15 09:11:14.223 (223583293)|HEAP_ALLOCATE|[5]|Bytes:4 09:11:14.223 (223590521)|VARIABLE_SCOPE_BEGIN|[5]|oppID|Id|false|false 09:11:14.223 (223653581)|VARIABLE_ASSIGNMENT|[5]|oppID|"006L0000008OEtxIAG" 09:11:14.223 (223661826)|STATEMENT_EXECUTE|[6] 09:11:14.223 (223667103)|HEAP_ALLOCATE|[6]|Bytes:19 09:11:14.223 (223731654)|HEAP_ALLOCATE|[6]|Bytes:18 09:11:14.223 (223759313)|HEAP_ALLOCATE|[6]|Bytes:37 09:11:14.223 (223784835)|HEAP_ALLOCATE|[50]|Bytes:5 09:11:14.223 (223807767)|HEAP_ALLOCATE|[56]|Bytes:5 09:11:14.223 (223819243)|HEAP_ALLOCATE|[64]|Bytes:7 09:11:14.223 (223865757)|USER_DEBUG|[6]|DEBUG|=== Opportunityid: 006L0000008OEtxIAG 09:11:14.223 (223876033)|STATEMENT_EXECUTE|[8] 09:11:14.223 (223880912)|HEAP_ALLOCATE|[8]|Bytes:125 09:11:14.223 (223895219)|HEAP_ALLOCATE|[8]|Bytes:4 09:11:14.223 (223908515)|HEAP_ALLOCATE|[8]|Bytes:7 09:11:14.224 (224347471)|SOQL_EXECUTE_BEGIN|[8]|Aggregations:0|SELECT Id, Name, AccountId, MNVAlert_Shown__c, Kind_HSS_STEM__c, StageName, Territory2ID FROM Opportunity WHERE Id = :tmpVar1 09:11:14.229 (229042000)|SOQL_EXECUTE_END|[8]|Rows:1 09:11:14.229 (229073034)|HEAP_ALLOCATE|[8]|Bytes:8 09:11:14.229 (229093831)|HEAP_ALLOCATE|[8]|Bytes:195 09:11:14.229 (229184597)|HEAP_ALLOCATE|[8]|Bytes:8 09:11:14.229 (229195789)|HEAP_ALLOCATE|[8]|Bytes:37 09:11:14.229 (229291244)|HEAP_ALLOCATE|[8]|Bytes:28 09:11:14.229 (229357008)|VARIABLE_ASSIGNMENT|[-1]|this|{}|0x3d842d34 09:11:14.229 (229394199)|VARIABLE_ASSIGNMENT|[-1]|value|{"s":1,"v":{"Id":"006L0000008OEtxIAG","Name":"Department1: QAI_Tes (24 more) ...","AccountId":"001L000000mWIJXIA4","MNVAlert_Shown__c":false,"StageName":"Prospecting","RecordTypeId":"012L0000000DKZ8IAO"}}|0x7f306188 09:11:14.229 (229419832)|VARIABLE_ASSIGNMENT|[3]|this.opp|{"s":1,"v":{"Id":"006L0000008OEtxIAG","Name":"Department1: QAI_Tes (24 more) ...","AccountId":"001L000000mWIJXIA4","MNVAlert_Shown__c":false,"StageName":"Prospecting","RecordTypeId":"012L0000000DKZ8IAO"}}|0x3d842d34 09:11:14.229 (229433864)|STATEMENT_EXECUTE|[11] 09:11:14.229 (229439674)|HEAP_ALLOCATE|[11]|Bytes:17 09:11:14.229 (229489763)|VARIABLE_ASSIGNMENT|[-1]|this|{"opp":"0x7f306188"}|0x3d842d34 09:11:14.229 (229572569)|HEAP_ALLOCATE|[11]|Bytes:197 09:11:14.229 (229597405)|HEAP_ALLOCATE|[11]|Bytes:214 09:11:14.229 (229611763)|USER_DEBUG|[11]|DEBUG|=== Opportunity: Opportunity:{Id=006L0000008OEtxIAG, Name=Department1: QAI_Test_Account1: Spring: 2015, AccountId=001L000000mWIJXIA4, MNVAlert_Shown__c=false, StageName=Prospecting, RecordTypeId=012L0000000DKZ8IAO} 09:11:14.230 (230279368)|CODE_UNIT_FINISHED|OpportunityAlertExtension <init> 09:11:14.260 (260066812)|CODE_UNIT_STARTED|[EXTERNAL]|01pL0000000R08e|OpportunityAlertExtension get(opp) 09:11:14.260 (260093022)|SYSTEM_MODE_ENTER|true 09:11:14.260 (260115204)|CODE_UNIT_STARTED|[EXTERNAL]|01pL0000000R08e|opp 09:11:14.260 (260142455)|CODE_UNIT_FINISHED|opp 09:11:14.260 (260165264)|CODE_UNIT_FINISHED|OpportunityAlertExtension get(opp) 09:11:14.262 (262142347)|VF_SERIALIZE_VIEWSTATE_BEGIN|066L0000000EUbm 09:11:14.263 (263460613)|VF_SERIALIZE_VIEWSTATE_END 09:11:14.266 (266971105)|CUMULATIVE_LIMIT_USAGE 09:11:14.266 (266971105)|LIMIT_USAGE_FOR_NS|(default)| Number of SOQL queries: 1 out of 100 Number of query rows: 1 out of 50000 Number of SOSL queries: 0 out of 20 Number of DML statements: 0 out of 150 Number of DML rows: 0 out of 10000 Maximum CPU time: 0 out of 10000 Maximum heap size: 0 out of 6000000 Number of callouts: 0 out of 100 Number of Email Invocations: 0 out of 10 Number of future calls: 0 out of 50 Number of queueable jobs added to the queue: 0 out of 50 Number of Mobile Apex push calls: 0 out of 10 09:11:14.266 (266971105)|CUMULATIVE_LIMIT_USAGE_END 09:11:14.267 (267009070)|CODE_UNIT_FINISHED|VF: /apex/Opportunity_Page_Alert 09:11:14.268 (268270387)|EXECUTION_FINISHED
 
I'm trying to populate a text field on Account with the Territory names (original territories, not Enterprise Territories or Territories2).  In order to do this you have to map through Account to Account Share to Group to Territory and then back.  I've got the mapping done I think but the navigating back is proving quite difficult, especially since my map for Account Share involves a list inside a map.  I also need the Territories that have been both mapped and Listed to show up in my field as just a string (IE Territory 1, Territory 2, Territory 3, etc).  How can I do this?  Currently line 75 is giving me an error of Incompatible key type List<AccountShare> for Map<Id,Id> at line 75 column 43.  I did the Account Shares map with a List because just having the Account ID, Group ID on the accountShare was deduplicating by the account ID and leaving me with just 1 record everytime instead of multiples.  I tried vastly simplifying line 75 to just MapofTerritories.values(); (which I don't think would bulk at all) and got the error of Illegal assignment from List<String> to String at line 75 column 12 so there's an issue there of having it list them out no matter if I get back to the correct account or not.
Thank you for your help

trigger AccountTerritories on Account (before update){
    if(Trigger.isBefore){
        Set<Id> setOfAccountIds = new Set<Id>();

        for(Account acct : Trigger.New){
            if(Trigger.isUpdate){
                if(acct.Id != null){
                    setOfAccountIds.add(acct.Id);
                }
            }
        }
 
        if(setOfAccountIds.size() > 0){

        /* Declaration of collection data types */
        Map<id,List<AccountShare>> MapOfAccountShare = new    Map<id,List<AccountShare>>();
       Map<Id, Id> mapOfGroup = new Map<Id, Id>();
       Map<Id, String> mapOfTerritories = new Map<Id, String>();


//Query in Account Share object
    /*
    Those Accounts which are assigned via Territory Assignment Rules.
You can query those Accounts by filtering RowCause = 'Territory' in AccountShare object query.
    */
    List<AccountShare> listOfAccountShare =
    [Select Id, UserOrGroupId, AccountId, RowCause from AccountShare where AccountId IN :setOfAccountIds];
    System.debug('=== contents of listOfAccountShare: ' + listOfAccountShare);
    System.debug('=== size of listOfAccountShare: ' + listOfAccountShare.size());
    List<Id> Groupids = new List<Id>();
    for(AccountShare a :listofAccountShare){
    Groupids.add(a.UserOrGroupId);
    }

    //Map of Account Share

  for(AccountShare acctShare : listOfAccountShare ){
        if (MapOfAccountShare.containsKey(acctShare.AccountID))
            {
        MapOfAccountShare.get(acctShare.AccountID). add(acctShare);
        }
        else{
        MapOfAccountShare.put(acctShare.AccountID, new  List <AccountShare> { acctShare });
        }  
        }  
    System.debug('=== all AccountShare keys in the map: ' + mapOfAccountShare.keySet());  
    System.debug('=== all AccountShare values in the map (as a List): ' + mapOfAccountShare.values());
    System.debug('=== size of mapOfAccountShare: ' + mapOfAccountShare.size());

    //Query in Group object            
    List<Group> listOfGroup = [Select Id, RelatedId from Group where Type='Territory' and Id IN :GroupIDs];
    System.debug('=== contents of listOfGroup: ' + listOfGroup);
    System.debug('=== size of listOfGroup: ' + listOfGroup.size());
//Map of Group object
    for(Group groupRecord : listOfGroup){
    mapOfGroup.put(groupRecord.Id, groupRecord.RelatedId);        
    }
    System.debug('=== all Group keys in the map: ' + mapOfGroup.keySet());  
    System.debug('=== all Group values in the map (as a List): ' + mapOfGroup.values());
    System.debug('=== size of MapOfGroup: ' + mapOfGroup.size());

    //Query in Territory object
    List<Territory> listOfTerritory = [Select Id, Name from Territory where Id IN :mapOfGroup.Values()];
    System.debug('=== contents of listOfTerritories: ' + listOfTerritory);
    System.debug('=== size of listOfTerritories: ' + listOfTerritory.size());
    //Map of Territory object
    
    for(Territory Territories : listOfTerritory){
    mapOfTerritories.put(Territories.Id, Territories.Name);
    System.debug('=== all Territories keys in the map: ' + mapOfTerritories.keySet());  
    System.debug('=== all Territories values in the map (as a List): ' + mapOfTerritories.values());  
    System.debug('=== size of MapOfTerritories: ' + mapOfTerritories.size());
    }
    for (Account updatedAccount : Trigger.new) {
    String territory = MapofTerritories.get(mapofGroup.get(mapofAccountShare.get(updatedaccount.id )));
    updatedAccount.territories__c = territory;
    }
 
}

}
}
I am trying to bulk my test class and running into issues.  I finally seem to have gotten past whatever was causing my DML error (I added a limit of 200 rows) but now it's still giving me an error on the UPDATE (not insert) saying that my demo doesn't have a demo date when they all clearly do because they inserted just fine.  What totally obvious thing am I clearly missing?
Thanks,
Amanda

    static testMethod void TestDemoSpecialisttoOppTeamSL() {
        
        //inserting a user
         Map<String,ID> profiles = new Map<String,ID>();
        List<Profile> ps = [select id, name from Profile where name =
        'Standard User' or name = 'System Administrator'];
            for(Profile p : ps){
                profiles.put(p.name, p.id);
            }

OMITTING a bunch of code here that doesn't seem to be part of the issue...this is where my bulking begins.
        
        // Insert 100 Demos
    List<Demo__c> Demos = new List<Demo__c>();
    for (Integer i = 0; i < 200; i++) {
        Demo__c demo = new Demo__c();
        demo.name = 'Test Demo' + i;
        demo.Contact__c = cont[0].id;
        demo.Opportunity__c = opp.id;
        demo.demo_date__c = Date.newInstance(2020,12,01);
        demo.Sales_Rep_Notes__c = 'Testing new demo creation';
        demos.add(demo);
    }
    insert Demos;      
        // Switch to test context
        Test.startTest();
    demos = [SELECT Id, Demo_Given_By__c FROM Demo__c limit 200];    
        //update demo to include demo specialist
        for (Demo__c demo : demos) {
          demo.Demo_Given_by__c = users[4].id;
    }
    update demos;       
 
        // check that the Opportunity Team Members were created
        List<OpportunityTeammember> newOTM = [Select otm.Id From OpportunityTeamMember otm where OpportunityID = :opp.id];
        System.assertEquals(newOTM.size(),2);
                
        // Switch back to runtime context
        Test.stopTest();       
 
    }
I'm trying to Query all of the Territories associated with an account record (old Territory not Territory2) in order to put them in a custom text field. First I am trying to do the steps of going from Account to AccountShare to Group to Territory but based on my debug it seems to be breaking from going from the list to the map on AccountShares.  The the debug list shows all the AccountShares that it should when I test update an account but then the debug on the map for Account shares only shows one AccountShare and not the correct one.  So once that map only gives one then all the rest only give one.  Can someone direct me as to what I'm doing wrong that is causing the map of the list to vary from the list itself?
Thanks

trigger AccountTerritories on Account (before update){
    if(Trigger.isBefore){
        Set<Id> setOfAccountIds = new Set<Id>();

        for(Account acct : Trigger.New){
            if(Trigger.isUpdate){
                if(acct.Id != null){
                    setOfAccountIds.add(acct.Id);
                }
            }
        }
 
        if(setOfAccountIds.size() > 0){

        /* Declaration of collection data types */
Map<Id, Id> mapOfAccountShare = new Map<Id, Id>();
       Map<Id, Id> mapOfGroup = new Map<Id, Id>();
       Map<Id, Territory> mapOfUserTerritory = new Map<Id, Territory>();


//Query in Account Share object

    List<AccountShare> listOfAccountShare =
    [Select Id, UserOrGroupId, AccountId, RowCause from AccountShare where AccountId IN :setOfAccountIds];
    System.debug('=== contents of listOfAccountShare: ' + listOfAccountShare);

//Map of Account Share
    for(AccountShare acctShare : listOfAccountShare){
    mapOfAccountShare.put(acctShare.AccountId, acctShare.UserOrGroupId);        
    }      
    System.debug('=== all AccountShare keys in the map: ' + mapOfAccountShare.keySet());  
    System.debug('=== all AccountShare values in the map (as a List): ' + mapOfAccountShare.values());

    //Query in Group object            
    List<Group> listOfGroup = [Select Id, RelatedId from Group where Type='Territory' and Id IN :mapOfAccountShare.Values()];
    System.debug('=== contents of listOfGroup: ' + listOfGroup);
//Map of Group object
    for(Group groupRecord : listOfGroup){
    mapOfGroup.put(groupRecord.Id, groupRecord.RelatedId);        
    }
    System.debug('=== all Group keys in the map: ' + mapOfGroup.keySet());  
    System.debug('=== all Group values in the map (as a List): ' + mapOfGroup.values());

    //Query in Territory object
    Map<Id, Territory> mapOfTerritories =
    new Map<Id, Territory>([select id, name, ParentTerritoryId from Territory where Id IN:mapOfGroup.Values() ]);  
    System.debug('=== all Territories keys in the map: ' + mapOfTerritories.keySet());  
    System.debug('=== all Territories values in the map (as a List): ' + mapOfTerritories.values());  


 
}

}
}

 
I'm receiving a null reference error only when uploading.  I can't seem to find a reason for why in the upload they are causing this null reference error but not individually.  At first I thought my qualification that it end if there were no eligible account team records was the issue but I've tried that and it worked on an individual one.  Even a small group of 20 records gets stopped on upload.  It will only insert them individually. I guess I must have bulked this improperly but I'm not sure where the hangup is steming from.  The error is pointing to line 110 but I'm not sure that is the actual issue because like I said the records are fine individually.  So maybe its getting confused when cross referencing the lists?  Any help would be greatly appreciated.

Thanks so much,
Amanda

trigger ProductCopyActTeamtoOpportunity on OpportunityLineItem (after insert) {

List<OpportunityTeamMember> oppTeamMembersList = new List<OpportunityTeamMember>();

//Get Account ID from Opportunity when products are added

List<OpportunityLineItem> OLIAccountIDs = new List<OpportunityLineItem>([SELECT Opportunity.AccountId, OpportunityID, Quantity, Product2.Family FROM OpportunityLineItem WHERE Id IN: Trigger.newMap.keySet()]);
Set<Id> accountIds = new Set<Id>();
for(OpportunityLineItem oli : OLIAccountIDs){
    accountIds.add(oli.Opportunity.AccountId);
}

Map< Id , Id > OpportunityLineItemIdToAccountId = new Map< Id , Id >();
for(OpportunityLineItem oli :OLIAccountIDs)  {
    if(oli.Quantity > 0.0)   {
        OpportunityLineItemIdToAccountId.put(oli.opportunityid,  oli.opportunity.accountid );
        System.Debug(oli.quantity);
        System.Debug(oli.id);
        System.debug(oli.opportunityid);
        system.debug(oli.opportunity.accountid);
    }
}

    
//Map from Account ID to get Standard Account Team Members
Map<id, List<AccountTeamMember > > accountIdToAccountTeamMembers = new    Map<id,  List<AccountTeamMember > > ();
for(AccountTeamMember accountTeamMember : [SELECT a.UserId,a.User.Name,a.TeamMemberRole, a.Id, a.AccountId
                        FROM AccountTeamMember a
                        WHERE a.TeamMemberRole IN ('Partner', 'Partner Manager','QB', 'QB Manager') AND
                        a.AccountId in :OpportunityLineItemIdToAccountId.values() ])   {

    
        List<AccountTeamMember > accountTeamMembers = ( accountIdToAccountTeamMembers.get(accountTeamMember.Accountid) == null) ?
                                                       new  List<AccountTeamMember >() :
                                                       accountIdToAccountTeamMembers.get(accountTeamMember.Accountid);

        accountTeamMembers.add(accountTeamMember);
        accountIdToAccountTeamMembers.put(accountTeamMember.Accountid, accountTeamMembers);
        system.debug(accountIdToAccountTeamMembers.size());
         }

//Map Account ID for Hayden McNeil

Map< Id , Id > HMspecialistOpportunityIDtoAccountID = new Map< Id , Id >();
for(OpportunityLineItem oli :OLIAccountIDs)  {
    // check if any of the product families we care about are used
    if(oli.Product2.Family == 'Hayden-McNeil')   {
        HMspecialistOpportunityIDtoAccountID.put(oli.opportunityid,  oli.Opportunity.AccountId );
        System.Debug(oli.quantity);
        System.Debug(oli.Product2.Family);
        System.Debug(oli.id);
        System.debug(oli.opportunityid);
        system.debug(oli.opportunity.accountid);
    }
}

//Map from Account ID to get Specialists for HM
Map<id, List<AccountTeamMember > > HMspecialistaccountIdToAccountTeamMembers = new    Map<id,  List<AccountTeamMember > > ();
for(AccountTeamMember HMspecialistaccountTeamMember : [SELECT a.UserId,a.User.Name,a.TeamMemberRole, a.Id, a.AccountId
                        FROM AccountTeamMember a
                        WHERE a.TeamMemberRole IN ('HM Specialist','HM Specialist Manager') AND
                        a.AccountId in :HMspecialistOpportunityIDtoAccountID.values() ]) {

        List<AccountTeamMember > HMspecialistaccountTeamMembers = ( HMspecialistaccountIdToAccountTeamMembers.get(HMspecialistaccountTeamMember.Accountid) == null) ?
                                                       new  List<AccountTeamMember >() :
                                                       HMspecialistaccountIdToAccountTeamMembers.get(HMspecialistaccountTeamMember.Accountid);

        HMspecialistaccountTeamMembers.add(HMspecialistaccountTeamMember);
        HMspecialistaccountIdToAccountTeamMembers.put(HMspecialistaccountTeamMember.Accountid, HMspecialistaccountTeamMembers);
}

//Map Account ID for iClicker

Map< Id , Id > iClickerspecialistOpportunityIDtoAccountID = new Map< Id , Id >();
for(OpportunityLineItem oli :OLIAccountIDs)  {
    // check if any of the product families we care about are used
    if(oli.Product2.Family == 'i>clicker')   {
        iClickerspecialistOpportunityIDtoAccountID.put(oli.opportunityid,  oli.Opportunity.AccountId );
        System.Debug(oli.quantity);
        System.Debug(oli.Product2.Family);
        System.Debug(oli.id);
        System.debug(oli.opportunityid);
        system.debug(oli.opportunity.accountid);
    }
}

//Map from Account ID to get Specialists for iClicker
Map<id, List<AccountTeamMember > > iClickerspecialistaccountIdToAccountTeamMembers = new    Map<id,  List<AccountTeamMember > > ();
for(AccountTeamMember iClickerspecialistaccountTeamMember : [SELECT a.UserId,a.User.Name,a.TeamMemberRole, a.Id, a.AccountId
                        FROM AccountTeamMember a
                        WHERE a.TeamMemberRole IN ('Reef Specialist','Reef Specialist Manager') AND
                        a.AccountId in :iClickerspecialistOpportunityIDtoAccountID.values() ]) {

        List<AccountTeamMember > iClickerspecialistaccountTeamMembers = ( iClickerspecialistaccountIdToAccountTeamMembers.get(iClickerspecialistaccountTeamMember.Accountid) == null) ?
                                                       new  List<AccountTeamMember >() :
                                                       iClickerspecialistaccountIdToAccountTeamMembers.get(iClickerspecialistaccountTeamMember.Accountid);

        iClickerspecialistaccountTeamMembers.add(iClickerspecialistaccountTeamMember);
        iClickerspecialistaccountIdToAccountTeamMembers.put(iClickerspecialistaccountTeamMember.Accountid, iClickerspecialistaccountTeamMembers);
}
    if( accountIdToAccountTeamMembers.keySet().size()> 0 ) // if there are no eligible Account Team records, end
{

for(OpportunityLineItem oli :OLIAccountIDs) {
    if(oli.quantity > 0.0)   {
        Id accountId  = OpportunityLineItemIdToAccountId.get(oli.opportunityid);
        System.debug(accountid);
        System.Debug(oli.product2.Family);
        system.debug(accountidtoaccountteammembers.get(accountid));
        for ( AccountTeamMember accountTeamMember : accountIdToAccountTeamMembers.get(accountId) )  {
            OpportunityTeamMember opportunityTeamMember  = new OpportunityTeamMember();
            opportunityTeamMember.UserId = accountTeamMember.UserId;
            opportunityTeamMember.TeamMemberRole = accountTeamMember.TeamMemberRole;
            system.debug (accountTeamMember.TeamMemberRole);
            opportunityTeamMember.OpportunityId = oli.opportunityID;
            oppTeamMembersList.add(opportunityTeamMember);
        }
     }
     if(oli.Product2.Family == 'Hayden-McNeil')   {
        System.Debug(oli.product2.Family);
        Id HMaccountId  = HMspecialistOpportunityIDtoAccountID.get(oli.opportunityId);
        System.Debug(HMaccountId);
        for ( AccountTeamMember accountTeamMember : HMspecialistaccountIdToAccountTeamMembers.get(HMaccountId) )  {
            OpportunityTeamMember opportunityTeamMember  = new OpportunityTeamMember();
            opportunityTeamMember.UserId = accountTeamMember.UserId;
            opportunityTeamMember.TeamMemberRole = accountTeamMember.TeamMemberRole;
            system.debug (accountTeamMember.TeamMemberRole);
            opportunityTeamMember.OpportunityId = oli.opportunityID;
            oppTeamMembersList.add(opportunityTeamMember);
        }
     }
     if(oli.Product2.Family == 'i>clicker')   {
        System.Debug(oli.product2.Family);
        Id iClickeraccountId  = iClickerspecialistOpportunityIDtoAccountID.get(oli.opportunityId);
        System.Debug(iClickeraccountId);
        for ( AccountTeamMember accountTeamMember : iClickerspecialistaccountIdToAccountTeamMembers.get(iClickeraccountId) )  {
            OpportunityTeamMember opportunityTeamMember  = new OpportunityTeamMember();
            opportunityTeamMember.UserId = accountTeamMember.UserId;
            opportunityTeamMember.TeamMemberRole = accountTeamMember.TeamMemberRole;
            system.debug (accountTeamMember.TeamMemberRole);
            opportunityTeamMember.OpportunityId = oli.opportunityID;
            oppTeamMembersList.add(opportunityTeamMember);
        }
     }
}

insert oppTeamMembersList;
}
}
 
I have a custom button which uses a controller class to clone an opportunity.  I'd like it to only allow the clone if certain criteria are met but I am running into an issue that if the criteria are not met I receive an error saying
"Visualforce ErrorHelp for this Page
System.NullPointerException: Attempt to de-reference a null object
Error is in expression '{!cloneWithItems}' in component <apex:page> in page opportunity_clone: Class.OpportunityCloneWithItemsController.cloneWithItems: line 157, column 1"
that line is
return new PageReference('/'+newOpp.id+'/e?retURL=%2F'+newOpp.id);
I tried adding in
  if(newopp.id != null){
      return new PageReference('/'+newOpp.id+'/e?retURL=%2F'+newOpp.id);
        }else{
      ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, 'The Opportunity could not be cloned');
      ApexPages.addMessage(msg);
But then I get "Compile Error: Non-void method might not return a value or might have statement after a return statement."
I understand that the reason I'm getting the first error is that if my criteria are NOT met then there will be no newOpp so it will be null, but I'm not clear on why it won't allow me to add a .message or if there is a way to just change the error that users see when they've tried to use the button incorrectly.  I'd prefer they just see a standard error saying "This Opportunity Cannot be Cloned" instead of the whole VF page error that references the class.

Thanks so much,
Amanda
 
I can't believe no one out there has wanted to do this but I've searched and searched and haven't found anything similar.  Specifically when converting a lead with an opportunity we'd like it to immedietly go to the add product page for the opportunity or at least just the page for the opportunity that was just created.  It seems like there should be some way to do this.  Something must tell it that it was just at the lead page and is now at the account page even if it's an existing account.  I just can't find how.  If anyone has any ideas on this I would love to hear them.

Thanks,
Amanda
Can anyone please help me understand why this is hitting SOQL limits?  I repurposed a previously working trigger that I had to do pretty much the same thing again but with a little bit more if then statements and a couple oldmap.get statements.  The prior trigger would allow you to import opportunities and update a date field and that would make the trigger go off with no problems.  But now this one doing pretty much the same thing with a checkbox is hitting SOQL statements when I try to do the import update to a special checkbox field.  Any ideas?

Thanks so much,
Amanda

trigger CloneOpportunityRollover on Opportunity (after Update) {
    
    List <Opportunity> opportunities = [select Id, Name, Type, LeadSource, Roll_Manually__c, Textbook__c, Description, Subject__c, Term_Use__c, Opportunity_Rolled__c,
    Opportunity_Rolled_From__c, AccountID, StageName, Term__c, CloseDate, Account.Academic_Calendar__c, Account.Winter_Course_Start_Date__c, Opportunity_Type__c,
    Account.Spring_Course_Start_Date__c, Account.Summer_Course_Start_Date__c, Account.Fall_Course_Start_Date__c, (select Id, opportunity.term__c,
    opportunity.stagename, opportunity.Term_Use__c, opportunity.account.Academic_Calendar__c,unitprice, Quantity, PricebookEntryID, Description From
    OpportunityLineItems), (Select Id, Contactid, IsPrimary, Role From OpportunityContactRoles) from Opportunity where ID IN :Trigger.newMap.keySet()];
    
    
    List<Opportunity> opportunitiesToUpdate = new List<Opportunity>{};
    List<Opportunity> newOpportunities = new List<Opportunity>{};
    List<OpportunityLineItem> newOpportunityLineitems = new List<OpportunityLineItem>{};
    List<opportunitycontactrole> newOpportunityContactRoles = new List<opportunitycontactrole>{};
    Integer CurrentYear = Date.Today().Year();
    
    
    

    for(Opportunity opp : opportunities){
    Integer CloseDateMonth = Opp.CloseDate.Month();
        if (((trigger.oldMap.get(Opp.id).StageName != null && opp.StageName == 'Commitment' &&  opp.Stagename != trigger.oldMap.get(Opp.id).StageName)  || opp.Roll_Manually__c == True) && Opp.Opportunity_Rolled__c == False && (Opp.Opportunity_Type__c == 'Hayden-McNeil' ||
        Opp.Opportunity_Type__c == 'Sapling Learning' || Opp.Opportunity_Type__c == 'Late Nite Labs' || Opp.Opportunity_Type__c == 'Nature Ed' ||
        Opp.Opportunity_Type__c == 'i>clicker')) {
            Opportunity newOpp;
            
            
//          try {
            
                newOpp = opp.clone(false);
                if (Opp.Term_Use__c == 'Used Each Term') {
                                
                    if (opp.term__c == 'Fall' && opp.account.Academic_Calendar__c == 'Semester') {
                        newOpp.Term__c = 'Spring';
                        if (opp.account.Spring_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Spring_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 1, 1) ;}
                    } else if (opp.term__c == 'Winter' && (opp.account.Academic_Calendar__c == 'Quarter' || opp.account.Academic_Calendar__c == 'Trimester')) {
                        newOpp.Term__c = 'Spring';
                        if (opp.account.Spring_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Spring_Course_Start_Date__c;
                        } else if (opp.closedate.month()==1 || opp.closedate.month()==2){
                        newOpp.CloseDate = date.newInstance(opp.CloseDate.Year(), 3, 1) ;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 3, 1) ;}
                    } else if ( opp.term__c == 'Spring' && opp.account.Academic_Calendar__c == 'Semester' )  {
                        newOpp.Term__c = 'Fall';
                        if (opp.account.Fall_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Fall_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year(), 9, 1) ;}
                    } else if ( opp.term__c == 'Fall' && (opp.account.Academic_Calendar__c == 'Quarter' || opp.account.Academic_Calendar__c == 'Trimester'))  {
                        newOpp.Term__c = 'Winter';
                        if (opp.account.Winter_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Winter_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 1, 1);}
                    } else if ( opp.term__c == 'Spring' && (opp.account.Academic_Calendar__c == 'Quarter' || opp.account.Academic_Calendar__c == 'Trimester'))  {
                        newOpp.Term__c = 'Summer';
                        if (opp.account.Summer_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Summer_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year(), 5, 1);}
                    } else if (opp.term__c == 'Summer') {
                        newOpp.Term__c = 'Summer';
                        if (opp.account.Summer_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Summer_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 5, 1) ;}
                    }
                } else if (Opp.Term_Use__c == 'Single Term') {
                                
                    if ( opp.term__c == 'Spring' && opp.account.Academic_Calendar__c == 'Semester') {
                        newOpp.Term__c = 'Spring';
                        if (opp.account.Spring_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Spring_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 1, 1);}
                    } else if (opp.term__c == 'Fall' && (opp.account.Academic_Calendar__c == 'Quarter' || opp.account.Academic_Calendar__c == 'Trimester'))  {
                        newOpp.Term__c = 'Spring';
                        if (opp.account.Spring_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Spring_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 3, 1);}
                    } else if (opp.term__c == 'Fall' && opp.account.Academic_Calendar__c == 'Semester')  {
                        newOpp.Term__c = 'Fall';
                        if (opp.account.Fall_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Fall_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 9, 1);}
                    } else if (opp.term__c == 'Spring' && (opp.account.Academic_Calendar__c == 'Quarter' || opp.account.Academic_Calendar__c == 'Trimester'))  {
                        newOpp.Term__c = 'Fall';
                        if (opp.account.Fall_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Fall_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year(), 9, 1);}
                    } else if ( opp.term__c == 'Summer' && (opp.account.Academic_Calendar__c == 'Quarter' || opp.account.Academic_Calendar__c == 'Trimester'))  {
                        newOpp.Term__c = 'Summer';
                        if (opp.account.Summer_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Summer_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 5, 1);}
                    } else if (( opp.term__c == 'Winter' && (opp.account.Academic_Calendar__c == 'Quarter' || opp.account.Academic_Calendar__c == 'Trimester')) || ( opp.term__c == 'Fall' && opp.account.Academic_Calendar__c == 'Trimester'))  {
                        newOpp.Term__c = 'Summer';
                        if (opp.account.Summer_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Summer_Course_Start_Date__c;
                        } else if (opp.closedate.month()==1 || opp.closedate.month()==2){
                        newOpp.CloseDate = date.newInstance(opp.CloseDate.Year(), 5, 1) ;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 5, 1) ;}
                    } else if (opp.term__c == 'Summer' && opp.account.Academic_Calendar__c == 'Semester') {
                        newOpp.Term__c = 'Summer';
                        if (opp.account.Summer_Course_Start_Date__c > opp.closedate){
                        newOpp.CloseDate = opp.account.Summer_Course_Start_Date__c;
                        } else {newopp.CloseDate = date.newInstance(opp.CloseDate.Year()+1, 5, 1) ;}
                    }
               }
                newOpp.Type = 'Renewal';
                newOpp.Name = opp.Name;
                newOpp.StageName = 'In Closing';
                newOpp.Roll_Manually__c = False;
                newOpp.Opportunity_Rolled__c = False;
                newOpp.Opportunity_Rolled_From__c = opp.ID;
                newOpportunities.add(newOpp);
                opp.Opportunity_Rolled__c = True;
                opportunitiesToUpdate.add(opp);
                
//          } catch (Exception e){
//              //ApexPages.addMessages(e);
//              opportunitiesToUpdate = new List<Opportunity>{};
//              newOpportunities = new List<Opportunity>{};
//              newOpportunityLineitems = new List<OpportunityLineItem>{};
//              newOpportunityContactRoles = new List<opportunitycontactrole>{};
//          }
    }}
    
    // setup the save point for rollback
    Savepoint sp = Database.setSavepoint();

//  try {
    
        insert newOpportunities;
        update opportunitiesToUpdate;
        
        Integer size = newOpportunities.size();
        
        for(Integer i = 0; i < size; i++){
            
            Opportunity opp = opportunitiesToUpdate.get(i);
            Opportunity newOpp = newOpportunities.get(i);
            
            List<OpportunityLineItem> lineItems = opp.OpportunityLineItems;
            //System.debug(lineItems.size=' + 'lineItems.size());
            for (OpportunityLineItem oli : lineItems) {
                 OpportunityLineItem newoli = oli.clone(false);
                 Decimal rounddown = oli.quantity *.8;
                    Decimal roundeddown = Rounddown.setScale(0, RoundingMode.DOWN);
                    system.debug(roundeddown);
                 Decimal roundup = oli.quantity *1.2;
                    Decimal roundedup = Roundup.setScale(0, RoundingMode.UP);
                    system.debug(roundedup);
                                                 
                    if ( oli.opportunity.term__c == 'Fall' && oli.opportunity.account.Academic_Calendar__c == 'Semester' && oli.opportunity.Term_Use__c=='Used Each Term'  ) {
                        newOli.Quantity = roundeddown;
                    } else if ( oli.opportunity.term__c == 'Spring' && oli.opportunity.account.Academic_Calendar__c == 'Semester' && oli.opportunity.Term_Use__c=='Used Each Term') {
                        newOli.Quantity = roundedup;
                    }
                 newoli.OpportunityID = newOpp.id;
                 newOpportunityLineitems.add(newoli);
            }
            
            List<opportunitycontactrole> roles = opp.opportunitycontactroles;
            //System.debug("roles.size=" + roles.size());
            for (opportunitycontactrole ocr : roles) {
                 opportunitycontactrole newocr = ocr.clone(false);
                 newocr.Opportunityid = newOpp.id;
                 newOpportunityContactRoles.add(newocr);
            }
        }

        
        insert newOpportunityLineitems;
        insert newopportunitycontactroles;


//  } catch (Exception e){
//      // roll everything back in case of error
//      Database.rollback(sp);
//      //ApexPages.addMessages(e);
//  }
}
I'm trying to do a popup alert that just lets people know that a record has been created when they do a certain action.  It's kind of an FYI thing.  So I tried a VF page embedded in the Opp layout and that worked but it showed up everytime they went to the record once it met the criteria.  So then I tried adding a controller to the page that would check a box saying that the alert was shown.  The controller works and checks the box but now the popup doesn't show.  Is there any way to get BOTH of these working as one solution?

Thanks so much!
Amanda

Here's the first VF page I tried which works to show the popup:
<apex:page standardcontroller="Opportunity" rendered="{!Opportunity.stagename=='Commitment' && Opportunity.Opportunity_Rolled__c==True && Opportunity.Alert_Shown__c==False}" >
  <script type="text/javascript">
  {
  window.alert("This Opportunity has Been Rolled to the next applicable Semester");
  }
  </script>
</apex:page>

And here's the second one I tried that will check the box but not actually show the alert.

<apex:page standardController="Opportunity" action="{!markread}" extensions="CloneAlertExtension">
<script type="text/javascript">
if({!Opportunity.stagename=='Commitment' && Opportunity.Opportunity_Rolled__c==True && Opportunity.Alert_Shown__c==False}) {
    window.alert("This Opportunity has Been Rolled to the next applicable Semester");
}
</script>
</apex:page>

public with sharing class CloneAlertExtension {
    ApexPages.StandardController controller;
    public CloneAlertExtension(ApexPages.StandardController controller) {
        this.controller = controller;
    }
    public void markread() {
        Opportunity o = (Opportunity)controller.getRecord();
        o.Alert_Shown__c = true;
        update o;
    }
}
I'm trying to write the test class on this trigger and have suddenly hit the System.LimitException.  Why is this hitting SOQL limits at line 3?  My starting line essentially.  It's part of a list so shouldn't that prevent the SOQL limit?

Thanks so much,
Amanda Howell

trigger CloneOpportunityRollover on Opportunity (after Insert, after Update) {
   
    List <Opportunity> opportunities = [select Id, Name, Type, LeadSource, Course_Type__c, Opportunity_Rolled__c, Opportunity_Rolled_From__c, AccountID, New_Subject__c, StageName, Term__c, CloseDate, Account.Academic_Term__c, Account.Winter_Course_Start_Date__c, Account.Spring_Course_Start_Date__c, Account.Summer_Course_Start_Date__c, Account.Fall_Course_Start_Date__c, (select Id, opportunity.term__c, opportunity.stagename, opportunity.course_type__c, opportunity.account.Academic_Term__c,unitprice, Quantity, PricebookEntryID, Description From OpportunityLineItems), (Select Id, Contactid, IsPrimary, Role From OpportunityContactRoles) from Opportunity where ID IN :Trigger.newMap.keySet()];
   
   
    List<Opportunity> opportunitiesToUpdate = new List<Opportunity>{};
    List<Opportunity> newOpportunities = new List<Opportunity>{};
    List<OpportunityLineItem> newOpportunityLineitems = new List<OpportunityLineItem>{};
    List<opportunitycontactrole> newOpportunityContactRoles = new List<opportunitycontactrole>{};


    for(Opportunity opp : opportunities){

        if (opp.StageName == 'Commitment' && Opp.Opportunity_Rolled__c == False) {
            Opportunity newOpp;
           
//          try {
           
                newOpp = opp.clone(false);
                if (Opp.StageName == 'Commitment' && Opp.Opportunity_Rolled__c == False && Opp.Course_Type__c == 'Standard') {
                               
                    if ( (opp.term__c == 'Fall' && (opp.account.Academic_Term__c == 'Semester' || opp.account.Academic_Term__c == 'Trimester' )) || (opp.term__c == 'Winter' && opp.account.Academic_Term__c == 'Quarter')) {
                        newOpp.Term__c = 'Spring';
                        newOpp.CloseDate = opp.account.Spring_Course_Start_Date__c;
                        newOpp.Name = opp.Name + ' Spring ' + opp.account.Spring_Course_Start_Date__c.year();
                    } else if ( (opp.term__c == 'Spring' && opp.account.Academic_Term__c == 'Semester') || (opp.term__c == 'Summer' && (opp.account.Academic_Term__c == 'Quarter' || opp.account.Academic_Term__c == 'Trimester')) )  {
                        newOpp.Term__c = 'Fall';
                        newOpp.CloseDate = opp.account.Fall_Course_Start_Date__c;
                        newOpp.Name = opp.Name + ' Fall ' + opp.account.Fall_Course_Start_Date__c.year();
                    } else if ( opp.term__c == 'Fall' && opp.account.Academic_Term__c == 'Quarter')  {
                        newOpp.Term__c = 'Winter';
                        newOpp.CloseDate = opp.account.Winter_Course_Start_Date__c;
                        newOpp.Name = opp.Name + ' Winter ' + opp.account.Winter_Course_Start_Date__c.year();
                    } else if ( opp.term__c == 'Spring' && (opp.account.Academic_Term__c == 'Quarter' || opp.account.Academic_Term__c == 'Trimester'))  {
                        newOpp.Term__c = 'Summer';
                        newOpp.CloseDate = opp.account.Summer_Course_Start_Date__c;
                        newOpp.Name = opp.Name + ' Summer ' + opp.account.Summer_Course_Start_Date__c.year();
                    }
                } else if (Opp.StageName == 'Commitment' && Opp.Opportunity_Rolled__c == False && Opp.Course_Type__c == 'Single Semester') {
                               
                    if ( (opp.term__c == 'Spring' && opp.account.Academic_Term__c == 'Semester') || ( opp.term__c == 'Summer' && opp.account.Academic_Term__c == 'Trimester') || (opp.term__c == 'Fall' && opp.account.Academic_Term__c == 'Quarter') ) {
                        newOpp.Term__c = 'Spring';
                        newOpp.CloseDate = opp.account.Spring_Course_Start_Date__c;
                        newOpp.Name = opp.Name + ' Spring ' + opp.account.Spring_Course_Start_Date__c.year();
                    } else if ( (opp.term__c == 'Fall' && opp.account.Academic_Term__c == 'Semester') || (opp.term__c == 'Spring' && (opp.account.Academic_Term__c == 'Quarter' || opp.account.Academic_Term__c == 'Trimester'))  )  {
                        newOpp.Term__c = 'Fall';
                        newOpp.CloseDate = opp.account.Fall_Course_Start_Date__c;
                        newOpp.Name = opp.Name + ' Fall ' + opp.account.Fall_Course_Start_Date__c.year();
                    } else if ( opp.term__c == 'Summer' && opp.account.Academic_Term__c == 'Quarter')  {
                        newOpp.Term__c = 'Winter';
                        newOpp.CloseDate = opp.account.Winter_Course_Start_Date__c;
                        newOpp.Name = opp.Name + ' Winter ' + opp.account.Winter_Course_Start_Date__c.year();
                    } else if (( opp.term__c == 'Winter' && opp.account.Academic_Term__c == 'Quarter') || ( opp.term__c == 'Fall' && opp.account.Academic_Term__c == 'Trimester'))  {
                        newOpp.Term__c = 'Summer';
                        newOpp.CloseDate = opp.account.Summer_Course_Start_Date__c;
                        newOpp.Name = opp.Name + ' Summer ' + opp.account.Summer_Course_Start_Date__c.year();
                    }
               }
                newOpp.Type = 'Renewal';
                newOpp.StageName = 'Prospecting';
                newOpp.Opportunity_Rolled__c = False;
                newOpp.Opportunity_Rolled_From__c = opp.ID;
                newOpportunities.add(newOpp);
                opp.Opportunity_Rolled__c = True;
                opportunitiesToUpdate.add(opp);
               
//          } catch (Exception e){
//              //ApexPages.addMessages(e);
//              opportunitiesToUpdate = new List<Opportunity>{};
//              newOpportunities = new List<Opportunity>{};
//              newOpportunityLineitems = new List<OpportunityLineItem>{};
//              newOpportunityContactRoles = new List<opportunitycontactrole>{};
//          }
    }}
   
    // setup the save point for rollback
    Savepoint sp = Database.setSavepoint();

//  try {
   
        insert newOpportunities;
        update opportunitiesToUpdate;
       
        Integer size = newOpportunities.size();
       
        for(Integer i = 0; i < size; i++){
           
            Opportunity opp = opportunitiesToUpdate.get(i);
            Opportunity newOpp = newOpportunities.get(i);
           
            List<OpportunityLineItem> lineItems = opp.OpportunityLineItems;
            //System.debug(lineItems.size=' + 'lineItems.size());
            for (OpportunityLineItem oli : lineItems) {
                 OpportunityLineItem newoli = oli.clone(false);
                 Decimal rounddown = oli.quantity *.8;
                    Decimal roundeddown = Rounddown.setScale(0, RoundingMode.DOWN);
                    system.debug(roundeddown);
                 Decimal roundup = oli.quantity *1.2;
                    Decimal roundedup = Roundup.setScale(0, RoundingMode.UP);
                    system.debug(roundedup);
                                                
                    if ( oli.opportunity.term__c == 'Fall' && oli.opportunity.account.Academic_Term__c == 'Semester' && oli.opportunity.course_type__c=='Standard' ) {
                        newOli.Quantity = roundeddown;
                    } else if ( oli.opportunity.term__c == 'Spring' && oli.opportunity.account.Academic_Term__c == 'Semester' && oli.opportunity.course_type__c=='Standard' )  {
                        newOli.Quantity = roundedup;
                    } else if ( oli.opportunity.term__c == 'Fall' && oli.opportunity.account.Academic_Term__c == 'Quarter' && oli.opportunity.course_type__c=='Standard' )  {
                        newOli.Quantity = roundeddown;
                    } else if ( oli.opportunity.term__c == 'Winter' && oli.opportunity.account.Academic_Term__c == 'Quarter' && oli.opportunity.course_type__c=='Standard' )  {
                        newOli.Quantity = roundeddown;
                    } else if ( oli.opportunity.term__c == 'Spring' && oli.opportunity.account.Academic_Term__c == 'Quarter' && oli.opportunity.course_type__c=='Standard' )  {
                        newOli.Quantity = roundeddown;
                    } else if ( oli.opportunity.term__c == 'Summer' && oli.opportunity.account.Academic_Term__c == 'Quarter' && oli.opportunity.course_type__c=='Standard' )  {
                        newOli.Quantity = roundedup;
                    } else if ( oli.opportunity.term__c == 'Fall' && oli.opportunity.account.Academic_Term__c == 'Trimester' && oli.opportunity.course_type__c=='Standard' )  {
                        newOli.Quantity = roundeddown;
                    } else if ( oli.opportunity.term__c == 'Spring' && oli.opportunity.account.Academic_Term__c == 'Trimester' && oli.opportunity.course_type__c=='Standard' )  {
                        newOli.Quantity = roundeddown;
                    } else if ( oli.opportunity.term__c == 'Summer' && oli.opportunity.account.Academic_Term__c == 'Trimester' && oli.opportunity.course_type__c=='Standard' )  {
                        newOli.Quantity = roundedup;
                    }
                 newoli.OpportunityID = newOpp.id;
                 newOpportunityLineitems.add(newoli);
            }
           
            List<opportunitycontactrole> roles = opp.opportunitycontactroles;
            //System.debug("roles.size=" + roles.size());
            for (opportunitycontactrole ocr : roles) {
                 opportunitycontactrole newocr = ocr.clone(false);
                 newocr.Opportunityid = newOpp.id;
                 newOpportunityContactRoles.add(newocr);
            }
        }

       
        insert newOpportunityLineitems;
        insert newopportunitycontactroles;


//  } catch (Exception e){
//      // roll everything back in case of error
//      Database.rollback(sp);
//      //ApexPages.addMessages(e);
//  }
}
I'm hitting the error that Initial term of field expression must be a concrete SObject: LIST<UserTerritory> at line 8 column 79 in my Test class.  I'm trying to call the list but apparently I'm doing something wrong.  Can someone please help me get the Territory ID out of the list of TerritoryUsers?

Thanks so much,
Amanda

@IsTest(SeeAllData=true)
public class TestOpportunityTerritory {

  static testMethod void testOpportunityTerritory() {
    user u = [select id from User where name = 'Will Culbertson'];
   
    List <UserTerritory> ut = [Select ut.UserId, ut.TerritoryId From UserTerritory ut Where ut.userId =:u.Id];
    List <Territory> t = [select t.id, t.name from Territory t where t.id IN :ut.territoryid];
    Account a = new Account(Name='Test Account');
        insert a;    
       
        test.startTest();
        System.RunAs(u){
       
        //Perform the dml action on which trigger gets fired , like insert, update ,delete , undelete, in your case you have to update the opportunity record that you created in above 
       Opportunity o = new Opportunity(Name='Test Opportunity',closedate=system.today(), stagename='Prospecting', AccountID=a.id, ownerid=u.id);
        insert o; 
       
        test.stopTest();
       
        for(Opportunity opp:[SELECT Territoryid FROM Opportunity
            WHERE CreatedDate = TODAY
            and CreatedById = :u.id])
       
       
        System.assertEquals(ut.TerritoryID, opp.territoryid);
}
}      
}