-
ChatterFeed
-
4Best Answers
-
0Likes Received
-
0Likes Given
-
69Questions
-
137Replies
VisualForce Page not invoking class method
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
- SFDCDevQA
- November 28, 2015
- Like
- 0
Error CPU Time Limit Exceeded
Thanks,
Amanda
- SFDCDevQA
- November 12, 2015
- Like
- 0
Contains method on child to parent relationship query
Thanks,
Amanda
List<userterritory2association> userTerritoryAssociations = [
Select id, UserID, territory2Id, RoleInTerritory2, Territory2.Territory2Type.Priority, Territory2.Territory2Type.MasterLabel from userterritory2association Where Territory2.Territory2Type.MasterLabel.contains( 'HSS' )
];
- SFDCDevQA
- October 14, 2015
- Like
- 0
Navigating Across multiple Lists and Maps and entering Map Values as String
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;
}
}
}
}
- SFDCDevQA
- August 25, 2015
- Like
- 0
Bulking Test Class
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();
}
- SFDCDevQA
- August 21, 2015
- Like
- 0
Querying Territories on Account record
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());
}
}
}
- SFDCDevQA
- August 20, 2015
- Like
- 0
Null Reference Error on Upload Only but not every time
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;
}
}
- SFDCDevQA
- May 20, 2015
- Like
- 0
Null Reference Error only on upload
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;
}
}
- SFDCDevQA
- April 30, 2015
- Like
- 0
Savepoints and Cancel
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
- SFDCDevQA
- March 11, 2015
- Like
- 0
VF Error System Null Pointer Exception OR Compile Error: Non-void method might not return a value or might have statement after a return statement
"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
- SFDCDevQA
- March 10, 2015
- Like
- 0
Open new opportunity when lead is converted
Thanks,
Amanda
- SFDCDevQA
- November 24, 2014
- Like
- 0
System.LimitException: Too many SOQL queries: 101
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);
// }
}
- SFDCDevQA
- October 21, 2014
- Like
- 0
Turn off Pop Up Alert
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;
}
}
- SFDCDevQA
- September 12, 2014
- Like
- 0
System.LimitException: Too many SOQL queries: 101
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);
// }
}
- SFDCDevQA
- August 15, 2014
- Like
- 0
Initial term of field expression must be a concrete SObject
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);
}
}
}
- SFDCDevQA
- August 07, 2014
- Like
- 0
Unknown property 'VisualforceArrayList.CloseDate'
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');
}
}
- SFDCDevQA
- April 23, 2014
- Like
- 0
Error: Unknown property 'VisualforceArrayList.CloseDate'
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');
}
}
- SFDCDevQA
- April 23, 2014
- Like
- 0
Test class not asserting properly - despite manual testing working perfectly
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);
}
}
}
- SFDCDevQA
- August 30, 2013
- Like
- 0
Constructor Not Defined error in test class
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
- SFDCDevQA
- August 22, 2013
- Like
- 0
Test Class not working - assertion fails
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
- SFDCDevQA
- August 22, 2013
- Like
- 0
VisualForce Page not invoking class method
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
- SFDCDevQA
- November 28, 2015
- Like
- 0
Navigating Across multiple Lists and Maps and entering Map Values as String
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;
}
}
}
}
- SFDCDevQA
- August 25, 2015
- Like
- 0
Bulking Test Class
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();
}
- SFDCDevQA
- August 21, 2015
- Like
- 0
Querying Territories on Account record
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());
}
}
}
- SFDCDevQA
- August 20, 2015
- Like
- 0
Null Reference Error only on upload
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;
}
}
- SFDCDevQA
- April 30, 2015
- Like
- 0
VF Error System Null Pointer Exception OR Compile Error: Non-void method might not return a value or might have statement after a return statement
"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
- SFDCDevQA
- March 10, 2015
- Like
- 0
Open new opportunity when lead is converted
Thanks,
Amanda
- SFDCDevQA
- November 24, 2014
- Like
- 0
System.LimitException: Too many SOQL queries: 101
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);
// }
}
- SFDCDevQA
- October 21, 2014
- Like
- 0
Turn off Pop Up Alert
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;
}
}
- SFDCDevQA
- September 12, 2014
- Like
- 0
System.LimitException: Too many SOQL queries: 101
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);
// }
}
- SFDCDevQA
- August 15, 2014
- Like
- 0
Initial term of field expression must be a concrete SObject
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);
}
}
}
- SFDCDevQA
- August 07, 2014
- Like
- 0