-
ChatterFeed
-
5Best Answers
-
2Likes Received
-
0Likes Given
-
29Questions
-
36Replies
Map of Opp ID and Contact Owner ID from Opp ID
So far, I have:
for (OpportunityContactRole OCR: [Select ContactId from OpportunityContactRole where OpportunityID in :newOpp and IsPrimary = TRUE]){
OppAndContact.put(OCR.id, OCR.contactId);
}
I'm kind of stuck now - is there a way I can get the map in one step?
-
- Gail
- January 14, 2019
- Like
- 0
- Continue reading or reply
Force paused flow interview to run in Apex Test?
-
- Gail
- November 10, 2015
- Like
- 0
- Continue reading or reply
What are the best practices for Salesforce Testing?
1) Maintainability - as rules are added and removed, this might be hard to maintain.
2) Test run time - this will add a LOT more tests to Salesforce so deployments may take some time.
I've also looked into Selenium but I don't really need to do UI testing - it's more functional testing and Apex tests will ensure test data is deleted.
Are there best practices for setting this up? Can anyone point me to documentation on this?
-
- Gail
- November 06, 2015
- Like
- 0
- Continue reading or reply
How do I assign multiselect picklist values to a collection variable in a flow?
-
- Gail
- October 30, 2014
- Like
- 0
- Continue reading or reply
Opportunity before update - trigger.new issue
List<Opportunity> oppsWithOLIs = [select id, IsWon, Assets_Created__c,(select id from OpportunityLineItems where
(product2.family = 'Subscription'or product2.family = 'Support'))
from Opportunity where Id in :Trigger.newMap.keySet()];
The problem is, my IsWon is returning as false when I'm changing the stage to a Won stage and returning as true when I'm change from a Won stage to an Open stage. I've tried using stagenames too and it keeps returning the old value. With Trigger.newMap, shouldn't it be returning the newly set value?
The other issue I'm running into is that in the for loop (for Opportunity o: oppsWithOLIs), I'm trying to set the opp value Assets_Created__c to true and this is not happening. However, the rest of the code where I do a for loop on the OLIs, add to a list and then outside of a loop add those to an apex class is running fine.
-
- Gail
- April 28, 2014
- Like
- 0
- Continue reading or reply
Custom Opportunity - Campaign Link
When to run the logic (the triggers):
- when contact role on opp is added, edited or deleted - add opp id to opportunity list
- when campaign member is created or deleted - query contact id for any opportunity contact roles, add opp id to opportunity list
The logic (apex class):
get list of opportunities (from the triggers)
cycle through each opportunity in the list and:
get list of all contact roles on opportunity
get set of all campaigns associated to contact roles on opportunity (contact-campaign set)
get list of all campaigns associated to opp (opp-campaign list)
cycle through opp-campaign list - if list item not in contact-campaign set, then add opp-campaign link id to remove_from_opp list
cycle through contact-campaign set - if set item not found in opp-campaign list, then add campaign id and opp id to add_to_opp list
delete all opp campaigns in remove_from_opp list
create new opp-campaign link for each campaign/opp id pair in add_to_opp list
-
- Gail
- April 04, 2014
- Like
- 0
- Continue reading or reply
Cannot filter using String.contains
public with sharing class AcctActivityList{
public Account acct {get; set;}
public List<ActivityHistory> ClosedTasks {get; set;}
string mail = 'mail';
public AcctActivityList(ApexPages.StandardController stdcontroller) {
//get account
acct = (Account)stdController.getRecord();
//get activity history - can't query activity history directly, just in a subquery against another object
SObject[] ActivityHistory = [Select id, (select Id, AccountId, Account.Name, ActivityDate, ActivityType, Description, OwnerId, Subject,
LastModifiedDate, IsTask, WhatId, WhoId from ActivityHistories where
(ActivityType !='Email' or Subject.contains('email')) ORDER by ActivityDate DESC)
from Account where Id =: acct.id];
ClosedTasks = (List<ActivityHistory>)ActivityHistory.get(0).getSObjects('ActivityHistories');
}
}
Why is my string.contains filter not working (i.e. why can't I save the code)?
When I try to save, I get the error: unexpected token: 'email'. The same is true if the filter is Subject.contains('email') == false.
I've seen this string class referenced various places around the web and it's still not working. I also tried reverting to API 27 (it was on 29) in case there was a bug in that API. No go.
-
- Gail
- March 17, 2014
- Like
- 0
- Continue reading or reply
ActivityHistory not displaying Related To on VF page
public with sharing class AcctActivityList{
public Account acct {get; set;}
public List<ActivityHistory> ClosedTasks {get; set;}
string mail = 'mail';
public AcctActivityList(ApexPages.StandardController stdcontroller) {
//get account
acct = (Account)stdController.getRecord();
//get activity history - can't query activity history directly, just in a subquery against another object
SObject[] ActivityHistory = [Select id, (select Id, AccountId, Account.Name, ActivityDate, ActivityType, Description, OwnerId, Subject,
LastModifiedDate, IsTask, WhatId, WhoId from ActivityHistories where
(ActivityType !='Email') ORDER by ActivityDate DESC)
from Account where Id =: acct.id];
ClosedTasks = (List<ActivityHistory>)ActivityHistory.get(0).getSObjects('ActivityHistories');
}
}
The vf page:
<apex:page standardcontroller="Account" extensions="AcctActivityList">
<apex:pageBlock title="Activity History">
<apex:pageBlockTable value="{!ClosedTasks}" var="ah" >
<apex:column headerValue="Subject">
<apex:outputLink value="/{!ah.id}">{!ah.Subject}</apex:outputlink>
</apex:column>
<apex:column headervalue="Name" value="{!ah.AccountId}"/>
<apex:column headervalue="Related To" value="{!ah.WhatId}"/>
<apex:column value="{!ah.IsTask}"/>
<apex:column headerValue="Due Date" value="{!ah.ActivityDate}"/>
<apex:column value="{!ah.OwnerId}"/>
<apex:column value="{!ah.LastModifiedDate}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
How do I get Related To to appear on the Visualforce page?
See where I refer to WhatId on the vf page? This results in the error "Content cannot be displayed: U#324.4ff (What): InvalidForeignKeyValue, 001f000000DQ9AyAAL" appearing on the page. Now, that "foreign key" is actually the account id of the account on which this is being displayed. That shouldn't be an issue tho - AccountId above it displays fine if I take out the reference to WhatId. I need to show Related To in the list - anyone know how I can do that?
-
- Gail
- March 17, 2014
- Like
- 0
- Continue reading or reply
mod formula issue - different results in report vs page layout (page layout is wrong)
I have opened a case with Salesforce but we all know how helpful that can be. Has anyone run into this in the past?
-
- Gail
- February 27, 2014
- Like
- 2
- Continue reading or reply
Upsert is creating duplicates rather than updating
Basically, I have a Add Product Page (thanks michaelforce.org for providing the base code) that has everything on one page.
The apex controller creates a list (shoppingCart) of the existing opportunity line items, as follows:
public opportunityLineItem[] shoppingCart {get;set;}
shoppingCart = [select Id, Quantity, UnitPrice, Budget__c, FlightEnd__c, CampaignName__c,
SpecialTerms__c, Targeting__c, PricingModel__c, DailyCap__c, Pacing__c, ServiceDate, Description, PriceBookEntryId,
PriceBookEntry.Name, PriceBookEntry.IsActive, PriceBookEntry.Product2Id, PriceBookEntry.Product2.Name,
PriceBookEntry.PriceBook2Id from opportunityLineItem where OpportunityId=:theOpp.Id];
//note: I have queried the opp prior to this...
The save function (which is duplicating every line item) is:
// method to delete any removed lines and add/update selected rows
public PageReference onSave(){
Savepoint sp = Database.setSavepoint();
try{
// If previously selected products are now removed, we need to delete them
if(forDeletion.size()>0)
delete(forDeletion);
// Previously selected products may have new quantities and amounts, and we may have new products listed, so we use upsert here
// if we have products, upsert them
if(shoppingCart.size()>0) {
// grab all OLIs and upsert them
List<OpportunityLineItem> olis = new List<OpportunityLineItem>();
for (OpportunityLineItem oli : shoppingCart) olis.add(oli);
upsert olis;
}
}
catch(Exception e){
Database.rollback(sp);
ApexPages.addMessages(e);
return null;
}
So, it seems like ID isn't getting added to the olis list? I tried upsert olis id; just for kicks but then got an error "field integrity exception: unknown (scheduling not enabled on product)". Then for fun, I tried update olis; and got the issue "id not specified in an update call". But didn't I specify the ids in the initial query for ShoppingCart (i.e. [select Id from OpportunityLineItem where...])
I also tried to create the shopping cart list a little differently:
(for OpportunityLineItem oli : [select Id, Quantity, UnitPrice, Budget__c, FlightEnd__c, CampaignName__c,
SpecialTerms__c, Targeting__c, PricingModel__c, DailyCap__c, Pacing__c, ServiceDate, Description, PriceBookEntryId,
PriceBookEntry.Name, PriceBookEntry.IsActive, PriceBookEntry.Product2Id, PriceBookEntry.Product2.Name,
PriceBookEntry.PriceBook2Id from opportunityLineItem where OpportunityId=:theOpp.Id]){
shoppingcart.add(oli) }
but then get an attempt to dereference a null object error when I open the page.
I ran this code and added system debugs and it's finding the opp but my system debug message that comes right after assigning to the shopping cart never does appear.
-
- Gail
- January 11, 2014
- Like
- 0
- Continue reading or reply
How can I find a value of a field in a field set?
if (fsMap.get(strProgram) != null){
for(Schema.FieldSetMember f : fsMap.get(strProgram).getFields()) {
TotalPreReqs += 1;
if(lead[f.getFieldPath()]== 'Yes'){
PreReqCount += 1;
}
}//end cycle through fieldset
}
-
- Gail
- December 30, 2014
- Like
- 0
- Continue reading or reply
KnowledgeArticleVersionStandardController - passing Data Categories
I am using an apex controller to pass Case data into an Article created from Case, as outlined at http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_pages_knowledgearticleversionstandardcontroller.htm. It's working fine EXCEPT for the lines passing Data Category to the article (the last two lines). I've ensured I have the proper Data Category Group name and I'm using a Data Category that actually exists in the Data Category Group but still no go. I suspect the apex controller example is missing lines of code to actually assign the Data Category to the Article?
-
- Gail
- November 27, 2013
- Like
- 0
- Continue reading or reply
Help bulkifying a trigger - too many SOQL queries when finding conversionrates
Here is a trigger I wrote. I understand that I need to get the conversion rate SOQL query out of the for statement:
trigger OpportunityBeforeInsertUpdate on Opportunity (before insert, before update) { for(Opportunity opp : Trigger.new) { if (opp.Total_Amount__c > 0) { opp.Amount = opp.Total_Amount__c; system.debug('opp amount is ' + opp.Amount); } if(Trigger.isInsert || ((opp.Amount != Trigger.oldMap.get(opp.Id).Amount || opp.CurrencyIsoCode != Trigger.oldMap.get(opp.Id).CurrencyIsoCode) && (!opp.IsClosed || (opp.IsClosed && !Trigger.oldMap.get(opp.Id).IsClosed))) || (!opp.IsClosed && Trigger.oldMap.get(opp.Id).IsClosed) ) { double conversionrate = [select conversionrate from CurrencyType where IsoCode = :opp.CurrencyIsoCode]; opp.Amount_USD__c = opp.Amount/ ConversionRate ; } } }
so I wrote the following but still get the Too many SOQL queries error when running a test where 200 opps are inserted:
trigger OpportunityBeforeInsertUpdate on Opportunity (before insert, before update) { List<CurrencyType> currs = new List<CurrencyType> ([select id, IsoCode, ConversionRate from CurrencyType where IsActive=true limit 200]); Map<String, Decimal> ConversionRates = new Map<String, Decimal>(); for(integer i=0; i<currs.size(); i++){ ConversionRates.put(currs[i].IsoCode, currs[i].ConversionRate); } for(Opportunity opp : Trigger.new) { if (opp.Total_Amount__c > 0) { opp.Amount = opp.Total_Amount__c; system.debug('opp amount is ' + opp.Amount); } if(Trigger.isInsert || ((opp.Amount != Trigger.oldMap.get(opp.Id).Amount || opp.CurrencyIsoCode != Trigger.oldMap.get(opp.Id).CurrencyIsoCode) && (!opp.IsClosed || (opp.IsClosed && !Trigger.oldMap.get(opp.Id).IsClosed))) || (!opp.IsClosed && Trigger.oldMap.get(opp.Id).IsClosed) ) { opp.Amount_USD__c = opp.Amount/ ConversionRates.get(opp.CurrencyIsoCode) ; } } }
-
- Gail
- July 04, 2013
- Like
- 0
- Continue reading or reply
Write test class for before delete trigger - deletion fails?
My trigger works fine when testing via the UI but when I try to delete an account via a test class, I get the error FATAL_ERROR|System.NullPointerException: Attempt to de-reference a null object.
trigger:
trigger AccountBeforeDelete on Account (before delete) { Set<Id> TerritoryUpd = new Set<Id>(); Set<Id> StratDeleted = new Set<Id>(); List<Account> ChildUpd = new List<Account>(); For (Account a : trigger.old){ If (a.Territory_Test__c.startsWith('STRAT')) { <--- this is the line that fails StratDeleted.add(a.id); } } ChildUpd = [SELECT Id FROM Account WHERE Ultimate_Parent_Acct__c in :StratDeleted]; For (Account aa : ChildUpd) { TerritoryUpd.add(aa.id); } If(!TerritoryUpd.isEmpty()){ Territory_Mgmt.Assign_Accounts(TerritoryUpd); } }
test class code snippet:
test.starttest(); insert up_strat; insert ch_strat; ch_strat.Ultimate_Parent_Acct__c = up_strat.Id; update ch_strat; Account up_strat_del = [Select id, Territory_Test__c FROM Account where ID = :up_strat.id]; delete up_strat_del; test.stoptest();
I used to try just deleting up_strat but saw something about querying for the inserted object and then deleting. That didn't work. When I put a try catch statement around the deletion, the deletion still failed with the same error. Why is my trigger not recognizing up_strat_del?
-
- Gail
- June 26, 2013
- Like
- 0
- Continue reading or reply
Test Class not updating opp?
I'm writing a test class for a trigger that runs on after insert or after update on Opps. My after insert test is working fine but I can't seem to get the update test to work.
// Create the new Opportunity record Account a = new Account(~sets fields~); Opportunity opp = new Opportunity(CurrencyIsoCode = 'EUR', License_Amount__c = double.valueOf('1000.00') ~sets other required fields~); insert opp; test.startTest(); opp.License_Amount__c = double.valueOf('2000.00'); update opp; test.stopTest(); //query the updated opp Opportunity oppRecordUpdated = [SELECT Amount_USD__c, Amount FROM Opportunity WHERE ID = :opp.ID]; // If the trigger works, then the opp's Amount_USD__c field should now be 2000 EUR converted to USD System.assertEquals(Math.roundtolong(oppRecordUpdated.Amount_USD__c), Math.roundtolong(oppRecordUpdated.Amount / EUR.ConversionRate)); } }
what's happening is Amount USD is not getting updated - the number returned is based on what happened on the insert, not on the update. When I check my code coverage on the trigger, it shows the update trigger as NOT having coverage. How do I ensure that update trigger is run? Thought I had it with the starttest statement but apparently not.
-
- Gail
- June 19, 2013
- Like
- 0
- Continue reading or reply
work on campaignmember with trigger
I'm writing a trigger that runs when a campaign member is added and gets a list of all lead ids if the campaign includes a boolean value. I don't know how to get the boolean value from the Campaign - all I know is I can say "cm.Campaign.Requires_Immediate_Response__c". Can anyone let me know how I should write the RIM = line (and maybe how I can use it in the IF statement rather than assigning the value to a boolean and then checking if it's true?
Thanks in advance for any assistance!
Gail
for (CampaignMember cm : Trigger.new) { RIM = Select [select Requires_Immediate_Response__c from Campaign] from cm; if (RIM == true && cm.LeadId != null) { ids.add(cm.LeadId); } }
-
- Gail
- June 17, 2013
- Like
- 0
- Continue reading or reply
Pass field name as a variable in getinstance
I have code that looks up a value in a custom field in a Custom Setting, kind of like below:
My_Custom_Setting__c.getInstance(a.Name).Custom_Field__c
Depending on some variable, "Custom_Field__c" could be one of 2 fields. I tried setting a string to the proper field name and then using that string in my get instance statement, kind of like below:
string custom_field;
if (something) {
string = 'Custom_Field_1__c';
}
else string = 'Custom_Field_2__c';
My_Custom_Setting__c.getInstance(a.Name).custom_field;
Of course, it looks for the field "custom_field" rather than replacing "custom_field" with "Custom_Field_1__c" or "Custom_Field_2__c". How do I get it to do what I want?
-
- Gail
- June 12, 2013
- Like
- 0
- Continue reading or reply
Find area code of a phone number?
I need to extract the area code from the Account Phone field. Luckily, I really only need the data on North American accounts, so I'm thinking I could remove all non-number fields and then extract characters depending on what it starts with (if 011, then char 4 to 6, if 1, then char 2 to 4, else char 1 to 3). That would catch most cases but I can't believe there isn't code already out there for doing this. I've been searching all over to no avail. Are there functions I'm unaware of that could help? Anyone know of a better way to do this?
-
- Gail
- June 12, 2013
- Like
- 0
- Continue reading or reply
test class for trigger failing - trigger not triggering or querying wrong variable?
I have a before insert and update trigger that updates two writeable fields in the account based on custom setting fields. When I test manually, the trigger works. However, my test code is failing. The account name is saving but the trigger to update continent and region doesn't seem to run. I added start test and stop test around inserting the accounts but that doesn't seem to help. How do I ensure the trigger runs and updates the account a3?
@isTest private class Test_AccountTrigger { static testMethod void test() { //create 2 accounts - billing country not in list, billing country in list Account a2 = new Account(); a2.Name = 'invalid country'; a2.billingcountry='alsdkfjasd;if'; a2.industry = 'Agency'; a2.Annual_company_revenue__c = 'under $100M'; Account a3 = new Account(); a3.Name = 'valid country'; a3.billingcountry='Germany'; a3.industry = 'Agency'; a3.Annual_company_revenue__c = 'under $100M'; Test.startTest(); insert a2; insert a3; Test.stopTest(); // Query the newly inserted records Account aa2 = [Select Name, Continent__c, Region1__c FROM Account where Id = :a2.Id]; Account aa3 = [Select Name, Continent__c, Region1__c FROM Account where Id = :a3.Id]; System.debug('aa2 ' + aa2.Name + ' continent = ' + aa2.Continent__c); System.debug('aa3 ' + aa3.Name + ' continent = ' + aa3.Continent__c); // If the trigger works, then territory and region will only be set on last account System.assertEquals(null, aa2.Continent__c); System.assertEquals(null, aa2.Region1__c); System.assertEquals('Europe',aa3.Continent__c); System.assertEquals('EMEA', aa3.Region1__c); } }
-
- Gail
- May 22, 2013
- Like
- 0
- Continue reading or reply
Data.com Clean button on list views
One of my users would like to see the Data.com Clean button (or a link to the same functionality) on the Accounts list view. Anyone know how I can accomplish this?
-
- Gail
- January 14, 2013
- Like
- 0
- Continue reading or reply
mod formula issue - different results in report vs page layout (page layout is wrong)
I have opened a case with Salesforce but we all know how helpful that can be. Has anyone run into this in the past?
-
- Gail
- February 27, 2014
- Like
- 2
- Continue reading or reply
Map of Opp ID and Contact Owner ID from Opp ID
So far, I have:
for (OpportunityContactRole OCR: [Select ContactId from OpportunityContactRole where OpportunityID in :newOpp and IsPrimary = TRUE]){
OppAndContact.put(OCR.id, OCR.contactId);
}
I'm kind of stuck now - is there a way I can get the map in one step?
- Gail
- January 14, 2019
- Like
- 0
- Continue reading or reply
What are the best practices for Salesforce Testing?
1) Maintainability - as rules are added and removed, this might be hard to maintain.
2) Test run time - this will add a LOT more tests to Salesforce so deployments may take some time.
I've also looked into Selenium but I don't really need to do UI testing - it's more functional testing and Apex tests will ensure test data is deleted.
Are there best practices for setting this up? Can anyone point me to documentation on this?
- Gail
- November 06, 2015
- Like
- 0
- Continue reading or reply
"Working with Custom Lightning Components" challenge not recognizing the app was created
I have completed the activity for "Working with Custom Lightning Components" I setup "My Domain", I installed the "Contacts Today" lightning component. Added the component to the "My Data" app which was created in the prior module and saved the changes. Upon checking it through the Trailhead. It says:
Challenge not yet complete... here's what's wrong:
The 'My Data' Lightning App was not found.
Any advice on what to do?
Thank you in advance.
- Justin Jarus 1
- October 21, 2015
- Like
- 2
- Continue reading or reply
How do I assign multiselect picklist values to a collection variable in a flow?
- Gail
- October 30, 2014
- Like
- 0
- Continue reading or reply
Opportunity before update - trigger.new issue
List<Opportunity> oppsWithOLIs = [select id, IsWon, Assets_Created__c,(select id from OpportunityLineItems where
(product2.family = 'Subscription'or product2.family = 'Support'))
from Opportunity where Id in :Trigger.newMap.keySet()];
The problem is, my IsWon is returning as false when I'm changing the stage to a Won stage and returning as true when I'm change from a Won stage to an Open stage. I've tried using stagenames too and it keeps returning the old value. With Trigger.newMap, shouldn't it be returning the newly set value?
The other issue I'm running into is that in the for loop (for Opportunity o: oppsWithOLIs), I'm trying to set the opp value Assets_Created__c to true and this is not happening. However, the rest of the code where I do a for loop on the OLIs, add to a list and then outside of a loop add those to an apex class is running fine.
- Gail
- April 28, 2014
- Like
- 0
- Continue reading or reply
Custom Opportunity - Campaign Link
When to run the logic (the triggers):
- when contact role on opp is added, edited or deleted - add opp id to opportunity list
- when campaign member is created or deleted - query contact id for any opportunity contact roles, add opp id to opportunity list
The logic (apex class):
get list of opportunities (from the triggers)
cycle through each opportunity in the list and:
get list of all contact roles on opportunity
get set of all campaigns associated to contact roles on opportunity (contact-campaign set)
get list of all campaigns associated to opp (opp-campaign list)
cycle through opp-campaign list - if list item not in contact-campaign set, then add opp-campaign link id to remove_from_opp list
cycle through contact-campaign set - if set item not found in opp-campaign list, then add campaign id and opp id to add_to_opp list
delete all opp campaigns in remove_from_opp list
create new opp-campaign link for each campaign/opp id pair in add_to_opp list
- Gail
- April 04, 2014
- Like
- 0
- Continue reading or reply
Cannot filter using String.contains
public with sharing class AcctActivityList{
public Account acct {get; set;}
public List<ActivityHistory> ClosedTasks {get; set;}
string mail = 'mail';
public AcctActivityList(ApexPages.StandardController stdcontroller) {
//get account
acct = (Account)stdController.getRecord();
//get activity history - can't query activity history directly, just in a subquery against another object
SObject[] ActivityHistory = [Select id, (select Id, AccountId, Account.Name, ActivityDate, ActivityType, Description, OwnerId, Subject,
LastModifiedDate, IsTask, WhatId, WhoId from ActivityHistories where
(ActivityType !='Email' or Subject.contains('email')) ORDER by ActivityDate DESC)
from Account where Id =: acct.id];
ClosedTasks = (List<ActivityHistory>)ActivityHistory.get(0).getSObjects('ActivityHistories');
}
}
Why is my string.contains filter not working (i.e. why can't I save the code)?
When I try to save, I get the error: unexpected token: 'email'. The same is true if the filter is Subject.contains('email') == false.
I've seen this string class referenced various places around the web and it's still not working. I also tried reverting to API 27 (it was on 29) in case there was a bug in that API. No go.
- Gail
- March 17, 2014
- Like
- 0
- Continue reading or reply
mod formula issue - different results in report vs page layout (page layout is wrong)
I have opened a case with Salesforce but we all know how helpful that can be. Has anyone run into this in the past?
- Gail
- February 27, 2014
- Like
- 2
- Continue reading or reply
Upsert is creating duplicates rather than updating
Basically, I have a Add Product Page (thanks michaelforce.org for providing the base code) that has everything on one page.
The apex controller creates a list (shoppingCart) of the existing opportunity line items, as follows:
public opportunityLineItem[] shoppingCart {get;set;}
shoppingCart = [select Id, Quantity, UnitPrice, Budget__c, FlightEnd__c, CampaignName__c,
SpecialTerms__c, Targeting__c, PricingModel__c, DailyCap__c, Pacing__c, ServiceDate, Description, PriceBookEntryId,
PriceBookEntry.Name, PriceBookEntry.IsActive, PriceBookEntry.Product2Id, PriceBookEntry.Product2.Name,
PriceBookEntry.PriceBook2Id from opportunityLineItem where OpportunityId=:theOpp.Id];
//note: I have queried the opp prior to this...
The save function (which is duplicating every line item) is:
// method to delete any removed lines and add/update selected rows
public PageReference onSave(){
Savepoint sp = Database.setSavepoint();
try{
// If previously selected products are now removed, we need to delete them
if(forDeletion.size()>0)
delete(forDeletion);
// Previously selected products may have new quantities and amounts, and we may have new products listed, so we use upsert here
// if we have products, upsert them
if(shoppingCart.size()>0) {
// grab all OLIs and upsert them
List<OpportunityLineItem> olis = new List<OpportunityLineItem>();
for (OpportunityLineItem oli : shoppingCart) olis.add(oli);
upsert olis;
}
}
catch(Exception e){
Database.rollback(sp);
ApexPages.addMessages(e);
return null;
}
So, it seems like ID isn't getting added to the olis list? I tried upsert olis id; just for kicks but then got an error "field integrity exception: unknown (scheduling not enabled on product)". Then for fun, I tried update olis; and got the issue "id not specified in an update call". But didn't I specify the ids in the initial query for ShoppingCart (i.e. [select Id from OpportunityLineItem where...])
I also tried to create the shopping cart list a little differently:
(for OpportunityLineItem oli : [select Id, Quantity, UnitPrice, Budget__c, FlightEnd__c, CampaignName__c,
SpecialTerms__c, Targeting__c, PricingModel__c, DailyCap__c, Pacing__c, ServiceDate, Description, PriceBookEntryId,
PriceBookEntry.Name, PriceBookEntry.IsActive, PriceBookEntry.Product2Id, PriceBookEntry.Product2.Name,
PriceBookEntry.PriceBook2Id from opportunityLineItem where OpportunityId=:theOpp.Id]){
shoppingcart.add(oli) }
but then get an attempt to dereference a null object error when I open the page.
I ran this code and added system debugs and it's finding the opp but my system debug message that comes right after assigning to the shopping cart never does appear.
- Gail
- January 11, 2014
- Like
- 0
- Continue reading or reply
How can I find a value of a field in a field set?
if (fsMap.get(strProgram) != null){
for(Schema.FieldSetMember f : fsMap.get(strProgram).getFields()) {
TotalPreReqs += 1;
if(lead[f.getFieldPath()]== 'Yes'){
PreReqCount += 1;
}
}//end cycle through fieldset
}
- Gail
- December 30, 2014
- Like
- 0
- Continue reading or reply
Write test class for before delete trigger - deletion fails?
My trigger works fine when testing via the UI but when I try to delete an account via a test class, I get the error FATAL_ERROR|System.NullPointerException: Attempt to de-reference a null object.
trigger:
trigger AccountBeforeDelete on Account (before delete) { Set<Id> TerritoryUpd = new Set<Id>(); Set<Id> StratDeleted = new Set<Id>(); List<Account> ChildUpd = new List<Account>(); For (Account a : trigger.old){ If (a.Territory_Test__c.startsWith('STRAT')) { <--- this is the line that fails StratDeleted.add(a.id); } } ChildUpd = [SELECT Id FROM Account WHERE Ultimate_Parent_Acct__c in :StratDeleted]; For (Account aa : ChildUpd) { TerritoryUpd.add(aa.id); } If(!TerritoryUpd.isEmpty()){ Territory_Mgmt.Assign_Accounts(TerritoryUpd); } }
test class code snippet:
test.starttest(); insert up_strat; insert ch_strat; ch_strat.Ultimate_Parent_Acct__c = up_strat.Id; update ch_strat; Account up_strat_del = [Select id, Territory_Test__c FROM Account where ID = :up_strat.id]; delete up_strat_del; test.stoptest();
I used to try just deleting up_strat but saw something about querying for the inserted object and then deleting. That didn't work. When I put a try catch statement around the deletion, the deletion still failed with the same error. Why is my trigger not recognizing up_strat_del?
- Gail
- June 26, 2013
- Like
- 0
- Continue reading or reply
Test Class not updating opp?
I'm writing a test class for a trigger that runs on after insert or after update on Opps. My after insert test is working fine but I can't seem to get the update test to work.
// Create the new Opportunity record Account a = new Account(~sets fields~); Opportunity opp = new Opportunity(CurrencyIsoCode = 'EUR', License_Amount__c = double.valueOf('1000.00') ~sets other required fields~); insert opp; test.startTest(); opp.License_Amount__c = double.valueOf('2000.00'); update opp; test.stopTest(); //query the updated opp Opportunity oppRecordUpdated = [SELECT Amount_USD__c, Amount FROM Opportunity WHERE ID = :opp.ID]; // If the trigger works, then the opp's Amount_USD__c field should now be 2000 EUR converted to USD System.assertEquals(Math.roundtolong(oppRecordUpdated.Amount_USD__c), Math.roundtolong(oppRecordUpdated.Amount / EUR.ConversionRate)); } }
what's happening is Amount USD is not getting updated - the number returned is based on what happened on the insert, not on the update. When I check my code coverage on the trigger, it shows the update trigger as NOT having coverage. How do I ensure that update trigger is run? Thought I had it with the starttest statement but apparently not.
- Gail
- June 19, 2013
- Like
- 0
- Continue reading or reply
Pass field name as a variable in getinstance
I have code that looks up a value in a custom field in a Custom Setting, kind of like below:
My_Custom_Setting__c.getInstance(a.Name).Custom_Field__c
Depending on some variable, "Custom_Field__c" could be one of 2 fields. I tried setting a string to the proper field name and then using that string in my get instance statement, kind of like below:
string custom_field;
if (something) {
string = 'Custom_Field_1__c';
}
else string = 'Custom_Field_2__c';
My_Custom_Setting__c.getInstance(a.Name).custom_field;
Of course, it looks for the field "custom_field" rather than replacing "custom_field" with "Custom_Field_1__c" or "Custom_Field_2__c". How do I get it to do what I want?
- Gail
- June 12, 2013
- Like
- 0
- Continue reading or reply
Find area code of a phone number?
I need to extract the area code from the Account Phone field. Luckily, I really only need the data on North American accounts, so I'm thinking I could remove all non-number fields and then extract characters depending on what it starts with (if 011, then char 4 to 6, if 1, then char 2 to 4, else char 1 to 3). That would catch most cases but I can't believe there isn't code already out there for doing this. I've been searching all over to no avail. Are there functions I'm unaware of that could help? Anyone know of a better way to do this?
- Gail
- June 12, 2013
- Like
- 0
- Continue reading or reply
test class for trigger failing - trigger not triggering or querying wrong variable?
I have a before insert and update trigger that updates two writeable fields in the account based on custom setting fields. When I test manually, the trigger works. However, my test code is failing. The account name is saving but the trigger to update continent and region doesn't seem to run. I added start test and stop test around inserting the accounts but that doesn't seem to help. How do I ensure the trigger runs and updates the account a3?
@isTest private class Test_AccountTrigger { static testMethod void test() { //create 2 accounts - billing country not in list, billing country in list Account a2 = new Account(); a2.Name = 'invalid country'; a2.billingcountry='alsdkfjasd;if'; a2.industry = 'Agency'; a2.Annual_company_revenue__c = 'under $100M'; Account a3 = new Account(); a3.Name = 'valid country'; a3.billingcountry='Germany'; a3.industry = 'Agency'; a3.Annual_company_revenue__c = 'under $100M'; Test.startTest(); insert a2; insert a3; Test.stopTest(); // Query the newly inserted records Account aa2 = [Select Name, Continent__c, Region1__c FROM Account where Id = :a2.Id]; Account aa3 = [Select Name, Continent__c, Region1__c FROM Account where Id = :a3.Id]; System.debug('aa2 ' + aa2.Name + ' continent = ' + aa2.Continent__c); System.debug('aa3 ' + aa3.Name + ' continent = ' + aa3.Continent__c); // If the trigger works, then territory and region will only be set on last account System.assertEquals(null, aa2.Continent__c); System.assertEquals(null, aa2.Region1__c); System.assertEquals('Europe',aa3.Continent__c); System.assertEquals('EMEA', aa3.Region1__c); } }
- Gail
- May 22, 2013
- Like
- 0
- Continue reading or reply