-
ChatterFeed
-
0Best Answers
-
0Likes Received
-
0Likes Given
-
21Questions
-
60Replies
Help with Test Class not passing (List Has No Rows For Assignment)
I am in need of some great support form one of you Awesome Salesforce Guru's!
I have a Apex Controller that I am using as an extension on a VF page to handle incoming attachments and populate a look up field when the record is created from the VF page.
I can not get the test class to not fail for the following reason System.QueryException: List has no rows for assignment to SObject and the stack trace is - Class.backlogAttachment.getReleaseMethod1: line 20, column 1
Class.backlogAttachment.<init>: line 12, column 1
Class.backlogAttachmentTest.backlogAttachmentTestMethod: line 10, column 1
Here is my controller class and Test class...can you please help me figure out why thsi is failing and what to do to fix it? You woudl be a hge saviour here as I am new to apex but am trying my hardest! Thanks in advance...
Shawn
Controller Extension:
Test Class that is failing:
I have a Apex Controller that I am using as an extension on a VF page to handle incoming attachments and populate a look up field when the record is created from the VF page.
I can not get the test class to not fail for the following reason System.QueryException: List has no rows for assignment to SObject and the stack trace is - Class.backlogAttachment.getReleaseMethod1: line 20, column 1
Class.backlogAttachment.<init>: line 12, column 1
Class.backlogAttachmentTest.backlogAttachmentTestMethod: line 10, column 1
Here is my controller class and Test class...can you please help me figure out why thsi is failing and what to do to fix it? You woudl be a hge saviour here as I am new to apex but am trying my hardest! Thanks in advance...
Shawn
Controller Extension:
public with sharing class backlogAttachment { public blob getfile{get;set;} public attachment objAttachment{get;set;} public Backlog__c objcase{get;set;} public string filename{get;set;} public backlogAttachment(apexpages.standardcontroller controller) { objcase = new Backlog__c(); objAttachment = new Attachment(); Scheduled_Releases__c sr = getReleaseMethod1(); objcase.Scheduled_Release__c = sr.Id; } Scheduled_Releases__c s; public Scheduled_Releases__c getReleaseMethod1(){ if(s == null) s=[SELECT Id, Name FROM Scheduled_Releases__c WHERE Name ='Software Enhancement Request (Default)' LIMIT 1]; return s; } Public PageReference saveBacklog() { try{ insert objcase; } catch(DMLException e) { ApexPages.addMessages(e); } if(filename != null && fileName.trim().length()>0 && getfile != null) { //objAttachment = new Attachment(); Integer i=0; objAttachment.clear(); objAttachment.body = getfile; objAttachment.ParentId = objcase.Id; objAttachment.name = this.filename; try{ insert objAttachment; }catch(Exception e){ system.debug(e); } } pagereference pr = new pagereference('/'+objcase.id); return pr; } }
Test Class that is failing:
@isTest public class backlogAttachmentTest { static testMethod void backlogAttachmentTestMethod() { List<Scheduled_Releases__c> re = [SELECT Id FROM Scheduled_Releases__c WHERE Id = 'a3l4B000000CiGw' LIMIT 1]; Backlog__c temprec = new Backlog__c(); ApexPages.StandardController cs = new ApexPages.StandardController(temprec); backlogAttachment controller = new backlogAttachment(cs); controller.getfile = Blob.valueof('Test Data'); controller.filename = 'TestFieName'; controller.objcase.Scheduled_Release__c = re[0].Id; test.startTest(); controller.saveBacklog(); test.StopTest(); } }
- Shawn Reichner
- March 24, 2017
- Like
- 0
Capturing attachment on Visualforce page
Hoping that one of you awesome Salesforce experts can help me with the following issue I am having.
I have an force.com Site which has a VisualForce page which should open a custom object record on Salesforce. I also have a need to have an attachment added to this VF page to then be attached to the new record being created upon the user pressing save.
Here is what I am seeign so far, if I do not include the Controller extension, the record gets created just fine, but when I have the extension added to the VF page, no record is created.
I am new to apex, so hoping that someone can look over my code below and provide a solution to my frustration :)
Thank you
Shawn
VF Page Code -
First Extention to pass ID of another custom object record and populate a lookup field when record is created.
And lastly, the second controller extension for handling the attachment.
PLEASE HELP!!!!
I have an force.com Site which has a VisualForce page which should open a custom object record on Salesforce. I also have a need to have an attachment added to this VF page to then be attached to the new record being created upon the user pressing save.
Here is what I am seeign so far, if I do not include the Controller extension, the record gets created just fine, but when I have the extension added to the VF page, no record is created.
I am new to apex, so hoping that someone can look over my code below and provide a solution to my frustration :)
Thank you
Shawn
VF Page Code -
<apex:page standardcontroller="Backlog__c" extensions="backlogAttachment,PopulateSchedRelease" showHeader="true"> <img src="{!$resource.AVISPL_Logo2}"></img><b/><b/> <apex:form > <apex:pageBlock > <apex:pageBlockSection title="Software Enhancement Request" columns="1" showHeader="True" collapsible="False"> </apex:pageBlockSection> </apex:pageBlock> <apex:pageMessages /> <apex:pageBlock > <apex:inputField value="{!objcase.Name}"/> <apex:pageBlockSection title="Request/Requestor Information"> <apex:inputfield value="{!objcase.SER_Requestor__c}" required="True"/> <apex:inputfield value="{!objcase.Priority__c}" required="True"/> <apex:inputField value="{!objcase.SER_Requestor_email__c}" required="True"/> <apex:inputfield value="{!objcase.Stakeholder__c}" required="True"/> <apex:inputField value="{!objcase.Requestor_GL_Code__c}"/> <apex:inputfield value="{!objcase.Executive_Sponsor__c}"/> </apex:pageBlockSection> <apex:pageBlockSection title="Impact of Request"> <apex:inputField value="{!objcase.SER_Category__c}" required="True"/> <apex:inputField value="{!objcase.SER_Sub_Category__c}"/> <apex:inputField value="{!objcase.SER_Designation__c}" required="True"/> <apex:inputField value="{!objcase.Number_of_Users_Affected__c}" required="True"/> <br/> </apex:pageBlockSection> <apex:pageBlockSection title="Request Description Information"> <apex:inputField value="{!objcase.Summary__c}" required="True"/> <apex:inputField value="{!objcase.Reason__c}" required="True"/> <apex:inputField value="{!objcase.Description__c}" required="True"/> <apex:inputField value="{!objcase.Benefit__c}" required="True"/> <br/> </apex:pageBlockSection> <apex:pageBlockSection title="Deadlines and Project Status"> <apex:inputField value="{!objcase.Training_Requirements__c}" required="True"/> <apex:inputField value="{!objcase.Target_Deadline__c}" required="True"/> <apex:inputField value="{!objcase.SOP_Requirements__c}" required="True"/> <apex:inputField value="{!objcase.List_All_U_A_T_Participants__c}" required="True"/> <apex:inputField value="{!objcase.SER_Scheduled_Release__c}"/> <apex:inputField value="{!objcase.Scheduled_Release__c}" rendered="False"/> <br/> </apex:pageBlockSection> <apex:pageBlock title="Upload Attachment"> <apex:inputFile style="width:100%" id="fileToUpload" value="{!objAttachment.Body}" filename="{!objAttachment.Name}" /> </apex:pageBlock> <apex:commandButton value="Submit Request" action="{!saveBacklog}" /> </apex:pageBlock> </apex:form> </apex:page>
First Extention to pass ID of another custom object record and populate a lookup field when record is created.
public class PopulateSchedRelease { public Backlog__c bl; public PopulateSchedRelease(ApexPages.StandardController controller) { this.bl = (Backlog__c)controller.getRecord(); Scheduled_Releases__c sr = getReleaseMethod1(); bl.Scheduled_Release__c = sr.Id; } Scheduled_Releases__c s; public Scheduled_Releases__c getReleaseMethod1() { if(s == null) s = [SELECT Id, Name FROM Scheduled_Releases__c WHERE Name = 'Software Enhancement Request (Default)' LIMIT 1]; return s; } }
And lastly, the second controller extension for handling the attachment.
public class backlogAttachment { public blob getfile{get;set;} public attachment objAttachment{get;set;} public Backlog__c objcase{get;set;} public string filename{get;set;} public backlogAttachment(apexpages.standardcontroller stdCon) { objcase = new Backlog__c(); objAttachment = new Attachment(); } Public PageReference saveBacklog() { insert objcase; objAttachment.body = getfile; objAttachment.ParentId = objcase.Id; objAttachment.name = filename; insert objAttachment; return ApexPages.currentPage(); } }
PLEASE HELP!!!!
- Shawn Reichner
- March 24, 2017
- Like
- 0
SOQL 101 Error Help Please
Thank you for any insight and for spending a few minutes to look over the following code. I am fairly new to apex and I am having issues getting this trigger to run in a batch scenario. I am constantly getting SOQL 101 Govenor Limit error and can not figure out how to properly "Bulkify" this code.
Hoping someone can help out with some advice....Thanks in advance!!!!
The error is showing as hittong the limit from line 27...
Trigger Code:
1. trigger InstallProdDuplicatePreventer on AVISPL_Client_Product__c (before insert, before update) {
2.
3. //They can have the same name provided they have different record types
4.
5. Map<String, AVISPL_Client_Product__c> IPMap = new Map<String, AVISPL_Client_Product__c>();
6. Set<String> ipNameAndRecordTypeIdConcatSet = new Set<String>();
7. for (AVISPL_Client_Product__c IP : System.Trigger.new) {
8. If(IP.Virtual_Product__c == false){
9. String ipNameAndRecordTypeId = IP.name + '' + IP.recordTypeId;
10.
11. // Make sure we don't treat a name that isn't changing during an update as a duplicate.
12. if ((IP.Name != null) &&
13. (System.Trigger.isInsert ||
14. IP.Name != System.Trigger.oldMap.get(IP.Id).Name)) {
15.
16. // Make sure another new Installed Product isn't also a duplicate
17. if (IPMap.containsKey(IP.Name) && ipNameAndRecordTypeIdConcatSet.contains(ipNameAndRecordTypeId)) {
18. IP.Name.addError('Another new Installed Product has the same Name for this Record Type.');
19. } else {
20. IPMap.put(IP.Name, IP);
21. ipNameAndRecordTypeIdConcatSet.add(ipNameAndRecordTypeId);
22. }
23. }
24. }
25.
26. // Using a single database query, find all the Installed Products in the database that have the same name as any of the Installed Products being inserted or updated.
27. for (AVISPL_Client_Product__c Ip2 : [SELECT Name, RecordTypeId FROM AVISPL_Client_Product__c WHERE Name IN :IPMap.KeySet()]) {
28. AVISPL_Client_Product__c newIP = IPMap.get(IP2.Name);
29. String ipNameAndRecordTypeId = Ip2.name + '' + Ip2.recordTypeId;
30.
31. if(ipNameAndRecordTypeIdConcatSet.contains(ipNameAndRecordTypeId)) {
32. newIP.Name.addError('A Installed Product with this name already exists for this Record Type.');
33. }
34. }
35. }
36.}
Hoping someone can help out with some advice....Thanks in advance!!!!
The error is showing as hittong the limit from line 27...
Trigger Code:
1. trigger InstallProdDuplicatePreventer on AVISPL_Client_Product__c (before insert, before update) {
2.
3. //They can have the same name provided they have different record types
4.
5. Map<String, AVISPL_Client_Product__c> IPMap = new Map<String, AVISPL_Client_Product__c>();
6. Set<String> ipNameAndRecordTypeIdConcatSet = new Set<String>();
7. for (AVISPL_Client_Product__c IP : System.Trigger.new) {
8. If(IP.Virtual_Product__c == false){
9. String ipNameAndRecordTypeId = IP.name + '' + IP.recordTypeId;
10.
11. // Make sure we don't treat a name that isn't changing during an update as a duplicate.
12. if ((IP.Name != null) &&
13. (System.Trigger.isInsert ||
14. IP.Name != System.Trigger.oldMap.get(IP.Id).Name)) {
15.
16. // Make sure another new Installed Product isn't also a duplicate
17. if (IPMap.containsKey(IP.Name) && ipNameAndRecordTypeIdConcatSet.contains(ipNameAndRecordTypeId)) {
18. IP.Name.addError('Another new Installed Product has the same Name for this Record Type.');
19. } else {
20. IPMap.put(IP.Name, IP);
21. ipNameAndRecordTypeIdConcatSet.add(ipNameAndRecordTypeId);
22. }
23. }
24. }
25.
26. // Using a single database query, find all the Installed Products in the database that have the same name as any of the Installed Products being inserted or updated.
27. for (AVISPL_Client_Product__c Ip2 : [SELECT Name, RecordTypeId FROM AVISPL_Client_Product__c WHERE Name IN :IPMap.KeySet()]) {
28. AVISPL_Client_Product__c newIP = IPMap.get(IP2.Name);
29. String ipNameAndRecordTypeId = Ip2.name + '' + Ip2.recordTypeId;
30.
31. if(ipNameAndRecordTypeIdConcatSet.contains(ipNameAndRecordTypeId)) {
32. newIP.Name.addError('A Installed Product with this name already exists for this Record Type.');
33. }
34. }
35. }
36.}
- Shawn Reichner
- March 17, 2017
- Like
- 0
Help With Regex Formula FIeld
Hello,
I am fairly nwe to the RegEx game and am struggling with the formula needed to extract some text between the first and second / in a string field. I want to extract the text between the first and second / in the string to then populate a new formula field.
Here is an example of the string itself that I need to extract info from.... Can anyone please help?
Auto Launch Failed / Open Space Linda / Nashua, NH / AVI Development
So in the example above I want to populate my new formula field with only "Open Space Linda"
Hope that makes sense and someone can help me out here.....Thanks in advance
Shawn
I am fairly nwe to the RegEx game and am struggling with the formula needed to extract some text between the first and second / in a string field. I want to extract the text between the first and second / in the string to then populate a new formula field.
Here is an example of the string itself that I need to extract info from.... Can anyone please help?
Auto Launch Failed / Open Space Linda / Nashua, NH / AVI Development
So in the example above I want to populate my new formula field with only "Open Space Linda"
Hope that makes sense and someone can help me out here.....Thanks in advance
Shawn
- Shawn Reichner
- March 15, 2017
- Like
- 0
Visualforce Page On Site Not Showing Validation Rule Message when Case is submitted
Hello, I have an exposed Site with a basic Visualforce page using the standard case controller with an Extension to handle an Attachment upload. All works great however I just added a new Validation rule to the Case Object where the BKR Job field needs to be in a certain format in order to allow the case to save. The format the field is looking for is like the following 000V-11-00000. Anything else not in that format should throw the Validation rule error message at the field. What is happenign on the Site exposed VF page is the case shows it has been submitted to the user but the case is not created in the system because of the V RUle error, however the error message doe snot show on the VF page when submitting. I am pasting my code below in hopes someone can help me figure this one out. As you can see I have try catch and attemptign to show the error message any way I know how but it doesnt seem to diplay the error no matter what I try. PLEASE HELP :)
Controller Extension:
public with sharing class caseattachment
{
public case objcase{get;set;}
public String subj {get;set;}
public String description {get;set;}
public Attachment myAttachment{get;set;}
public string fileName{get;set;}
public Blob fileBody{get;set;}
public caseattachment(Apexpages.standardcontroller controller)
{
objcase = new case();
myAttachment =new Attachment();
}
public pagereference save()
{
String currentPage = null;
Boolean isServiceReadinessPage = false;
if(ApexPages.currentPage() != null && !Test.isRunningTest()) {
currentPage = ApexPages.currentPage().getUrl();
isServiceReadinessPage = currentPage.contains('Service_Readiness_Updated');
}
if(objCase.Requested_Completion_Date__c != null) {
objCase.Contract_Start_Date__c = objCase.Requested_Completion_Date__c;
objCase.Requested_Completion_Date__c = null;
}
if(objCase.Requested_Completion_Date_2__c != null) {
objCase.Contract_End_Date__c = objCase.Requested_Completion_Date_2__c;
objCase.Requested_Completion_Date_2__c = null;
}
Boolean contractStartEndDateFieldsHaveValues = (objCase.Contract_Start_Date__c != null) && (objCase.Contract_End_Date__c != null);
Boolean requiredFieldsHaveValues = true;
//requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Sales_Type__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Customer_Name__c != null);
//requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Request_Type_2__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Manufacturer__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Number_Of_Ports__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Number_Of_Users__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Contract_Start_Date__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Contract_End_Date__c != null);
//requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Salesperson__c != null);
//requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Sales_Engineer__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Trial_Account__c != null);
if(requiredFieldsHaveValues || (objCase.VMR_or_Bridging__c != 'Bridging/VMR' && contractStartEndDateFieldsHaveValues) || (!isServiceReadinessPage && objCase.VMR_or_Bridging__c != 'Bridging/VMR')) {
//if(requiredFieldsHaveValues || objCase.VMR_or_Bridging__c != 'Bridging/VMR') {
try{
insert objcase;
} catch(DMLException e) {
ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, e.getdmlMessage(0));
ApexPages.addMessage(msg);
}
if (fileName != null && fileName.trim().length() > 0 && fileBody != null) {
myAttachment = new Attachment();
Integer i=0;
myAttachment .clear();
myAttachment.Body = fileBody;
myAttachment.Name = this.fileName;
myAttachment.ParentId = objcase.id;
insert myAttachment;
}
pagereference pr = new pagereference('/'+objcase.id);
return pr;
} else {
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Fill in all the required fields before saving.');
ApexPages.addMessage(myMsg);
return null;
}
}
}
VF Page code:
<apex:page standardcontroller="Case" extensions="caseattachment"
showHeader="false">
<img src="{!$resource.AVISPL_Logo2}"></img><b/><b/>
<apex:pageMessages id="errMsg" />
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection title="Professional Service / Onboarding Request" columns="1" showHeader="True" collapsible="False"> </apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock >
<apex:inputField value="{!Case.CaseNumber}"/>
<apex:pageBlockSection title="Requestor Information">
<apex:inputfield value="{!objcase.Requestor_s_First_Name__c}" required="True"/>
<apex:inputfield value="{!objcase.Requestor_s_Last_Name__c}" required="True"/>
<apex:inputfield value="{!objcase.Requestor_Email_Address__c}" required="True"/>
<apex:inputfield value="{!objcase.Requestor_s_Phone_Number__c}" required="True"/>
<apex:inputField value="{!objcase.Account_Name__c}" required="True"/>
<apex:inputField value="{!objcase.Sales_Type__c}" required="True"/>
<apex:inputField value="{!objcase.Customer_Name__c}" required="True"/>
<apex:inputField value="{!objcase.Customer_Type__c}" required="True"/>
<apex:inputField value="{!objcase.Customer_Points_of_Contact__c}" required="True"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Description Information">
<apex:inputField value="{!objcase.Project_Name__c}" required="True"/>
<apex:inputField value="{!objcase.Request_Type_2__c}" required="True"/>
<apex:inputField value="{!objcase.Service_Type__c}" required="True"/>
<apex:inputField value="{!objcase.Connection_Type__c}"/>
<apex:inputField value="{!objcase.Description}" required="True"/>
<apex:inputField value="{!objcase.Manufacturer__c}" required="True"/>
<apex:inputField value="{!objcase.BKR_Opp_or_Quote__c}" label="BKR Job#" required="True"/>
<apex:inputField value="{!objcase.Messaging_Technology__c}" required="True"/>
<apex:inputField value="{!objcase.Target_Deadline__c}" required="True"/>
<apex:inputField value="{!objcase.TSG_Project_Manager_Budgeted_Hours__c}" required="True"/>
<apex:inputField value="{!objcase.TSG_Engineer_Programmer_Budgeted_Hours__c }" label="Engineer Budgeted Hours" required="True"/> <apex:inputField value="{!objcase.Project_Budgeted_Cost__c }" required="True"/>
<br/> >
</apex:pageBlockSection>
<apex:pageBlockSection title="SOW PO & IPT (Attachment)">
<apex:inputFile id="fileToUpload" value="{!fileBody}" filename="{!fileName}" styleClass="input-file"/>
</apex:pageBlockSection> <apex:commandButton value="Submit Request" action="{!Save}" reRender="errMsg" />
<apex:outputLink value="http://avi-spl.force.com/profmanservicemainpage">Return To Main Page</apex:outputLink>
</apex:pageBlock>
</apex:form>
</apex:page>
Controller Extension:
public with sharing class caseattachment
{
public case objcase{get;set;}
public String subj {get;set;}
public String description {get;set;}
public Attachment myAttachment{get;set;}
public string fileName{get;set;}
public Blob fileBody{get;set;}
public caseattachment(Apexpages.standardcontroller controller)
{
objcase = new case();
myAttachment =new Attachment();
}
public pagereference save()
{
String currentPage = null;
Boolean isServiceReadinessPage = false;
if(ApexPages.currentPage() != null && !Test.isRunningTest()) {
currentPage = ApexPages.currentPage().getUrl();
isServiceReadinessPage = currentPage.contains('Service_Readiness_Updated');
}
if(objCase.Requested_Completion_Date__c != null) {
objCase.Contract_Start_Date__c = objCase.Requested_Completion_Date__c;
objCase.Requested_Completion_Date__c = null;
}
if(objCase.Requested_Completion_Date_2__c != null) {
objCase.Contract_End_Date__c = objCase.Requested_Completion_Date_2__c;
objCase.Requested_Completion_Date_2__c = null;
}
Boolean contractStartEndDateFieldsHaveValues = (objCase.Contract_Start_Date__c != null) && (objCase.Contract_End_Date__c != null);
Boolean requiredFieldsHaveValues = true;
//requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Sales_Type__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Customer_Name__c != null);
//requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Request_Type_2__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Manufacturer__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Number_Of_Ports__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Number_Of_Users__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Contract_Start_Date__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Contract_End_Date__c != null);
//requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Salesperson__c != null);
//requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Sales_Engineer__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Trial_Account__c != null);
if(requiredFieldsHaveValues || (objCase.VMR_or_Bridging__c != 'Bridging/VMR' && contractStartEndDateFieldsHaveValues) || (!isServiceReadinessPage && objCase.VMR_or_Bridging__c != 'Bridging/VMR')) {
//if(requiredFieldsHaveValues || objCase.VMR_or_Bridging__c != 'Bridging/VMR') {
try{
insert objcase;
} catch(DMLException e) {
ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, e.getdmlMessage(0));
ApexPages.addMessage(msg);
}
if (fileName != null && fileName.trim().length() > 0 && fileBody != null) {
myAttachment = new Attachment();
Integer i=0;
myAttachment .clear();
myAttachment.Body = fileBody;
myAttachment.Name = this.fileName;
myAttachment.ParentId = objcase.id;
insert myAttachment;
}
pagereference pr = new pagereference('/'+objcase.id);
return pr;
} else {
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Fill in all the required fields before saving.');
ApexPages.addMessage(myMsg);
return null;
}
}
}
VF Page code:
<apex:page standardcontroller="Case" extensions="caseattachment"
showHeader="false">
<img src="{!$resource.AVISPL_Logo2}"></img><b/><b/>
<apex:pageMessages id="errMsg" />
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection title="Professional Service / Onboarding Request" columns="1" showHeader="True" collapsible="False"> </apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock >
<apex:inputField value="{!Case.CaseNumber}"/>
<apex:pageBlockSection title="Requestor Information">
<apex:inputfield value="{!objcase.Requestor_s_First_Name__c}" required="True"/>
<apex:inputfield value="{!objcase.Requestor_s_Last_Name__c}" required="True"/>
<apex:inputfield value="{!objcase.Requestor_Email_Address__c}" required="True"/>
<apex:inputfield value="{!objcase.Requestor_s_Phone_Number__c}" required="True"/>
<apex:inputField value="{!objcase.Account_Name__c}" required="True"/>
<apex:inputField value="{!objcase.Sales_Type__c}" required="True"/>
<apex:inputField value="{!objcase.Customer_Name__c}" required="True"/>
<apex:inputField value="{!objcase.Customer_Type__c}" required="True"/>
<apex:inputField value="{!objcase.Customer_Points_of_Contact__c}" required="True"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Description Information">
<apex:inputField value="{!objcase.Project_Name__c}" required="True"/>
<apex:inputField value="{!objcase.Request_Type_2__c}" required="True"/>
<apex:inputField value="{!objcase.Service_Type__c}" required="True"/>
<apex:inputField value="{!objcase.Connection_Type__c}"/>
<apex:inputField value="{!objcase.Description}" required="True"/>
<apex:inputField value="{!objcase.Manufacturer__c}" required="True"/>
<apex:inputField value="{!objcase.BKR_Opp_or_Quote__c}" label="BKR Job#" required="True"/>
<apex:inputField value="{!objcase.Messaging_Technology__c}" required="True"/>
<apex:inputField value="{!objcase.Target_Deadline__c}" required="True"/>
<apex:inputField value="{!objcase.TSG_Project_Manager_Budgeted_Hours__c}" required="True"/>
<apex:inputField value="{!objcase.TSG_Engineer_Programmer_Budgeted_Hours__c }" label="Engineer Budgeted Hours" required="True"/> <apex:inputField value="{!objcase.Project_Budgeted_Cost__c }" required="True"/>
<br/> >
</apex:pageBlockSection>
<apex:pageBlockSection title="SOW PO & IPT (Attachment)">
<apex:inputFile id="fileToUpload" value="{!fileBody}" filename="{!fileName}" styleClass="input-file"/>
</apex:pageBlockSection> <apex:commandButton value="Submit Request" action="{!Save}" reRender="errMsg" />
<apex:outputLink value="http://avi-spl.force.com/profmanservicemainpage">Return To Main Page</apex:outputLink>
</apex:pageBlock>
</apex:form>
</apex:page>
- Shawn Reichner
- March 13, 2017
- Like
- 0
Test Class help needed please
Hello, thnak you very much for the help in advance if you are able to help with the following test class. I am new to Apex and have created a trigger which I am posting below which is working fine. The test class I created is covering roughly 54 percent and I need it higher of course. I am posting the test class below as well with the lines marked that are not being covered. If you can help me get the code coverage up I would greatly appreciate it. Thank you again!
Trigger Code -
List<String> CaseZipList = new List<String>();
For(Case Cases : Trigger.new) {
IF(string.isBlank(Cases.New_Job_Number__c) && Cases.AVISPL_Service_Maintenance_Contract__c != null && !string.isBlank(Cases.New_Company_Database__c) && !string.isBlank(Cases.Address_Zip_Code__c)) {
String zipCode = cases.Address_Zip_Code__c;
//We need to sanitize the incoming zip code. Specifically, the Zip_Code__c object stores 5-digit zip codes only, so a longer zip code (e.g. 17801-7952) needs to be trimmed to match (e.g. 17801).
zipCode = zipCode.left(5);
trigger AVI_SPL_TM_Zip_To_Warehouse on Case (after insert, before update) {
CaseZipList.add(zipCode);
}
}
//If there is at least one Case which meets our criteria...
if(CaseZipList.size() > 0) {
//...then query the appropriate objects and perform the rest of the trigger's functionality.
ID ExternalZipCodeRT = Schema.sObjectType.Zip_Code__c.getRecordTypeInfosByName().get('External Zip Code').getRecordTypeId();
List<Zip_Code__c> zipList = [SELECT ID, Name, Location__Longitude__s,Location__Latitude__s, Warehouse_Code_Selection__c, Company_Database__c
FROM Zip_Code__c
WHERE Name = : CaseZipList
AND RecordTypeId = :ExternalZipCodeRT];
ID InternalZipCodeRT = Schema.sObjectType.Zip_Code__c.getRecordTypeInfosByName().get('Internal Sales Office').getRecordTypeId();
List<Zip_Code__c> SalesZipList = [SELECT ID, Name, Location__Longitude__s,Location__Latitude__s, Warehouse_Code_Selection__c, Company_Database__c
FROM Zip_Code__c
WHERE RecordTypeId = :InternalZipCodeRT];
List<Location> SalesOfficeLocations = new List<Location>();
Map<Location,String> locationToWarehouseCode = new Map<Location,String>();
Map<String,String> warehouseCodeToCompanyDatabase = new Map<String, String>();
For(Zip_Code__c SZ : SalesZipList) {
NOT COVERED Location Loc = Location.newInstance(SZ.Location__Latitude__s,SZ.Location__Longitude__s);
NOT COVERED SalesOfficeLocations.add(Loc);
NOT COVERED locationToWarehouseCode.put(Loc,SZ.Warehouse_Code_Selection__c);
NOT COVERED warehouseCodeToCompanyDatabase.put(SZ.Warehouse_Code_Selection__c, SZ.Company_Database__c);
}
//Loop through each inserted or updated Case.
for(Case Cases : Trigger.new) {
//For each Case that meets our criteria...
IF(string.isBlank(Cases.New_Job_Number__c) && Cases.AVISPL_Service_Maintenance_Contract__c != null && !string.isBlank(Cases.New_Company_Database__c) && !string.isBlank(Cases.Address_Zip_Code__c)) {
//...then loop through each of the External Zip Codes we queried.
For(Zip_Code__c CL : ZipList) {
NOT COVERED String zipCode = Cases.Address_Zip_Code__c;
//We need to sanitize the incoming zip code. Specifically, the Zip_Code__c object stores 5-digit zip codes only, so a longer zip code (e.g. 17801-7952) needs to be trimmed to match (e.g. 17801).
NOT COVERED zipCode = zipCode.left(5);
//When we find the matching External Zip Code...
NOT COVERED if(CL.name == zipCode) {
//...then grab its location so we can compare against the Sales Office Locations.
NOT COVERED Location Loc = Location.newInstance(CL.Location__Latitude__s,CL.Location__Longitude__s);
NOT COVERED Double minDistance = null;
NOT COVERED String closestWarehouseCode = null;
//Loop through all the Sales Office Locations.
NOT COVERED For(Location SOL : SalesOfficeLocations){
//If the Sales Office Location is for the same Company Database value as the Case we're currently examining...
NOT COVERED if(warehouseCodeToCompanyDatabase.get(locationToWarehouseCode.get(SOL)) == cases.New_Company_Database__c) {
//...then determine the distance between them.
NOT COVERED Double distance = Location.getDistance(Loc,SOL,'mi');
//If this is the closest distance we've calculated so far...
NOT COVERED If(minDistance == null || distance < minDistance){
//...then save that distance as our new closest and assign the Warehouse Code as the closest Warehouse.
NOT COVERED minDistance = distance;
NOT COVERED closestWarehouseCode = locationToWarehouseCode.get(SOL);
}//end of If(minDistance == null || distance < minDistance)
}//end of if(warehouseCodeToCompanyDatabase.get(locationToWarehouseCode.get(SOL)) == cases.New_Company_Database__c)
}//end of For(Location SOL : SalesOfficeLocations)
//Having done all of those comparisons, we can now assign the closest Warehouse Code to the Case.
NOT COVERED Cases.AVI_SPL_Rep_Whse_Office_Code_2011__c = closestWarehouseCode;
}//end of if(CL.name == zipCode)
}//end of For(Zip_Code__c CL : ZipList)
}//end of IF(string.isBlank(Cases.New_Job_Number__c) && Cases.AVISPL_Service_Maintenance_Contract__c != null && !string.isBlank(Cases.New_Company_Database__c) && !string.isBlank(Cases.Address_Zip_Code__c))
}//end of for(Case Cases : Trigger.new)
}//end of if(CaseZipList.size() > 0)
//call of existing trigger "SalesExtract" from Case Object. Need this code to fire after Zip actions.
salespersonextraction.salesextract(Trigger.new);
}
Test Class -
@isTest
public class AVI_SPL_TM_Zip_To_Warehouse_Test{
public static Case testCase;
public static AVISPL_Service_Maintenance_Contract__c testSmc;
public static Account testAcc;
@testSetup
private static void myTestData(){
Account a = new Account();
a.Name = 'Test Warehouse Account';
a.CurrencyIsoCode = 'USD';
a.RecordTypeId = '01240000000DhQMAA0';
a.Named_Account__c = 'No';
a.Exclusive_Account__c = 'No';
a.Enterprise_Account__c = 'No';
insert a;
AVI_SPL_TM_Zip_To_Warehouse_Test.testAcc = a;
System.debug('The new Account ID is ' + a.Id);
Contact con = new Contact();
con.FirstName = 'Test Shawn';
con.LastName = 'Contact';
con.Email = 'djsuite015@gmail.com';
con.CurrencyIsoCode = 'USD';
con.AccountId ='0014000000iLrfy';
con.RecordTypeId ='012330000001HMuAAM';
insert con;
System.debug('The new Contact ID is ' + con.Id);
AVISPL_Service_Level_Term__c sla = new AVISPL_Service_Level_Term__c();
sla.Name = 'Test';
sla.Active__c = True;
insert sla;
system.debug('The new SLA Term ID is ' + sla.Id);
AVISPL_Service_Maintenance_Contract__c s = new AVISPL_Service_Maintenance_Contract__c();
s.Name = 'Warehouse Test SMC';
s.Active_Contract__c = True;
s.CurrencyIsoCode = 'USD';
s.Salesperson__c = con.Id;
s.BKR_Customer__c = '12345';
s.Company_Database__c = 'AVI';
s.Contract_Start_Date__c = Date.newInstance(2016, 11, 1);
s.Contract_End_Date__c = Date.newInstance(2017, 11, 1);
s.SLA_Terms__c = sla.Id;
s.Sale_Type__c = 'Service Only - Net New';
// s.Preventative_Maintenance_Visits__c = 'One';
s.RecordTypeId = '012330000001HMpAAM';
insert s;
AVI_SPL_TM_Zip_To_Warehouse_Test.testSmc = s;
system.debug('The new SMC Id is ' + s.Id);
Case c = new Case();
c.RecordTypeId = '01240000000INaqAAG';
c.Status = 'New / Open';
c.Priority = 'P4';
c.Department__c = 'Help Desk';
c.CurrencyIsoCode = 'USD';
c.AccountId = a.Id;
c.AVISPL_Service_Maintenance_Contract__c = s.Id;
c.Sub_Account_Room_Information__c = 'TBD';
c.Type = 'Contract';
c.Origin = 'Phone';
c.Subject = 'Test';
c.Description = 'Test';
c.Svc_Category_Client_Reported_Issue__c = 'A/V';
c.New_Job_Number__c = '';
c.Address_Zip_Code__c = '17801-7952';
c.New_Company_Database__c = s.Company_Database__c;
insert c;
AVI_SPL_TM_Zip_To_Warehouse_Test.testCase = c;
system.debug('The testCase ID is ' + testCase.Id);
system.debug('The new Case Id is ' + c.Id);
}
private static testMethod void tm1(){
AVI_SPL_TM_Zip_To_Warehouse_Test.myTestData();
AVI_SPL_TM_Zip_To_Warehouse_Test.testCase = [SELECT Id, New_Company_Database__c, Address_Zip_Code__c, New_Job_Number__c,
AVI_SPL_Rep_Whse_Office_Code_2011__c FROM Case
WHERE Id = : AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.Id];
If(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.AVI_SPL_Rep_Whse_Office_Code_2011__c != null){
system.assert(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.AVI_SPL_Rep_Whse_Office_Code_2011__c == 'PA_Philadelphia_240S_240600_SPL');
system.assert(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.Address_Zip_Code__c == '17801');
system.assert(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.New_Company_Database__c == 'SPL');
system.assert(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.Address_Zip_Code__c != '17801-7952');
}
}
}
Trigger Code -
List<String> CaseZipList = new List<String>();
For(Case Cases : Trigger.new) {
IF(string.isBlank(Cases.New_Job_Number__c) && Cases.AVISPL_Service_Maintenance_Contract__c != null && !string.isBlank(Cases.New_Company_Database__c) && !string.isBlank(Cases.Address_Zip_Code__c)) {
String zipCode = cases.Address_Zip_Code__c;
//We need to sanitize the incoming zip code. Specifically, the Zip_Code__c object stores 5-digit zip codes only, so a longer zip code (e.g. 17801-7952) needs to be trimmed to match (e.g. 17801).
zipCode = zipCode.left(5);
trigger AVI_SPL_TM_Zip_To_Warehouse on Case (after insert, before update) {
CaseZipList.add(zipCode);
}
}
//If there is at least one Case which meets our criteria...
if(CaseZipList.size() > 0) {
//...then query the appropriate objects and perform the rest of the trigger's functionality.
ID ExternalZipCodeRT = Schema.sObjectType.Zip_Code__c.getRecordTypeInfosByName().get('External Zip Code').getRecordTypeId();
List<Zip_Code__c> zipList = [SELECT ID, Name, Location__Longitude__s,Location__Latitude__s, Warehouse_Code_Selection__c, Company_Database__c
FROM Zip_Code__c
WHERE Name = : CaseZipList
AND RecordTypeId = :ExternalZipCodeRT];
ID InternalZipCodeRT = Schema.sObjectType.Zip_Code__c.getRecordTypeInfosByName().get('Internal Sales Office').getRecordTypeId();
List<Zip_Code__c> SalesZipList = [SELECT ID, Name, Location__Longitude__s,Location__Latitude__s, Warehouse_Code_Selection__c, Company_Database__c
FROM Zip_Code__c
WHERE RecordTypeId = :InternalZipCodeRT];
List<Location> SalesOfficeLocations = new List<Location>();
Map<Location,String> locationToWarehouseCode = new Map<Location,String>();
Map<String,String> warehouseCodeToCompanyDatabase = new Map<String, String>();
For(Zip_Code__c SZ : SalesZipList) {
NOT COVERED Location Loc = Location.newInstance(SZ.Location__Latitude__s,SZ.Location__Longitude__s);
NOT COVERED SalesOfficeLocations.add(Loc);
NOT COVERED locationToWarehouseCode.put(Loc,SZ.Warehouse_Code_Selection__c);
NOT COVERED warehouseCodeToCompanyDatabase.put(SZ.Warehouse_Code_Selection__c, SZ.Company_Database__c);
}
//Loop through each inserted or updated Case.
for(Case Cases : Trigger.new) {
//For each Case that meets our criteria...
IF(string.isBlank(Cases.New_Job_Number__c) && Cases.AVISPL_Service_Maintenance_Contract__c != null && !string.isBlank(Cases.New_Company_Database__c) && !string.isBlank(Cases.Address_Zip_Code__c)) {
//...then loop through each of the External Zip Codes we queried.
For(Zip_Code__c CL : ZipList) {
NOT COVERED String zipCode = Cases.Address_Zip_Code__c;
//We need to sanitize the incoming zip code. Specifically, the Zip_Code__c object stores 5-digit zip codes only, so a longer zip code (e.g. 17801-7952) needs to be trimmed to match (e.g. 17801).
NOT COVERED zipCode = zipCode.left(5);
//When we find the matching External Zip Code...
NOT COVERED if(CL.name == zipCode) {
//...then grab its location so we can compare against the Sales Office Locations.
NOT COVERED Location Loc = Location.newInstance(CL.Location__Latitude__s,CL.Location__Longitude__s);
NOT COVERED Double minDistance = null;
NOT COVERED String closestWarehouseCode = null;
//Loop through all the Sales Office Locations.
NOT COVERED For(Location SOL : SalesOfficeLocations){
//If the Sales Office Location is for the same Company Database value as the Case we're currently examining...
NOT COVERED if(warehouseCodeToCompanyDatabase.get(locationToWarehouseCode.get(SOL)) == cases.New_Company_Database__c) {
//...then determine the distance between them.
NOT COVERED Double distance = Location.getDistance(Loc,SOL,'mi');
//If this is the closest distance we've calculated so far...
NOT COVERED If(minDistance == null || distance < minDistance){
//...then save that distance as our new closest and assign the Warehouse Code as the closest Warehouse.
NOT COVERED minDistance = distance;
NOT COVERED closestWarehouseCode = locationToWarehouseCode.get(SOL);
}//end of If(minDistance == null || distance < minDistance)
}//end of if(warehouseCodeToCompanyDatabase.get(locationToWarehouseCode.get(SOL)) == cases.New_Company_Database__c)
}//end of For(Location SOL : SalesOfficeLocations)
//Having done all of those comparisons, we can now assign the closest Warehouse Code to the Case.
NOT COVERED Cases.AVI_SPL_Rep_Whse_Office_Code_2011__c = closestWarehouseCode;
}//end of if(CL.name == zipCode)
}//end of For(Zip_Code__c CL : ZipList)
}//end of IF(string.isBlank(Cases.New_Job_Number__c) && Cases.AVISPL_Service_Maintenance_Contract__c != null && !string.isBlank(Cases.New_Company_Database__c) && !string.isBlank(Cases.Address_Zip_Code__c))
}//end of for(Case Cases : Trigger.new)
}//end of if(CaseZipList.size() > 0)
//call of existing trigger "SalesExtract" from Case Object. Need this code to fire after Zip actions.
salespersonextraction.salesextract(Trigger.new);
}
Test Class -
@isTest
public class AVI_SPL_TM_Zip_To_Warehouse_Test{
public static Case testCase;
public static AVISPL_Service_Maintenance_Contract__c testSmc;
public static Account testAcc;
@testSetup
private static void myTestData(){
Account a = new Account();
a.Name = 'Test Warehouse Account';
a.CurrencyIsoCode = 'USD';
a.RecordTypeId = '01240000000DhQMAA0';
a.Named_Account__c = 'No';
a.Exclusive_Account__c = 'No';
a.Enterprise_Account__c = 'No';
insert a;
AVI_SPL_TM_Zip_To_Warehouse_Test.testAcc = a;
System.debug('The new Account ID is ' + a.Id);
Contact con = new Contact();
con.FirstName = 'Test Shawn';
con.LastName = 'Contact';
con.Email = 'djsuite015@gmail.com';
con.CurrencyIsoCode = 'USD';
con.AccountId ='0014000000iLrfy';
con.RecordTypeId ='012330000001HMuAAM';
insert con;
System.debug('The new Contact ID is ' + con.Id);
AVISPL_Service_Level_Term__c sla = new AVISPL_Service_Level_Term__c();
sla.Name = 'Test';
sla.Active__c = True;
insert sla;
system.debug('The new SLA Term ID is ' + sla.Id);
AVISPL_Service_Maintenance_Contract__c s = new AVISPL_Service_Maintenance_Contract__c();
s.Name = 'Warehouse Test SMC';
s.Active_Contract__c = True;
s.CurrencyIsoCode = 'USD';
s.Salesperson__c = con.Id;
s.BKR_Customer__c = '12345';
s.Company_Database__c = 'AVI';
s.Contract_Start_Date__c = Date.newInstance(2016, 11, 1);
s.Contract_End_Date__c = Date.newInstance(2017, 11, 1);
s.SLA_Terms__c = sla.Id;
s.Sale_Type__c = 'Service Only - Net New';
// s.Preventative_Maintenance_Visits__c = 'One';
s.RecordTypeId = '012330000001HMpAAM';
insert s;
AVI_SPL_TM_Zip_To_Warehouse_Test.testSmc = s;
system.debug('The new SMC Id is ' + s.Id);
Case c = new Case();
c.RecordTypeId = '01240000000INaqAAG';
c.Status = 'New / Open';
c.Priority = 'P4';
c.Department__c = 'Help Desk';
c.CurrencyIsoCode = 'USD';
c.AccountId = a.Id;
c.AVISPL_Service_Maintenance_Contract__c = s.Id;
c.Sub_Account_Room_Information__c = 'TBD';
c.Type = 'Contract';
c.Origin = 'Phone';
c.Subject = 'Test';
c.Description = 'Test';
c.Svc_Category_Client_Reported_Issue__c = 'A/V';
c.New_Job_Number__c = '';
c.Address_Zip_Code__c = '17801-7952';
c.New_Company_Database__c = s.Company_Database__c;
insert c;
AVI_SPL_TM_Zip_To_Warehouse_Test.testCase = c;
system.debug('The testCase ID is ' + testCase.Id);
system.debug('The new Case Id is ' + c.Id);
}
private static testMethod void tm1(){
AVI_SPL_TM_Zip_To_Warehouse_Test.myTestData();
AVI_SPL_TM_Zip_To_Warehouse_Test.testCase = [SELECT Id, New_Company_Database__c, Address_Zip_Code__c, New_Job_Number__c,
AVI_SPL_Rep_Whse_Office_Code_2011__c FROM Case
WHERE Id = : AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.Id];
If(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.AVI_SPL_Rep_Whse_Office_Code_2011__c != null){
system.assert(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.AVI_SPL_Rep_Whse_Office_Code_2011__c == 'PA_Philadelphia_240S_240600_SPL');
system.assert(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.Address_Zip_Code__c == '17801');
system.assert(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.New_Company_Database__c == 'SPL');
system.assert(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.Address_Zip_Code__c != '17801-7952');
}
}
}
- Shawn Reichner
- January 26, 2017
- Like
- 0
Help with Test Class created.
Hello I am attempting to test a trigger I have created, but I am failing at line 43 of the Test class. Any ideas what may be happening here based on the code for the trigger and test class below? I am new to Apex code and developing in general, so I am hopful someone more experienced may be able to help.
The error code I am getting when testing the class is as follows: Class.InstallProdDuplicatePreventerTests.testInstallProdDuplicatePreventer: line 43, column 1
Trigger -
trigger InstallProdDuplicatePreventer on AVISPL_Client_Product__c
(before insert, before update) {
Map<String, AVISPL_Client_Product__c > IPMap = new Map<String, AVISPL_Client_Product__c >();
for (AVISPL_Client_Product__c IP : System.Trigger.new) {
// Make sure we don't treat an email address that
// isn't changing during an update as a duplicate.
if ((IP.Name != null) &&
(System.Trigger.isInsert ||
(IP.Name !=
System.Trigger.oldMap.get(IP.Id).Name))) {
// Make sure another new lead isn't also a duplicate
if (IPMap.containsKey(IP.Name)) {
IP.Name.addError('Another Installed Product has the '
+ 'same Name.');
} else {
IPMap.put(IP.Name, IP);
}
}
}
// Using a single database query, find all the leads in
// the database that have the same email address as any
// of the leads being inserted or updated.
for (AVISPL_Client_Product__c Ip2 : [SELECT Name FROM AVISPL_Client_Product__c
WHERE Name IN :IPMap.KeySet()]) {
AVISPL_Client_Product__c newIP = IPMap.get(IP2.Name);
newIP.Name.addError('A Installed Product with this name '
+ 'already exists.');
}
}
Test Class -
@IsTest
public class InstallProdDuplicatePreventerTests{
static testMethod void testInstallProdDuplicatePreventer() {
// First make sure there are no Installed Products already in the system
// that have the Name used for testing
Set<String> testName = new Set<String>();
testName.add('1213');
testName.add('1212');
testName.add('1211');
testName.add('1210');
testName.add('1209');
System.assert([SELECT count() FROM AVISPL_Client_Product__c
WHERE Name IN :testName] == 0);
// Seed the database with some Installed Products, and make sure they can
// be bulk inserted successfully.
AVISPL_Client_Product__c IP1 = new AVISPL_Client_Product__c(Name='Test1');
AVISPL_Client_Product__c IP2 = new AVISPL_Client_Product__c(Name='Test2');
AVISPL_Client_Product__c IP3 = new AVISPL_Client_Product__c(Name='Test3');
AVISPL_Client_Product__c[] IPs = new AVISPL_Client_Product__c[] {IP1, IP2, IP3};
insert IPs;
// Now make sure that some of these Installed Products can be changed and
// then bulk updated successfully. Note that IP1 is not
// being changed, but is still being passed to the update
// call. This should be OK.
IP2.Name = '12111';
IP3.Name = '33333';
update IPs;
// Make sure that single row Installed Prod duplication prevention works
// on insert.
AVISPL_Client_Product__c dup1 = new AVISPL_Client_Product__c(Name='33333');
try {
insert dup1;
System.assert(false);
} catch (DmlException e) {
System.assert(e.getNumDml() == 1);
System.assert(e.getDmlIndex(0) == 0);
System.assert(e.getDmlFields(0).size() == 1);
// System.assert(e.getDmlFields(0)[0] == 'String');
System.assert(e.getDmlMessage(0).indexOf(
'A Installed Product with this Name already exists.') > -1);
}
// Make sure that single row Installed Prod duplication prevention works
// on update.
dup1 = new AVISPL_Client_Product__c(Id = IP1.Id, Name='Test1');
try {
update dup1;
System.assert(false);
} catch (DmlException e) {
System.assert(e.getNumDml() == 1);
System.assert(e.getDmlIndex(0) == 0);
System.assert(e.getDmlFields(0).size() == 1);
// System.assert(e.getDmlFields(0)[0] == 'Name');
System.assert(e.getDmlMessage(0).indexOf(
'A Installed Product with this Name already exists.') > -1);
}
// Make sure that bulk Installed Products duplication prevention works on
// insert. Note that the first item being inserted is fine,
// but the second and third items are duplicates. Note also
// that since at least one record insert fails, the entire
// transaction will be rolled back.
dup1 = new AVISPL_Client_Product__c(Name='Test1');
AVISPL_Client_Product__c dup2 = new AVISPL_Client_Product__c(Name='Test2');
AVISPL_Client_Product__c dup3 = new AVISPL_Client_Product__c(Name='Test3');
AVISPL_Client_Product__c[] dups = new AVISPL_Client_Product__c[] {dup1, dup2, dup3};
try {
insert dups;
System.assert(false);
} catch (DmlException e) {
System.assert(e.getNumDml() == 2);
System.assert(e.getDmlIndex(0) == 1);
System.assert(e.getDmlFields(0).size() == 1);
// System.assert(e.getDmlFields(0)[0] == 'Name');
System.assert(e.getDmlMessage(0).indexOf(
'A Installed Product with this Name already exists.') > -1);
System.assert(e.getDmlIndex(1) == 2);
System.assert(e.getDmlFields(1).size() == 1);
// System.assert(e.getDmlFields(1)[0] == 'Name');
System.assert(e.getDmlMessage(1).indexOf(
'A Installed Product with this Name already exists.') > -1);
}
// Make sure that bulk Installed Prod duplication prevention works on
// update. Note that the first item being updated is fine,
// because the Name is new, and the second item is
// also fine, but in this case it's because the Name
// doesn't change. The third case is flagged as an
// error because it is a duplicate of the Name of the
// first Installed Prod value in the database, even though that value
// is changing in this same update call. Note also that since at least one record update
// fails, the entire transaction will be rolled back.
dup1 = new AVISPL_Client_Product__c(Id=IP1.Id, Name='TestDup1');
dup2 = new AVISPL_Client_Product__c(Id=IP2.Id, Name='TestDup2');
dup3 = new AVISPL_Client_Product__c(Id=IP3.Id, Name='TestDup3');
dups = new AVISPL_Client_Product__c[] {dup1, dup2, dup3};
try {
update dups;
System.assert(false);
} catch (DmlException e) {
System.debug(e.getNumDml());
System.debug(e.getDmlMessage(0));
System.assert(e.getNumDml() == 1);
System.assert(e.getDmlIndex(0) == 2);
System.assert(e.getDmlFields(0).size() == 1);
// System.assert(e.getDmlFields(0)[0] == 'Name');
System.assert(e.getDmlMessage(0).indexOf(
'A Installed Product with this Name already exists.') > -1);
}
// Make sure that duplicates in the submission are caught when
// inserting Installed Products. Note that this test also catches an
// attempt to insert a Installed Product where there is an existing
// duplicate.
dup1 = new AVISPL_Client_Product__c(Name='Test1Dup');
dup2 = new AVISPL_Client_Product__c(Name='Test2Dup');
dup3 = new AVISPL_Client_Product__c(Name='Test3Dup');
dups = new AVISPL_Client_Product__c[] {dup1, dup2, dup3};
try {
insert dups;
System.assert(false);
} catch (DmlException e) {
System.assert(e.getNumDml() == 2);
System.assert(e.getDmlIndex(0) == 1);
System.assert(e.getDmlFields(0).size() == 1);
// System.assert(e.getDmlFields(0)[0] == 'Name');
System.assert(e.getDmlMessage(0).indexOf(
'Another new Installed Product has the same Name.') > -1);
System.assert(e.getDmlIndex(1) == 2);
System.assert(e.getDmlFields(1).size() == 1);
// System.assert(e.getDmlFields(1)[0] == 'Name');
System.assert(e.getDmlMessage(1).indexOf(
'A Installed Product with this Name already exists.') > -1);
}
// Make sure that duplicates in the submission are caught when
// updating Installed Products. Note that this test also catches an attempt
// to update a Installed Product where there is an existing duplicate.
dup1 = new AVISPL_Client_Product__c(Id=IP1.Id, Name='TestDup1');
dup2 = new AVISPL_Client_Product__c(Id=IP2.Id, Name='TestDup4');
dup3 = new AVISPL_Client_Product__c(Id=IP3.Id, Name='TestDup2');
dups = new AVISPL_Client_Product__c[] {dup1, dup2, dup3};
try {
update dups;
System.assert(false);
} catch (DmlException e) {
System.assert(e.getNumDml() == 2);
System.assert(e.getDmlIndex(0) == 1);
System.assert(e.getDmlFields(0).size() == 1);
// System.assert(e.getDmlFields(0)[0] == 'Name');
System.assert(e.getDmlMessage(0).indexOf(
'Another new Installed Product has the same Name.') > -1);
System.assert(e.getDmlIndex(1) == 2);
System.assert(e.getDmlFields(1).size() == 1);
// System.assert(e.getDmlFields(1)[0] == 'Name');
System.assert(e.getDmlMessage(1).indexOf(
'A Installed Product with this Name already exists.') > -1);
}
}
}
The error code I am getting when testing the class is as follows: Class.InstallProdDuplicatePreventerTests.testInstallProdDuplicatePreventer: line 43, column 1
Trigger -
trigger InstallProdDuplicatePreventer on AVISPL_Client_Product__c
(before insert, before update) {
Map<String, AVISPL_Client_Product__c > IPMap = new Map<String, AVISPL_Client_Product__c >();
for (AVISPL_Client_Product__c IP : System.Trigger.new) {
// Make sure we don't treat an email address that
// isn't changing during an update as a duplicate.
if ((IP.Name != null) &&
(System.Trigger.isInsert ||
(IP.Name !=
System.Trigger.oldMap.get(IP.Id).Name))) {
// Make sure another new lead isn't also a duplicate
if (IPMap.containsKey(IP.Name)) {
IP.Name.addError('Another Installed Product has the '
+ 'same Name.');
} else {
IPMap.put(IP.Name, IP);
}
}
}
// Using a single database query, find all the leads in
// the database that have the same email address as any
// of the leads being inserted or updated.
for (AVISPL_Client_Product__c Ip2 : [SELECT Name FROM AVISPL_Client_Product__c
WHERE Name IN :IPMap.KeySet()]) {
AVISPL_Client_Product__c newIP = IPMap.get(IP2.Name);
newIP.Name.addError('A Installed Product with this name '
+ 'already exists.');
}
}
Test Class -
@IsTest
public class InstallProdDuplicatePreventerTests{
static testMethod void testInstallProdDuplicatePreventer() {
// First make sure there are no Installed Products already in the system
// that have the Name used for testing
Set<String> testName = new Set<String>();
testName.add('1213');
testName.add('1212');
testName.add('1211');
testName.add('1210');
testName.add('1209');
System.assert([SELECT count() FROM AVISPL_Client_Product__c
WHERE Name IN :testName] == 0);
// Seed the database with some Installed Products, and make sure they can
// be bulk inserted successfully.
AVISPL_Client_Product__c IP1 = new AVISPL_Client_Product__c(Name='Test1');
AVISPL_Client_Product__c IP2 = new AVISPL_Client_Product__c(Name='Test2');
AVISPL_Client_Product__c IP3 = new AVISPL_Client_Product__c(Name='Test3');
AVISPL_Client_Product__c[] IPs = new AVISPL_Client_Product__c[] {IP1, IP2, IP3};
insert IPs;
// Now make sure that some of these Installed Products can be changed and
// then bulk updated successfully. Note that IP1 is not
// being changed, but is still being passed to the update
// call. This should be OK.
IP2.Name = '12111';
IP3.Name = '33333';
update IPs;
// Make sure that single row Installed Prod duplication prevention works
// on insert.
AVISPL_Client_Product__c dup1 = new AVISPL_Client_Product__c(Name='33333');
try {
insert dup1;
System.assert(false);
} catch (DmlException e) {
System.assert(e.getNumDml() == 1);
System.assert(e.getDmlIndex(0) == 0);
System.assert(e.getDmlFields(0).size() == 1);
// System.assert(e.getDmlFields(0)[0] == 'String');
System.assert(e.getDmlMessage(0).indexOf(
'A Installed Product with this Name already exists.') > -1);
}
// Make sure that single row Installed Prod duplication prevention works
// on update.
dup1 = new AVISPL_Client_Product__c(Id = IP1.Id, Name='Test1');
try {
update dup1;
System.assert(false);
} catch (DmlException e) {
System.assert(e.getNumDml() == 1);
System.assert(e.getDmlIndex(0) == 0);
System.assert(e.getDmlFields(0).size() == 1);
// System.assert(e.getDmlFields(0)[0] == 'Name');
System.assert(e.getDmlMessage(0).indexOf(
'A Installed Product with this Name already exists.') > -1);
}
// Make sure that bulk Installed Products duplication prevention works on
// insert. Note that the first item being inserted is fine,
// but the second and third items are duplicates. Note also
// that since at least one record insert fails, the entire
// transaction will be rolled back.
dup1 = new AVISPL_Client_Product__c(Name='Test1');
AVISPL_Client_Product__c dup2 = new AVISPL_Client_Product__c(Name='Test2');
AVISPL_Client_Product__c dup3 = new AVISPL_Client_Product__c(Name='Test3');
AVISPL_Client_Product__c[] dups = new AVISPL_Client_Product__c[] {dup1, dup2, dup3};
try {
insert dups;
System.assert(false);
} catch (DmlException e) {
System.assert(e.getNumDml() == 2);
System.assert(e.getDmlIndex(0) == 1);
System.assert(e.getDmlFields(0).size() == 1);
// System.assert(e.getDmlFields(0)[0] == 'Name');
System.assert(e.getDmlMessage(0).indexOf(
'A Installed Product with this Name already exists.') > -1);
System.assert(e.getDmlIndex(1) == 2);
System.assert(e.getDmlFields(1).size() == 1);
// System.assert(e.getDmlFields(1)[0] == 'Name');
System.assert(e.getDmlMessage(1).indexOf(
'A Installed Product with this Name already exists.') > -1);
}
// Make sure that bulk Installed Prod duplication prevention works on
// update. Note that the first item being updated is fine,
// because the Name is new, and the second item is
// also fine, but in this case it's because the Name
// doesn't change. The third case is flagged as an
// error because it is a duplicate of the Name of the
// first Installed Prod value in the database, even though that value
// is changing in this same update call. Note also that since at least one record update
// fails, the entire transaction will be rolled back.
dup1 = new AVISPL_Client_Product__c(Id=IP1.Id, Name='TestDup1');
dup2 = new AVISPL_Client_Product__c(Id=IP2.Id, Name='TestDup2');
dup3 = new AVISPL_Client_Product__c(Id=IP3.Id, Name='TestDup3');
dups = new AVISPL_Client_Product__c[] {dup1, dup2, dup3};
try {
update dups;
System.assert(false);
} catch (DmlException e) {
System.debug(e.getNumDml());
System.debug(e.getDmlMessage(0));
System.assert(e.getNumDml() == 1);
System.assert(e.getDmlIndex(0) == 2);
System.assert(e.getDmlFields(0).size() == 1);
// System.assert(e.getDmlFields(0)[0] == 'Name');
System.assert(e.getDmlMessage(0).indexOf(
'A Installed Product with this Name already exists.') > -1);
}
// Make sure that duplicates in the submission are caught when
// inserting Installed Products. Note that this test also catches an
// attempt to insert a Installed Product where there is an existing
// duplicate.
dup1 = new AVISPL_Client_Product__c(Name='Test1Dup');
dup2 = new AVISPL_Client_Product__c(Name='Test2Dup');
dup3 = new AVISPL_Client_Product__c(Name='Test3Dup');
dups = new AVISPL_Client_Product__c[] {dup1, dup2, dup3};
try {
insert dups;
System.assert(false);
} catch (DmlException e) {
System.assert(e.getNumDml() == 2);
System.assert(e.getDmlIndex(0) == 1);
System.assert(e.getDmlFields(0).size() == 1);
// System.assert(e.getDmlFields(0)[0] == 'Name');
System.assert(e.getDmlMessage(0).indexOf(
'Another new Installed Product has the same Name.') > -1);
System.assert(e.getDmlIndex(1) == 2);
System.assert(e.getDmlFields(1).size() == 1);
// System.assert(e.getDmlFields(1)[0] == 'Name');
System.assert(e.getDmlMessage(1).indexOf(
'A Installed Product with this Name already exists.') > -1);
}
// Make sure that duplicates in the submission are caught when
// updating Installed Products. Note that this test also catches an attempt
// to update a Installed Product where there is an existing duplicate.
dup1 = new AVISPL_Client_Product__c(Id=IP1.Id, Name='TestDup1');
dup2 = new AVISPL_Client_Product__c(Id=IP2.Id, Name='TestDup4');
dup3 = new AVISPL_Client_Product__c(Id=IP3.Id, Name='TestDup2');
dups = new AVISPL_Client_Product__c[] {dup1, dup2, dup3};
try {
update dups;
System.assert(false);
} catch (DmlException e) {
System.assert(e.getNumDml() == 2);
System.assert(e.getDmlIndex(0) == 1);
System.assert(e.getDmlFields(0).size() == 1);
// System.assert(e.getDmlFields(0)[0] == 'Name');
System.assert(e.getDmlMessage(0).indexOf(
'Another new Installed Product has the same Name.') > -1);
System.assert(e.getDmlIndex(1) == 2);
System.assert(e.getDmlFields(1).size() == 1);
// System.assert(e.getDmlFields(1)[0] == 'Name');
System.assert(e.getDmlMessage(1).indexOf(
'A Installed Product with this Name already exists.') > -1);
}
}
}
- Shawn Reichner
- August 22, 2016
- Like
- 0
Visualforce Page only displays White screen in Salesforce1
Hello,
Hoping that someone can help us here! I have a VF page that is to diplay the standard Salesforce calendar in Salesforce1.
I have created the VF page(Marked it as mobile), a VF tab, and placed it in the navigation menu of Salesforce1. I also must point out that this works just fine in our dev sandbox, and this issue of just displaying a white screen is only occuirng in our production instance.
Here is the code for the VF page......does anyone have any suggestions? I am very anxious to hear any as I scoured the web and could not find any leads, so I want to turn it over to the wonderful brilliant friends here.....
<apex:page showHeader="false" sidebar="false" >
<script type="text/javascript">
window.location = "https://ap1.salesforce.com/00U/c?isdtp=mn" </script> </apex:page>
Thank you in advance for any help or suggestions you may be able to provide,
Shawn
Hoping that someone can help us here! I have a VF page that is to diplay the standard Salesforce calendar in Salesforce1.
I have created the VF page(Marked it as mobile), a VF tab, and placed it in the navigation menu of Salesforce1. I also must point out that this works just fine in our dev sandbox, and this issue of just displaying a white screen is only occuirng in our production instance.
Here is the code for the VF page......does anyone have any suggestions? I am very anxious to hear any as I scoured the web and could not find any leads, so I want to turn it over to the wonderful brilliant friends here.....
<apex:page showHeader="false" sidebar="false" >
<script type="text/javascript">
window.location = "https://ap1.salesforce.com/00U/c?isdtp=mn" </script> </apex:page>
Thank you in advance for any help or suggestions you may be able to provide,
Shawn
- Shawn Reichner
- April 22, 2016
- Like
- 0
Unexpected Token error when attempting to test a Test Class - Please Help!
Hello Experts!
I am trying to create a test apex class, which saves just fine, however when I attempt to actually run the test for the test class, i get the following error: Error Message System.QueryException: unexpected token: WHERE
Stack Trace Class.MyClosedIssuesTest.testMyClosedIssues: line 23, column 1
Here is my code, can anyone tell me what I may have done incorrectly, as google searching has yielded no results.
@IsTest(SeeAllData=true)
public class MyClosedIssuesTest {
static testMethod void testMyClosedIssues() {
SObjectType objToken = Schema.getGlobalDescribe().get('Backlog__c');
DescribeSObjectResult objDef = objToken.getDescribe();
Map<String, SObjectField> fields = objDef.fields.getMap();
Set<String> fieldSet = fields.keySet();
String query = 'SELECT ';
Integer counter = 0;
for(String s : fieldSet) {
counter++;
SObjectField fieldToken = fields.get(s);
DescribeFieldResult selectedField = fieldToken.getDescribe();
query = query + selectedField.getName();
if(counter < fieldSet.size()) {
query = query + ', ';
}
}
String query1 = query + 'FROM Backlog__c WHERE createdbyid = \'' + userinfo.getuserid() + '\'order by createddate desc';
Backlog__c testIssue = Database.query(query1);
testIssue.Parent__c = 'a3W180000008ddj';
testIssue.Scheduled_Release__c = 'a3l18000000085c';
testIssue.Environment__c = 'Production';
testIssue.Summary__c = 'Add New Items To Account and Contact';
testIssue.Description__c = 'Test';
update testIssue;
Backlog__c result = [Select ID,Description__c FROM Backlog__c WHERE Id = :testIssue.Id];
}
}
Thank you in advance for any help you may be able to provide
Shawn
I am trying to create a test apex class, which saves just fine, however when I attempt to actually run the test for the test class, i get the following error: Error Message System.QueryException: unexpected token: WHERE
Stack Trace Class.MyClosedIssuesTest.testMyClosedIssues: line 23, column 1
Here is my code, can anyone tell me what I may have done incorrectly, as google searching has yielded no results.
@IsTest(SeeAllData=true)
public class MyClosedIssuesTest {
static testMethod void testMyClosedIssues() {
SObjectType objToken = Schema.getGlobalDescribe().get('Backlog__c');
DescribeSObjectResult objDef = objToken.getDescribe();
Map<String, SObjectField> fields = objDef.fields.getMap();
Set<String> fieldSet = fields.keySet();
String query = 'SELECT ';
Integer counter = 0;
for(String s : fieldSet) {
counter++;
SObjectField fieldToken = fields.get(s);
DescribeFieldResult selectedField = fieldToken.getDescribe();
query = query + selectedField.getName();
if(counter < fieldSet.size()) {
query = query + ', ';
}
}
String query1 = query + 'FROM Backlog__c WHERE createdbyid = \'' + userinfo.getuserid() + '\'order by createddate desc';
Backlog__c testIssue = Database.query(query1);
testIssue.Parent__c = 'a3W180000008ddj';
testIssue.Scheduled_Release__c = 'a3l18000000085c';
testIssue.Environment__c = 'Production';
testIssue.Summary__c = 'Add New Items To Account and Contact';
testIssue.Description__c = 'Test';
update testIssue;
Backlog__c result = [Select ID,Description__c FROM Backlog__c WHERE Id = :testIssue.Id];
}
}
Thank you in advance for any help you may be able to provide
Shawn
- Shawn Reichner
- December 30, 2016
- Like
- 0
HYPERLINK Formula Field Issues
Hello,
I have created 2 HYPERLINK Formula fields which will be populated with the text in another field, just makign it clickable.
This is working just fine, however, when you attempt to click on the HYPERLINK field, the system does nothing.
When you right click on the HYPERLINK field, and choose to open in a new tab, it opens an about:Blank page.
Any ideas what may be causing this?
Here is the formula for the HYPERLINK field for an FYI....
IF(ISBLANK(I_Job_File_Path__c),"I-Job File Path Not Entered", HYPERLINK("file:///" & I_Job_File_Path__c, "Click here for the link to this job's support files."))
Thank you in advance for any help you can provide as this is driving me insane tryign to figure this one out :)
Shawn
I have created 2 HYPERLINK Formula fields which will be populated with the text in another field, just makign it clickable.
This is working just fine, however, when you attempt to click on the HYPERLINK field, the system does nothing.
When you right click on the HYPERLINK field, and choose to open in a new tab, it opens an about:Blank page.
Any ideas what may be causing this?
Here is the formula for the HYPERLINK field for an FYI....
IF(ISBLANK(I_Job_File_Path__c),"I-Job File Path Not Entered", HYPERLINK("file:///" & I_Job_File_Path__c, "Click here for the link to this job's support files."))
Thank you in advance for any help you can provide as this is driving me insane tryign to figure this one out :)
Shawn
- Shawn Reichner
- October 12, 2015
- Like
- 0
Trigger help with Rollup of Opportunity Sales to Custom Object
Hello,
FIrst off I am very new to coding, and have attempted to try to get the following Trigger and Class to work (Phase 1) which is to have amounts populate from "Closed-Won" opportunities to a custom object I created to house Salespeople total sales. You will notice in my code I do not have the parameters to take dates into account, which what I am after is is an opportunity is closed within the month of Januaray 2015, then a certain field on the custom object will be the rollup for all opps closed in Janurary. There will be a field for each month of the 2015 year that will need to be populated with amounts from closed won opps in that particular month for that specific salesperson. So far my trigger and class is build to test the waters just to see that the rollup is working, but I am receiving an error when attempting to save an opportunity. So I am hopeful that someone here would be nice enough to tell me where I may be going wrong, and also some points into getting the above scenerio to work to bring over amounts from certail months into certain fields on the Custom Object. Again new at code so if I left anything out, please ask if that will help you to help me the newbie! :)
Here is my trigger code
trigger OpportunityRollUpEstPrice on Opportunity (after delete, after insert, after update, after undelete) {
if(trigger.isInsert || trigger.isUpdate || trigger.isUnDelete){
list<RollUpSummaryUtility.fieldDefinition> fieldDefinitions =
new list<RollUpSummaryUtility.fieldDefinition> {
new RollUpSummaryUtility.fieldDefinition('SUM', 'Estimated_Price__c',
'Jan_Rev_ACT__c')
};
RollUpSummaryUtility.rollUpTrigger(fieldDefinitions, trigger.new,
'Sales_Targets__c', 'Sales_Target__c', 'Opportunities', '');
}
if(trigger.isDelete){
list<RollUpSummaryUtility.fieldDefinition> fieldDefinitions =
new list<RollUpSummaryUtility.fieldDefinition> {
new RollUpSummaryUtility.fieldDefinition('SUM', 'Estimated_Price__c',
'Jan_Rev_ACT__c')
};
RollUpSummaryUtility.rollUpTrigger(fieldDefinitions, trigger.old,
'Jan_Rev_ACT__c', 'Opportunity__c', 'Opportunities', '');
}
}
Here is my Class -
public class RollUpSummaryUtility {
//the following class will be used to house the field names
//and desired operations
public class fieldDefinition {
public String operation {get;set;}
public String childField {get;set;}
public String parentField {get;set;}
public fieldDefinition (String o, String c, String p) {
operation = o;
childField = c;
parentField = p;
}
}
public static void rollUpTrigger(list<fieldDefinition> fieldDefinitions,
list<sObject> records, String childObject, String childParentLookupField,
String parentObject, String queryFilter) {
//Limit the size of list by using Sets which do not contain duplicate
//elements prevents hitting governor limits
set<Id> parentIds = new set<Id>();
for(sObject s : records) {
parentIds.add((Id)s.get(childParentLookupField));
}
//populate query text strings to be used in child aggregrator and
//parent value assignment
String fieldsToAggregate = '';
String parentFields = '';
for(fieldDefinition d : fieldDefinitions) {
fieldsToAggregate += d.operation + '(' + d.childField + ') ' +
', ';
parentFields += d.parentField + ', ';
}
//Using dynamic SOQL with aggergate results to populate parentValueMap
String aggregateQuery = 'Select ' + fieldsToAggregate +
childParentLookupField + ' from ' + childObject + ' where ' +
childParentLookupField + ' IN :parentIds ' + queryFilter + ' ' +
' group by ' + childParentLookupField;
//Map will contain one parent record Id per one aggregate object
map<Id, AggregateResult> parentValueMap =
new map <Id, AggregateResult>();
for(AggregateResult q : Database.query(aggregateQuery)){
parentValueMap.put((Id)q.get(childParentLookupField), q);
}
//list of parent object records to update
list<sObject> parentsToUpdate = new list<sObject>();
String parentQuery = 'select ' + parentFields + ' Id ' +
' from ' + parentObject + ' where Id IN :parentIds';
//for each affected parent object, retrieve aggregate results and
//for each field definition add aggregate value to parent field
for(sObject s : Database.query(parentQuery)) {
Integer row = 0; //row counter reset for every parent record
for(fieldDefinition d : fieldDefinitions) {
String field = 'expr' + row.format();
AggregateResult r = parentValueMap.get(s.Id);
//r will be null if no records exist
//(e.g. last record deleted)
if(r != null) {
Decimal value = ((Decimal)r.get(field) == null ) ? 0 :
(Decimal)r.get(field);
s.put(d.parentField, value);
} else {
s.put(d.parentField, 0);
}
row += 1; //plus 1 for every field definition after first
}
parentsToUpdate.add(s);
}
//if parent records exist, perform update of all parent records
//with a single DML statement
if(parentsToUpdate.Size() > 0) {
update parentsToUpdate;
}
}
}
Thanks again for any help you can provide, as I would love to get this working!
Shawn
FIrst off I am very new to coding, and have attempted to try to get the following Trigger and Class to work (Phase 1) which is to have amounts populate from "Closed-Won" opportunities to a custom object I created to house Salespeople total sales. You will notice in my code I do not have the parameters to take dates into account, which what I am after is is an opportunity is closed within the month of Januaray 2015, then a certain field on the custom object will be the rollup for all opps closed in Janurary. There will be a field for each month of the 2015 year that will need to be populated with amounts from closed won opps in that particular month for that specific salesperson. So far my trigger and class is build to test the waters just to see that the rollup is working, but I am receiving an error when attempting to save an opportunity. So I am hopeful that someone here would be nice enough to tell me where I may be going wrong, and also some points into getting the above scenerio to work to bring over amounts from certail months into certain fields on the Custom Object. Again new at code so if I left anything out, please ask if that will help you to help me the newbie! :)
Here is my trigger code
trigger OpportunityRollUpEstPrice on Opportunity (after delete, after insert, after update, after undelete) {
if(trigger.isInsert || trigger.isUpdate || trigger.isUnDelete){
list<RollUpSummaryUtility.fieldDefinition> fieldDefinitions =
new list<RollUpSummaryUtility.fieldDefinition> {
new RollUpSummaryUtility.fieldDefinition('SUM', 'Estimated_Price__c',
'Jan_Rev_ACT__c')
};
RollUpSummaryUtility.rollUpTrigger(fieldDefinitions, trigger.new,
'Sales_Targets__c', 'Sales_Target__c', 'Opportunities', '');
}
if(trigger.isDelete){
list<RollUpSummaryUtility.fieldDefinition> fieldDefinitions =
new list<RollUpSummaryUtility.fieldDefinition> {
new RollUpSummaryUtility.fieldDefinition('SUM', 'Estimated_Price__c',
'Jan_Rev_ACT__c')
};
RollUpSummaryUtility.rollUpTrigger(fieldDefinitions, trigger.old,
'Jan_Rev_ACT__c', 'Opportunity__c', 'Opportunities', '');
}
}
Here is my Class -
public class RollUpSummaryUtility {
//the following class will be used to house the field names
//and desired operations
public class fieldDefinition {
public String operation {get;set;}
public String childField {get;set;}
public String parentField {get;set;}
public fieldDefinition (String o, String c, String p) {
operation = o;
childField = c;
parentField = p;
}
}
public static void rollUpTrigger(list<fieldDefinition> fieldDefinitions,
list<sObject> records, String childObject, String childParentLookupField,
String parentObject, String queryFilter) {
//Limit the size of list by using Sets which do not contain duplicate
//elements prevents hitting governor limits
set<Id> parentIds = new set<Id>();
for(sObject s : records) {
parentIds.add((Id)s.get(childParentLookupField));
}
//populate query text strings to be used in child aggregrator and
//parent value assignment
String fieldsToAggregate = '';
String parentFields = '';
for(fieldDefinition d : fieldDefinitions) {
fieldsToAggregate += d.operation + '(' + d.childField + ') ' +
', ';
parentFields += d.parentField + ', ';
}
//Using dynamic SOQL with aggergate results to populate parentValueMap
String aggregateQuery = 'Select ' + fieldsToAggregate +
childParentLookupField + ' from ' + childObject + ' where ' +
childParentLookupField + ' IN :parentIds ' + queryFilter + ' ' +
' group by ' + childParentLookupField;
//Map will contain one parent record Id per one aggregate object
map<Id, AggregateResult> parentValueMap =
new map <Id, AggregateResult>();
for(AggregateResult q : Database.query(aggregateQuery)){
parentValueMap.put((Id)q.get(childParentLookupField), q);
}
//list of parent object records to update
list<sObject> parentsToUpdate = new list<sObject>();
String parentQuery = 'select ' + parentFields + ' Id ' +
' from ' + parentObject + ' where Id IN :parentIds';
//for each affected parent object, retrieve aggregate results and
//for each field definition add aggregate value to parent field
for(sObject s : Database.query(parentQuery)) {
Integer row = 0; //row counter reset for every parent record
for(fieldDefinition d : fieldDefinitions) {
String field = 'expr' + row.format();
AggregateResult r = parentValueMap.get(s.Id);
//r will be null if no records exist
//(e.g. last record deleted)
if(r != null) {
Decimal value = ((Decimal)r.get(field) == null ) ? 0 :
(Decimal)r.get(field);
s.put(d.parentField, value);
} else {
s.put(d.parentField, 0);
}
row += 1; //plus 1 for every field definition after first
}
parentsToUpdate.add(s);
}
//if parent records exist, perform update of all parent records
//with a single DML statement
if(parentsToUpdate.Size() > 0) {
update parentsToUpdate;
}
}
}
Thanks again for any help you can provide, as I would love to get this working!
Shawn
- Shawn Reichner
- September 24, 2015
- Like
- 0
Help with Test Class
Team,
I have created an Apex Trigger and Class to populate a field based on the values in 2 other fields.
The trigger works like a charm, however I can not get the test class I created past 51 percent.
Can anyone save the day by looking over the following Triiger, class, and test class to advise me where I need to beef up the test class to promote to my production environemnt?
Thank you in advance for your help!
Shawn
Trigger Code
trigger TimeZoneextract on SVMXC__Service_Order__c (before insert, before update) {
List<SVMXC__Service_Order__c> Service_Orders = Trigger.new;
TimeZoneOffsetextraction.TimeZoneextract(Service_Orders);
Class Code
public class TimeZoneOffsetextraction {
public static void TimeZoneextract(List<SVMXC__Service_Order__c> Service_Orders) {
for (SVMXC__Service_Order__c w:Service_Orders){
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'GMT'){
w.Time_Zone_Offset__c = '-8';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'GMT'){
w.Time_Zone_Offset__c = '-7';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'GMT'){
w.Time_Zone_Offset__c = '-6';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'GMT'){
w.Time_Zone_Offset__c = '-5';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'GMT'){
w.Time_Zone_Offset__c = '-10';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'GMT'){
w.Time_Zone_Offset__c = '-10';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'AST'){
w.Time_Zone_Offset__c = '-4';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'AST'){
w.Time_Zone_Offset__c = '-3';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'AST'){
w.Time_Zone_Offset__c = '-2';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'AST'){
w.Time_Zone_Offset__c = '-1';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'AST'){
w.Time_Zone_Offset__c = '-6';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'AST'){
w.Time_Zone_Offset__c = '-6';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'EST'){
w.Time_Zone_Offset__c = '-3';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'EST'){
w.Time_Zone_Offset__c = '-2';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'EST'){
w.Time_Zone_Offset__c = '-1';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'EST'){
w.Time_Zone_Offset__c = '-5';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'EST'){
w.Time_Zone_Offset__c = '-5';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'EST'){
w.Time_Zone_Offset__c = '-0';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'CST'){
w.Time_Zone_Offset__c = '-2';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'CST'){
w.Time_Zone_Offset__c = '-1';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'CST'){
w.Time_Zone_Offset__c = '-0';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'CST'){
w.Time_Zone_Offset__c = '+1';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'CST'){
w.Time_Zone_Offset__c = '-4';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'CST'){
w.Time_Zone_Offset__c = '-4';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'MST'){
w.Time_Zone_Offset__c = '-1';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'MST'){
w.Time_Zone_Offset__c = '-0';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'MST'){
w.Time_Zone_Offset__c = '+1';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'MST'){
w.Time_Zone_Offset__c = '+2';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'MST'){
w.Time_Zone_Offset__c = '-3';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'MST'){
w.Time_Zone_Offset__c = '-3';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'PST'){
w.Time_Zone_Offset__c = '-0';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'PST'){
w.Time_Zone_Offset__c = '+1';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'PST'){
w.Time_Zone_Offset__c = '+2';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'PST'){
w.Time_Zone_Offset__c = '+3';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'PST'){
w.Time_Zone_Offset__c = '-2';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'PST'){
w.Time_Zone_Offset__c = '-2';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'AHST'){
w.Time_Zone_Offset__c = '+2';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'AHST'){
w.Time_Zone_Offset__c = '+3';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'AHST'){
w.Time_Zone_Offset__c = '+4';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'AHST'){
w.Time_Zone_Offset__c = '+5';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'AHST'){
w.Time_Zone_Offset__c = '-0';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'AHST'){
w.Time_Zone_Offset__c = '-0';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'CET'){
w.Time_Zone_Offset__c = '-9';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'CET'){
w.Time_Zone_Offset__c = '-8';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'CET'){
w.Time_Zone_Offset__c = '-7';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'CET'){
w.Time_Zone_Offset__c = '-6';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'CET'){
w.Time_Zone_Offset__c = '-11';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'CET'){
w.Time_Zone_Offset__c = '-11';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'EET'){
w.Time_Zone_Offset__c = '-10';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'EET'){
w.Time_Zone_Offset__c = '-9';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'EET'){
w.Time_Zone_Offset__c = '-8';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'EET'){
w.Time_Zone_Offset__c = '-7';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'EET'){
w.Time_Zone_Offset__c = '-12';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'EET'){
w.Time_Zone_Offset__c = '-12';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'BT'){
w.Time_Zone_Offset__c = '-11';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'BT'){
w.Time_Zone_Offset__c = '-10';
}
IF (w.Account_Time_Zone__c == 'cST' && w.My_Time_Zone__c == 'BT'){
w.Time_Zone_Offset__c = '-9';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'BT'){
w.Time_Zone_Offset__c = '-8';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'BT'){
w.Time_Zone_Offset__c = '-13';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'BT'){
w.Time_Zone_Offset__c = '-13';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'CCT'){
w.Time_Zone_Offset__c = '-16';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'CCT'){
w.Time_Zone_Offset__c = '-15';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'CCT'){
w.Time_Zone_Offset__c = '-14';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'CCT'){
w.Time_Zone_Offset__c = '-13';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'CCT'){
w.Time_Zone_Offset__c = '-18';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'CCT'){
w.Time_Zone_Offset__c = '-18';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'JST'){
w.Time_Zone_Offset__c = '-17';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'JST'){
w.Time_Zone_Offset__c = '-16';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'JST'){
w.Time_Zone_Offset__c = '-15';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'JST'){
w.Time_Zone_Offset__c = '-14';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'JST'){
w.Time_Zone_Offset__c = '-19';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'JST'){
w.Time_Zone_Offset__c = '-19';
}
}
}
}
Test Class
@isTest(SeeAllData = true)
private class TestTimeZoneOffsetextraction {
//test method
static testMethod void testService_Order() {
SVMXC__Service_Order__c w = New SVMXC__Service_Order__c (
SVMXC__Case__c = '5004000000bSVJt',
SVMXC__Company__c = '0014000000OCOao',
SVMXC__Contact__c = '0034000001CZCxg',
SVMXC__Order_Status__c = 'Open',
SVMXC__Order_Type__c = 'Field Service',
SVMXC__Priority__c = 'P4',
Escallations__c = 'Tier 1 - AVI-SPL Field Techs',
Is_Billable_new__c = 'No',
SVMXC__Purpose_of_Visit__c = 'Testing',
SVMXC__Billing_Type__c = 'Contract',
Alert_Message__c = 'Testing',
Criticality__c = 'T&M',
Rate_Category_wm__c = 'Metro 6-8pm',
After_Hours_or_Holiday__c = 'No',
Day__c = 'Weekday',
Internal_Comments__c = 'Testing',
Initial_Room_Availability__c = 'Testing',
wm_desired_skills__c = 'Testing',
Technician_wm__c = 'Test Tester',
Technician_email_wm__c = 'test@test.com',
SVMXC__City__c = 'Tampa',
SVMXC__Street__c = '123 Anywhere street',
SVMXC__Zip__c = '33615',
SVMXC__Country__c = 'United States',
SVMXC__State__c = 'WA',
My_Time_Zone__c = 'MST',
Time_Zone_Offset__c = '-1',
SVMXC__Problem_Description__c = 'Testing',
Dispatch_Detail__c = 'Testing');
insert w;
SVMXC__Service_Order__c pop1 = [SELECT Id, Account_Time_Zone__c FROM SVMXC__Service_Order__c Where ID =:w.ID];
system.debug(pop1.Account_Time_Zone__c);
}
}
I have created an Apex Trigger and Class to populate a field based on the values in 2 other fields.
The trigger works like a charm, however I can not get the test class I created past 51 percent.
Can anyone save the day by looking over the following Triiger, class, and test class to advise me where I need to beef up the test class to promote to my production environemnt?
Thank you in advance for your help!
Shawn
Trigger Code
trigger TimeZoneextract on SVMXC__Service_Order__c (before insert, before update) {
List<SVMXC__Service_Order__c> Service_Orders = Trigger.new;
TimeZoneOffsetextraction.TimeZoneextract(Service_Orders);
Class Code
public class TimeZoneOffsetextraction {
public static void TimeZoneextract(List<SVMXC__Service_Order__c> Service_Orders) {
for (SVMXC__Service_Order__c w:Service_Orders){
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'GMT'){
w.Time_Zone_Offset__c = '-8';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'GMT'){
w.Time_Zone_Offset__c = '-7';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'GMT'){
w.Time_Zone_Offset__c = '-6';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'GMT'){
w.Time_Zone_Offset__c = '-5';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'GMT'){
w.Time_Zone_Offset__c = '-10';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'GMT'){
w.Time_Zone_Offset__c = '-10';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'AST'){
w.Time_Zone_Offset__c = '-4';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'AST'){
w.Time_Zone_Offset__c = '-3';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'AST'){
w.Time_Zone_Offset__c = '-2';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'AST'){
w.Time_Zone_Offset__c = '-1';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'AST'){
w.Time_Zone_Offset__c = '-6';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'AST'){
w.Time_Zone_Offset__c = '-6';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'EST'){
w.Time_Zone_Offset__c = '-3';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'EST'){
w.Time_Zone_Offset__c = '-2';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'EST'){
w.Time_Zone_Offset__c = '-1';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'EST'){
w.Time_Zone_Offset__c = '-5';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'EST'){
w.Time_Zone_Offset__c = '-5';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'EST'){
w.Time_Zone_Offset__c = '-0';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'CST'){
w.Time_Zone_Offset__c = '-2';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'CST'){
w.Time_Zone_Offset__c = '-1';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'CST'){
w.Time_Zone_Offset__c = '-0';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'CST'){
w.Time_Zone_Offset__c = '+1';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'CST'){
w.Time_Zone_Offset__c = '-4';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'CST'){
w.Time_Zone_Offset__c = '-4';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'MST'){
w.Time_Zone_Offset__c = '-1';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'MST'){
w.Time_Zone_Offset__c = '-0';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'MST'){
w.Time_Zone_Offset__c = '+1';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'MST'){
w.Time_Zone_Offset__c = '+2';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'MST'){
w.Time_Zone_Offset__c = '-3';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'MST'){
w.Time_Zone_Offset__c = '-3';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'PST'){
w.Time_Zone_Offset__c = '-0';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'PST'){
w.Time_Zone_Offset__c = '+1';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'PST'){
w.Time_Zone_Offset__c = '+2';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'PST'){
w.Time_Zone_Offset__c = '+3';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'PST'){
w.Time_Zone_Offset__c = '-2';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'PST'){
w.Time_Zone_Offset__c = '-2';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'AHST'){
w.Time_Zone_Offset__c = '+2';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'AHST'){
w.Time_Zone_Offset__c = '+3';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'AHST'){
w.Time_Zone_Offset__c = '+4';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'AHST'){
w.Time_Zone_Offset__c = '+5';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'AHST'){
w.Time_Zone_Offset__c = '-0';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'AHST'){
w.Time_Zone_Offset__c = '-0';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'CET'){
w.Time_Zone_Offset__c = '-9';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'CET'){
w.Time_Zone_Offset__c = '-8';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'CET'){
w.Time_Zone_Offset__c = '-7';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'CET'){
w.Time_Zone_Offset__c = '-6';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'CET'){
w.Time_Zone_Offset__c = '-11';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'CET'){
w.Time_Zone_Offset__c = '-11';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'EET'){
w.Time_Zone_Offset__c = '-10';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'EET'){
w.Time_Zone_Offset__c = '-9';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'EET'){
w.Time_Zone_Offset__c = '-8';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'EET'){
w.Time_Zone_Offset__c = '-7';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'EET'){
w.Time_Zone_Offset__c = '-12';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'EET'){
w.Time_Zone_Offset__c = '-12';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'BT'){
w.Time_Zone_Offset__c = '-11';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'BT'){
w.Time_Zone_Offset__c = '-10';
}
IF (w.Account_Time_Zone__c == 'cST' && w.My_Time_Zone__c == 'BT'){
w.Time_Zone_Offset__c = '-9';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'BT'){
w.Time_Zone_Offset__c = '-8';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'BT'){
w.Time_Zone_Offset__c = '-13';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'BT'){
w.Time_Zone_Offset__c = '-13';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'CCT'){
w.Time_Zone_Offset__c = '-16';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'CCT'){
w.Time_Zone_Offset__c = '-15';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'CCT'){
w.Time_Zone_Offset__c = '-14';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'CCT'){
w.Time_Zone_Offset__c = '-13';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'CCT'){
w.Time_Zone_Offset__c = '-18';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'CCT'){
w.Time_Zone_Offset__c = '-18';
}
IF (w.Account_Time_Zone__c == 'PST' && w.My_Time_Zone__c == 'JST'){
w.Time_Zone_Offset__c = '-17';
}
IF (w.Account_Time_Zone__c == 'MST' && w.My_Time_Zone__c == 'JST'){
w.Time_Zone_Offset__c = '-16';
}
IF (w.Account_Time_Zone__c == 'CST' && w.My_Time_Zone__c == 'JST'){
w.Time_Zone_Offset__c = '-15';
}
IF (w.Account_Time_Zone__c == 'EST' && w.My_Time_Zone__c == 'JST'){
w.Time_Zone_Offset__c = '-14';
}
IF (w.Account_Time_Zone__c == 'AKST' && w.My_Time_Zone__c == 'JST'){
w.Time_Zone_Offset__c = '-19';
}
IF (w.Account_Time_Zone__c == 'HST' && w.My_Time_Zone__c == 'JST'){
w.Time_Zone_Offset__c = '-19';
}
}
}
}
Test Class
@isTest(SeeAllData = true)
private class TestTimeZoneOffsetextraction {
//test method
static testMethod void testService_Order() {
SVMXC__Service_Order__c w = New SVMXC__Service_Order__c (
SVMXC__Case__c = '5004000000bSVJt',
SVMXC__Company__c = '0014000000OCOao',
SVMXC__Contact__c = '0034000001CZCxg',
SVMXC__Order_Status__c = 'Open',
SVMXC__Order_Type__c = 'Field Service',
SVMXC__Priority__c = 'P4',
Escallations__c = 'Tier 1 - AVI-SPL Field Techs',
Is_Billable_new__c = 'No',
SVMXC__Purpose_of_Visit__c = 'Testing',
SVMXC__Billing_Type__c = 'Contract',
Alert_Message__c = 'Testing',
Criticality__c = 'T&M',
Rate_Category_wm__c = 'Metro 6-8pm',
After_Hours_or_Holiday__c = 'No',
Day__c = 'Weekday',
Internal_Comments__c = 'Testing',
Initial_Room_Availability__c = 'Testing',
wm_desired_skills__c = 'Testing',
Technician_wm__c = 'Test Tester',
Technician_email_wm__c = 'test@test.com',
SVMXC__City__c = 'Tampa',
SVMXC__Street__c = '123 Anywhere street',
SVMXC__Zip__c = '33615',
SVMXC__Country__c = 'United States',
SVMXC__State__c = 'WA',
My_Time_Zone__c = 'MST',
Time_Zone_Offset__c = '-1',
SVMXC__Problem_Description__c = 'Testing',
Dispatch_Detail__c = 'Testing');
insert w;
SVMXC__Service_Order__c pop1 = [SELECT Id, Account_Time_Zone__c FROM SVMXC__Service_Order__c Where ID =:w.ID];
system.debug(pop1.Account_Time_Zone__c);
}
}
- Shawn Reichner
- November 17, 2014
- Like
- 0
Using VF Page and Class to Show Custom Object records on Account Page Layouts
Team,
I have created the following Apex Class Extension and VF Page which when placed on our Account Page Layouts gives me the following error...
Content cannot be displayed: SObject row was retrieved via SOQL without querying the requested field: Account.Account_Name__c
I am a little confused as I am a beginner with coding, but I am thinking I am requesting the correct field.
Please help me by looking over my code as follows... Thank you for your time, and I thank you in advance to whoever can save the day!
Shawn
Apex Class
/*
Class Name:
Description: This Class is used to display Bill To Address details in Account page as in-line visual force page.
Date Created: 12-11-2014.
*/
public class PopulatebilltoInfoHandler
{
Account ac= new Account();
List<Bill_to_Address__c> roomLoclist = new List<Bill_to_Address__c>();
private Integer counter=0;
private Integer list_size=2000;
public Id accId;
private Integer total_size;
public PopulatebilltoInfoHandler(ApexPages.StandardController controller)
{
ac = (Account)controller.getRecord();
accId = ac.Account_Name__c;
//populateBilltoInfo();
total_size = [Select count() From Bill_to_Address__c Where (Bill_to_Address__c.Account_Name__c = :ac.Account_Name__c)];
}
public List<Bill_to_Address__c> getroomList()
{
try
{
roomLoclist = [Select Id,Name,Customer_Number__c,City__c,State__c,Zip__c
From Bill_to_Address__c];
}
catch(Exception e){system.debug('Query Exception'+e.getMessage());}
if(roomLoclist != null && roomLoclist.size()>0)
return roomLoclist;
else
return roomLoclist;
}
public PageReference Previous()
{
counter-=list_size;
return null;
}
public PageReference Next()
{
counter+=list_size;
return null;
}
public Boolean getDisablePrevious()
{
if(counter >0)
return false;
else
return true;
}
public Boolean getDisableNext()
{
if(counter+list_size < total_size)
return false;
else return true;
}
}
VF Page Code
<apex:page standardcontroller="Account" extensions="PopulatebilltoInfoHandler" id="lolinePage">
<apex:stylesheet value="{!$Resource.pdfresources}"/>
<apex:pageBlock title="Bill-To Details">
<apex:pageBlockTable value="{!roomList}" var="loline" id="lolinedetails">
<apex:column >
<apex:facet name="header">Bill To Address</apex:facet>
<a href="/{!loline.Name}" target="_parent">{!loline.Name}</a>
</apex:column>
<apex:column >
<apex:facet name="header">City</apex:facet>
<apex:outputText value="{!loline.City__c}"/>
</apex:column>
<apex:column >
<apex:facet name="header">State</apex:facet>
<apex:outputText value="{!loline.State__c}"/>
</apex:column>
<apex:column >
<apex:facet name="header">Zip</apex:facet>
<apex:outputField value="{!loline.Zip__c}"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
<apex:outputPanel id="myButtons" layout="block">
<apex:form >
<apex:panelGrid cellpadding="7" columns="4">
<apex:commandButton value="<Previous" action="{!Previous}" disabled="{!DisablePrevious}" reRender="lolinedetails,myButtons"/>
<apex:commandButton value="Next>" action="{!Next}" disabled="{!DisableNext}" reRender="lolinedetails,myButtons"/>
</apex:panelGrid>
</apex:form>
</apex:outputPanel>
</apex:page>
I have created the following Apex Class Extension and VF Page which when placed on our Account Page Layouts gives me the following error...
Content cannot be displayed: SObject row was retrieved via SOQL without querying the requested field: Account.Account_Name__c
I am a little confused as I am a beginner with coding, but I am thinking I am requesting the correct field.
Please help me by looking over my code as follows... Thank you for your time, and I thank you in advance to whoever can save the day!
Shawn
Apex Class
/*
Class Name:
Description: This Class is used to display Bill To Address details in Account page as in-line visual force page.
Date Created: 12-11-2014.
*/
public class PopulatebilltoInfoHandler
{
Account ac= new Account();
List<Bill_to_Address__c> roomLoclist = new List<Bill_to_Address__c>();
private Integer counter=0;
private Integer list_size=2000;
public Id accId;
private Integer total_size;
public PopulatebilltoInfoHandler(ApexPages.StandardController controller)
{
ac = (Account)controller.getRecord();
accId = ac.Account_Name__c;
//populateBilltoInfo();
total_size = [Select count() From Bill_to_Address__c Where (Bill_to_Address__c.Account_Name__c = :ac.Account_Name__c)];
}
public List<Bill_to_Address__c> getroomList()
{
try
{
roomLoclist = [Select Id,Name,Customer_Number__c,City__c,State__c,Zip__c
From Bill_to_Address__c];
}
catch(Exception e){system.debug('Query Exception'+e.getMessage());}
if(roomLoclist != null && roomLoclist.size()>0)
return roomLoclist;
else
return roomLoclist;
}
public PageReference Previous()
{
counter-=list_size;
return null;
}
public PageReference Next()
{
counter+=list_size;
return null;
}
public Boolean getDisablePrevious()
{
if(counter >0)
return false;
else
return true;
}
public Boolean getDisableNext()
{
if(counter+list_size < total_size)
return false;
else return true;
}
}
VF Page Code
<apex:page standardcontroller="Account" extensions="PopulatebilltoInfoHandler" id="lolinePage">
<apex:stylesheet value="{!$Resource.pdfresources}"/>
<apex:pageBlock title="Bill-To Details">
<apex:pageBlockTable value="{!roomList}" var="loline" id="lolinedetails">
<apex:column >
<apex:facet name="header">Bill To Address</apex:facet>
<a href="/{!loline.Name}" target="_parent">{!loline.Name}</a>
</apex:column>
<apex:column >
<apex:facet name="header">City</apex:facet>
<apex:outputText value="{!loline.City__c}"/>
</apex:column>
<apex:column >
<apex:facet name="header">State</apex:facet>
<apex:outputText value="{!loline.State__c}"/>
</apex:column>
<apex:column >
<apex:facet name="header">Zip</apex:facet>
<apex:outputField value="{!loline.Zip__c}"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
<apex:outputPanel id="myButtons" layout="block">
<apex:form >
<apex:panelGrid cellpadding="7" columns="4">
<apex:commandButton value="<Previous" action="{!Previous}" disabled="{!DisablePrevious}" reRender="lolinedetails,myButtons"/>
<apex:commandButton value="Next>" action="{!Next}" disabled="{!DisableNext}" reRender="lolinedetails,myButtons"/>
</apex:panelGrid>
</apex:form>
</apex:outputPanel>
</apex:page>
- Shawn Reichner
- November 12, 2014
- Like
- 0
Help With Testing Standard Controller Extension
Hello,
I have created my first Standard Controller Extention for Case standard controller to include attachments on a VF Page for case submissions.
I have not created a test class to test the controller extension before, and after looking at example after example I am even more confused now.
Can someone please help me write a test class for the following Controller extension class so that I can move this into my production environment.
Any help will be greatly appreciated, as I am very new to apex development and especially writing test classes.
Controller Extension Code:
public with sharing class sfdevcaseattachment
{
public case objcase{get;set;}
public String subj {get;set;}
public String description {get;set;}
public String Initiating_Requestor {get;set;}
public Attachment myAttachment{get;set;}
public string fileName{get;set;}
public Blob fileBody{get;set;}
public sfdevcaseattachment(Apexpages.standardcontroller controller)
{
objcase = new case();
myAttachment =new Attachment();
}
public pagereference save()
{
insert objcase;
if (fileName != null && fileName.trim().length() > 0 && fileBody != null) {
myAttachment = new Attachment();
Integer i=0;
myAttachment .clear();
myAttachment.Body = fileBody;
myAttachment.Name = this.fileName;
myAttachment.ParentId = objcase.id;
insert myAttachment;
}
pagereference pr = new pagereference('/'+objcase.id);
return pr;
}
}
Thank you again in advance for your help.....I have spent 3 days now studying on how to do this and I am more of a visual learner so I am completely lost.
Shawn
I have created my first Standard Controller Extention for Case standard controller to include attachments on a VF Page for case submissions.
I have not created a test class to test the controller extension before, and after looking at example after example I am even more confused now.
Can someone please help me write a test class for the following Controller extension class so that I can move this into my production environment.
Any help will be greatly appreciated, as I am very new to apex development and especially writing test classes.
Controller Extension Code:
public with sharing class sfdevcaseattachment
{
public case objcase{get;set;}
public String subj {get;set;}
public String description {get;set;}
public String Initiating_Requestor {get;set;}
public Attachment myAttachment{get;set;}
public string fileName{get;set;}
public Blob fileBody{get;set;}
public sfdevcaseattachment(Apexpages.standardcontroller controller)
{
objcase = new case();
myAttachment =new Attachment();
}
public pagereference save()
{
insert objcase;
if (fileName != null && fileName.trim().length() > 0 && fileBody != null) {
myAttachment = new Attachment();
Integer i=0;
myAttachment .clear();
myAttachment.Body = fileBody;
myAttachment.Name = this.fileName;
myAttachment.ParentId = objcase.id;
insert myAttachment;
}
pagereference pr = new pagereference('/'+objcase.id);
return pr;
}
}
Thank you again in advance for your help.....I have spent 3 days now studying on how to do this and I am more of a visual learner so I am completely lost.
Shawn
- Shawn Reichner
- October 24, 2014
- Like
- 0
Help with Controller Extension Code
Hello,
I am building a "Site" for guest users to submit a Case for support. I have the site built, the visualforce page, and a controller extension built to add an attchment. When the case is submitted form the site, it creates a Case record in Salesforce, the attachment shows under the notes and attachments related list, but the subject and description fields that were filled out on the Site are not being populated on the case record.
I am at a loss here as to why they are not working, and I am a new developer so I very well could have missed something very easy. Please look over the following code for my VF Page, and the controller extension, and if available please help me figure out how to get the subject and description fields to populate on the case record with the information that was submitted via the site submission.
Thank you in advance for your time and help!
VF Page
<apex:page standardcontroller="Case" extensions="caseattachment"
showHeader="false">
<img src="{!$resource.AVISPL_Logo2}"></img><b/><b/>
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection title="Hello, Thank You For Reporting Your Incident! A Salesforce Platform Engineer Will Be In Touch Shortly. " columns="1" showHeader="True" collapsible="False">
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageMessages />
<apex:pageBlock >
<apex:inputField value="{!Case.CaseNumber}"/>
<apex:pageBlockSection title="Subject">
<apex:inputText value="{!Case.subject}" />
</apex:pageBlockSection>
<apex:pageBlockSection title="Attachment Or ScreenShot">
<apex:inputFile id="fileToUpload" value="{!fileBody}" filename="{!fileName}" styleClass="input-file"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Tell Us About The Incident">
<apex:inputTextarea value="{!Case.Description}" rows="8" cols="80" />
</apex:pageBlockSection>
<apex:commandButton value="Submit Incident" action="{!Save}" />
</apex:pageBlock>
</apex:form>
</apex:page>
Controller extension
public class caseattachment
{
public case objcase{get;set;}
public Attachment myAttachment{get;set;}
public string fileName{get;set;}
public Blob fileBody{get;set;}
public caseattachment(Apexpages.standardcontroller controller)
{
objcase = new case();
myAttachment =new Attachment();
}
public pagereference save()
{
insert objcase;
System.debug('@@@@@fileBody'+fileBody);
myAttachment = new Attachment();
Integer i=0;
myAttachment .clear();
myAttachment.Body = fileBody;
myAttachment.Name = this.fileName;
myAttachment.ParentId = objcase.id;
insert myAttachment;
pagereference pr = new pagereference('/'+objcase.id);
return pr;
}
}
I am building a "Site" for guest users to submit a Case for support. I have the site built, the visualforce page, and a controller extension built to add an attchment. When the case is submitted form the site, it creates a Case record in Salesforce, the attachment shows under the notes and attachments related list, but the subject and description fields that were filled out on the Site are not being populated on the case record.
I am at a loss here as to why they are not working, and I am a new developer so I very well could have missed something very easy. Please look over the following code for my VF Page, and the controller extension, and if available please help me figure out how to get the subject and description fields to populate on the case record with the information that was submitted via the site submission.
Thank you in advance for your time and help!
VF Page
<apex:page standardcontroller="Case" extensions="caseattachment"
showHeader="false">
<img src="{!$resource.AVISPL_Logo2}"></img><b/><b/>
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection title="Hello, Thank You For Reporting Your Incident! A Salesforce Platform Engineer Will Be In Touch Shortly. " columns="1" showHeader="True" collapsible="False">
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageMessages />
<apex:pageBlock >
<apex:inputField value="{!Case.CaseNumber}"/>
<apex:pageBlockSection title="Subject">
<apex:inputText value="{!Case.subject}" />
</apex:pageBlockSection>
<apex:pageBlockSection title="Attachment Or ScreenShot">
<apex:inputFile id="fileToUpload" value="{!fileBody}" filename="{!fileName}" styleClass="input-file"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Tell Us About The Incident">
<apex:inputTextarea value="{!Case.Description}" rows="8" cols="80" />
</apex:pageBlockSection>
<apex:commandButton value="Submit Incident" action="{!Save}" />
</apex:pageBlock>
</apex:form>
</apex:page>
Controller extension
public class caseattachment
{
public case objcase{get;set;}
public Attachment myAttachment{get;set;}
public string fileName{get;set;}
public Blob fileBody{get;set;}
public caseattachment(Apexpages.standardcontroller controller)
{
objcase = new case();
myAttachment =new Attachment();
}
public pagereference save()
{
insert objcase;
System.debug('@@@@@fileBody'+fileBody);
myAttachment = new Attachment();
Integer i=0;
myAttachment .clear();
myAttachment.Body = fileBody;
myAttachment.Name = this.fileName;
myAttachment.ParentId = objcase.id;
insert myAttachment;
pagereference pr = new pagereference('/'+objcase.id);
return pr;
}
}
- Shawn Reichner
- October 22, 2014
- Like
- 0
Help with Site VisualForce Page Not Populating fields on Case Record
Hello,
I am building a "Site" for guest users to submit a Case for support. I have the site built, the visualforce page, and a controller extension built to add an attchment. When the case is submitted form the site, it creates a Case record in Salesforce, the attachment shows under the notes and attachments related list, but the subject and description fields that were filled out on the Site are not being populated on the case record.
I am at a loss here as to why they are not working, and I am a new developer so I very well could have missed something very easy. Please look over the following code for my VF Page, and the controller extension, and if available please help me figure out how to get the subject and description fields to populate on the case record with the information that was submitted via the site submission.
Thank you in advance for your time and help!
VF Page
<apex:page standardcontroller="Case" extensions="caseattachment"
showHeader="false">
<img src="{!$resource.AVISPL_Logo2}"></img><b/><b/>
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection title="Hello, Thank You For Reporting Your Incident! A Salesforce Platform Engineer Will Be In Touch Shortly. " columns="1" showHeader="True" collapsible="False">
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageMessages />
<apex:pageBlock >
<apex:inputField value="{!Case.CaseNumber}"/>
<apex:pageBlockSection title="Subject">
<apex:inputText value="{!Case.subject}" />
</apex:pageBlockSection>
<apex:pageBlockSection title="Attachment Or ScreenShot">
<apex:inputFile id="fileToUpload" value="{!fileBody}" filename="{!fileName}" styleClass="input-file"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Tell Us About The Incident">
<apex:inputTextarea value="{!Case.Description}" rows="8" cols="80" />
</apex:pageBlockSection>
<apex:commandButton value="Submit Incident" action="{!Save}" />
</apex:pageBlock>
</apex:form>
</apex:page>
Controller extension
public class caseattachment
{
public case objcase{get;set;}
public Attachment myAttachment{get;set;}
public string fileName{get;set;}
public Blob fileBody{get;set;}
public caseattachment(Apexpages.standardcontroller controller)
{
objcase = new case();
myAttachment =new Attachment();
}
public pagereference save()
{
insert objcase;
System.debug('@@@@@fileBody'+fileBody);
myAttachment = new Attachment();
Integer i=0;
myAttachment .clear();
myAttachment.Body = fileBody;
myAttachment.Name = this.fileName;
myAttachment.ParentId = objcase.id;
insert myAttachment;
pagereference pr = new pagereference('/'+objcase.id);
return pr;
}
}
I am building a "Site" for guest users to submit a Case for support. I have the site built, the visualforce page, and a controller extension built to add an attchment. When the case is submitted form the site, it creates a Case record in Salesforce, the attachment shows under the notes and attachments related list, but the subject and description fields that were filled out on the Site are not being populated on the case record.
I am at a loss here as to why they are not working, and I am a new developer so I very well could have missed something very easy. Please look over the following code for my VF Page, and the controller extension, and if available please help me figure out how to get the subject and description fields to populate on the case record with the information that was submitted via the site submission.
Thank you in advance for your time and help!
VF Page
<apex:page standardcontroller="Case" extensions="caseattachment"
showHeader="false">
<img src="{!$resource.AVISPL_Logo2}"></img><b/><b/>
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection title="Hello, Thank You For Reporting Your Incident! A Salesforce Platform Engineer Will Be In Touch Shortly. " columns="1" showHeader="True" collapsible="False">
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageMessages />
<apex:pageBlock >
<apex:inputField value="{!Case.CaseNumber}"/>
<apex:pageBlockSection title="Subject">
<apex:inputText value="{!Case.subject}" />
</apex:pageBlockSection>
<apex:pageBlockSection title="Attachment Or ScreenShot">
<apex:inputFile id="fileToUpload" value="{!fileBody}" filename="{!fileName}" styleClass="input-file"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Tell Us About The Incident">
<apex:inputTextarea value="{!Case.Description}" rows="8" cols="80" />
</apex:pageBlockSection>
<apex:commandButton value="Submit Incident" action="{!Save}" />
</apex:pageBlock>
</apex:form>
</apex:page>
Controller extension
public class caseattachment
{
public case objcase{get;set;}
public Attachment myAttachment{get;set;}
public string fileName{get;set;}
public Blob fileBody{get;set;}
public caseattachment(Apexpages.standardcontroller controller)
{
objcase = new case();
myAttachment =new Attachment();
}
public pagereference save()
{
insert objcase;
System.debug('@@@@@fileBody'+fileBody);
myAttachment = new Attachment();
Integer i=0;
myAttachment .clear();
myAttachment.Body = fileBody;
myAttachment.Name = this.fileName;
myAttachment.ParentId = objcase.id;
insert myAttachment;
pagereference pr = new pagereference('/'+objcase.id);
return pr;
}
}
- Shawn Reichner
- October 22, 2014
- Like
- 0
Case Trigger Not Firing
Hello,
I have created a class and trigger which I will paste below. These are on the case object and in sandbox at the moment until I can get them to operate correctly.
What I want to happen is when a certain picklist choice is chosen, I woudl like the trigger to automatically populate another field with a certain value.
Here is my code currently, can anyone please help with figuring out why this is not updating the field when that picklist value is chosen and the case record is saved?
Thank you,
Class
public class salespersonextraction {
public static void salesextract(List<Case> Cases){
for (Case c:Cases){
IF (c.AVI_SPL_Rep_Whse_Office_Code_2011__c == 'AB_Calgary_780S_780600_CAD'){
c.Salesperson_Extraction_Code__c = '780S';
IF (c.AVI_SPL_Rep_Whse_Office_Code_2011__c == 'AL_Birmingham_120S_120600_AVI'){
c.Salesperson_Extraction_Code__c = '120S';
}}}
}}
Trigger
trigger Salesextract on Case (before insert, before update) {
List<Case> Cases = Trigger.new;
salespersonextraction.salesextract(Cases);
}
I have created a class and trigger which I will paste below. These are on the case object and in sandbox at the moment until I can get them to operate correctly.
What I want to happen is when a certain picklist choice is chosen, I woudl like the trigger to automatically populate another field with a certain value.
Here is my code currently, can anyone please help with figuring out why this is not updating the field when that picklist value is chosen and the case record is saved?
Thank you,
Class
public class salespersonextraction {
public static void salesextract(List<Case> Cases){
for (Case c:Cases){
IF (c.AVI_SPL_Rep_Whse_Office_Code_2011__c == 'AB_Calgary_780S_780600_CAD'){
c.Salesperson_Extraction_Code__c = '780S';
IF (c.AVI_SPL_Rep_Whse_Office_Code_2011__c == 'AL_Birmingham_120S_120600_AVI'){
c.Salesperson_Extraction_Code__c = '120S';
}}}
}}
Trigger
trigger Salesextract on Case (before insert, before update) {
List<Case> Cases = Trigger.new;
salespersonextraction.salesextract(Cases);
}
- Shawn Reichner
- September 12, 2014
- Like
- 0
Case Trigger Not Firing Approval Process
Hello,
I have created a case trigger with the following code.....
trigger CaseApproval on Case (after insert, after update) {
for (Case currentCase : Trigger.new) {
if (currentCase.RecordType.Name == 'SF_Dev_Requests')
{
Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
req.setComments('Submitted for approval. Please approve.');
req.setObjectId(currentCase.Id);
Approval.ProcessResult result = Approval.process(req);
}
}
The trigger is not firing the approval processes when a case with the record type mentioned in the trigger code is created.
Can someone please help me understand what may be causing the trigger to not fire, and help me resolve this issue to have these types of incoming cases auto start the approval process?
Thank you for all of your help in advance,
Shawn
I have created a case trigger with the following code.....
trigger CaseApproval on Case (after insert, after update) {
for (Case currentCase : Trigger.new) {
if (currentCase.RecordType.Name == 'SF_Dev_Requests')
{
Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
req.setComments('Submitted for approval. Please approve.');
req.setObjectId(currentCase.Id);
Approval.ProcessResult result = Approval.process(req);
}
}
The trigger is not firing the approval processes when a case with the record type mentioned in the trigger code is created.
Can someone please help me understand what may be causing the trigger to not fire, and help me resolve this issue to have these types of incoming cases auto start the approval process?
Thank you for all of your help in advance,
Shawn
- Shawn Reichner
- September 10, 2014
- Like
- 0
Automating Case approval process when Case is created
Hello,
I am very new to working with apex triggers and classes, and I am hoping for some help with creating an automated solution to the following scenerio....
When a case is created with a specific record type, the approval process that has been created will automatically start without the user having to press the submit for approval button.
Any ideas how I woudl do this on the standard case object and how to write the trigger and class itself???
Help me please, I woudl greatly appreciate it!
Thank you in advance,
Shawn
I am very new to working with apex triggers and classes, and I am hoping for some help with creating an automated solution to the following scenerio....
When a case is created with a specific record type, the approval process that has been created will automatically start without the user having to press the submit for approval button.
Any ideas how I woudl do this on the standard case object and how to write the trigger and class itself???
Help me please, I woudl greatly appreciate it!
Thank you in advance,
Shawn
- Shawn Reichner
- September 10, 2014
- Like
- 0
Controller Extension for Standard Case Controller
Friends,
I have a Visualforce page that has been created, and what I want to do is when the Visualforce page is submitted to create a case by clicking on the save button on the Visualforce page, I want the user to be redirected to another visualforce page thanking the user for thier submission with the newly created case number.
I know I will have to create a Standard controller extention, but I am not familiar with this process at all, and any help would be very much appreciated.
Here is the Visualforce page code I have created, and for our example purposes the VF page for the redirect we will name Thank_You.
Please help however you can by telling me how to create a custom extentsion to add functionality to redirect to the Thank_You Visualforce page after the standard Save has been completed.
Thank you so much!
<apex:page standardController="Case">
<img src="{!$resource.AVISPL_Logo2}"></img>
<apex:pageBlock >
<apex:pageBlockSection title="Hello, Thank You For Your Project Request !" columns="1" showHeader="True" collapsible="False">
</apex:pageBlockSection>
</apex:pageBlock>
<apex:form >
<apex:pageBlock tabStyle="Case" title="Impact" >
<apex:pageBlockSection >
<apex:inputField value="{!Case.Number_of_Users_Affected__c}"/>
<apex:inputField value="{!Case.Area_s_Affected__c}"/>
<apex:inputField value="{!Case.Functionality_Affected__c}"/>
<apex:inputField value="{!Case.Profile_s_Affected__c}"/>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock title="Description Information" >
<apex:pageBlockSection >
<apex:inputField value="{!Case.Subject}"/>
<apex:inputField value="{!Case.Driver__c}"/>
<apex:inputField value="{!Case.Benefit_Of_Change__c}"/>
<apex:inputField value="{!Case.Reason_For_Change__c}"/>
<apex:inputField value="{!Case.Description}"/>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock title="Deadlines and Project Status" >
<apex:pageBlockSection >
<apex:inputField value="{!Case.Target_Deadline__c}"/>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock title="Requesting Department Information" >
<apex:pageBlockSection >
<apex:inputField value="{!Case.Sponsoring_Department_s__c}"/>
<apex:inputField value="{!Case.Sponsoring_Dept_GL_Code__c}"/>
<apex:commandButton value="Submit Change Request" action="{!Save}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
I have a Visualforce page that has been created, and what I want to do is when the Visualforce page is submitted to create a case by clicking on the save button on the Visualforce page, I want the user to be redirected to another visualforce page thanking the user for thier submission with the newly created case number.
I know I will have to create a Standard controller extention, but I am not familiar with this process at all, and any help would be very much appreciated.
Here is the Visualforce page code I have created, and for our example purposes the VF page for the redirect we will name Thank_You.
Please help however you can by telling me how to create a custom extentsion to add functionality to redirect to the Thank_You Visualforce page after the standard Save has been completed.
Thank you so much!
<apex:page standardController="Case">
<img src="{!$resource.AVISPL_Logo2}"></img>
<apex:pageBlock >
<apex:pageBlockSection title="Hello, Thank You For Your Project Request !" columns="1" showHeader="True" collapsible="False">
</apex:pageBlockSection>
</apex:pageBlock>
<apex:form >
<apex:pageBlock tabStyle="Case" title="Impact" >
<apex:pageBlockSection >
<apex:inputField value="{!Case.Number_of_Users_Affected__c}"/>
<apex:inputField value="{!Case.Area_s_Affected__c}"/>
<apex:inputField value="{!Case.Functionality_Affected__c}"/>
<apex:inputField value="{!Case.Profile_s_Affected__c}"/>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock title="Description Information" >
<apex:pageBlockSection >
<apex:inputField value="{!Case.Subject}"/>
<apex:inputField value="{!Case.Driver__c}"/>
<apex:inputField value="{!Case.Benefit_Of_Change__c}"/>
<apex:inputField value="{!Case.Reason_For_Change__c}"/>
<apex:inputField value="{!Case.Description}"/>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock title="Deadlines and Project Status" >
<apex:pageBlockSection >
<apex:inputField value="{!Case.Target_Deadline__c}"/>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock title="Requesting Department Information" >
<apex:pageBlockSection >
<apex:inputField value="{!Case.Sponsoring_Department_s__c}"/>
<apex:inputField value="{!Case.Sponsoring_Dept_GL_Code__c}"/>
<apex:commandButton value="Submit Change Request" action="{!Save}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
- Shawn Reichner
- June 09, 2014
- Like
- 0
Help with Test Class not passing (List Has No Rows For Assignment)
I am in need of some great support form one of you Awesome Salesforce Guru's!
I have a Apex Controller that I am using as an extension on a VF page to handle incoming attachments and populate a look up field when the record is created from the VF page.
I can not get the test class to not fail for the following reason System.QueryException: List has no rows for assignment to SObject and the stack trace is - Class.backlogAttachment.getReleaseMethod1: line 20, column 1
Class.backlogAttachment.<init>: line 12, column 1
Class.backlogAttachmentTest.backlogAttachmentTestMethod: line 10, column 1
Here is my controller class and Test class...can you please help me figure out why thsi is failing and what to do to fix it? You woudl be a hge saviour here as I am new to apex but am trying my hardest! Thanks in advance...
Shawn
Controller Extension:
Test Class that is failing:
I have a Apex Controller that I am using as an extension on a VF page to handle incoming attachments and populate a look up field when the record is created from the VF page.
I can not get the test class to not fail for the following reason System.QueryException: List has no rows for assignment to SObject and the stack trace is - Class.backlogAttachment.getReleaseMethod1: line 20, column 1
Class.backlogAttachment.<init>: line 12, column 1
Class.backlogAttachmentTest.backlogAttachmentTestMethod: line 10, column 1
Here is my controller class and Test class...can you please help me figure out why thsi is failing and what to do to fix it? You woudl be a hge saviour here as I am new to apex but am trying my hardest! Thanks in advance...
Shawn
Controller Extension:
public with sharing class backlogAttachment { public blob getfile{get;set;} public attachment objAttachment{get;set;} public Backlog__c objcase{get;set;} public string filename{get;set;} public backlogAttachment(apexpages.standardcontroller controller) { objcase = new Backlog__c(); objAttachment = new Attachment(); Scheduled_Releases__c sr = getReleaseMethod1(); objcase.Scheduled_Release__c = sr.Id; } Scheduled_Releases__c s; public Scheduled_Releases__c getReleaseMethod1(){ if(s == null) s=[SELECT Id, Name FROM Scheduled_Releases__c WHERE Name ='Software Enhancement Request (Default)' LIMIT 1]; return s; } Public PageReference saveBacklog() { try{ insert objcase; } catch(DMLException e) { ApexPages.addMessages(e); } if(filename != null && fileName.trim().length()>0 && getfile != null) { //objAttachment = new Attachment(); Integer i=0; objAttachment.clear(); objAttachment.body = getfile; objAttachment.ParentId = objcase.Id; objAttachment.name = this.filename; try{ insert objAttachment; }catch(Exception e){ system.debug(e); } } pagereference pr = new pagereference('/'+objcase.id); return pr; } }
Test Class that is failing:
@isTest public class backlogAttachmentTest { static testMethod void backlogAttachmentTestMethod() { List<Scheduled_Releases__c> re = [SELECT Id FROM Scheduled_Releases__c WHERE Id = 'a3l4B000000CiGw' LIMIT 1]; Backlog__c temprec = new Backlog__c(); ApexPages.StandardController cs = new ApexPages.StandardController(temprec); backlogAttachment controller = new backlogAttachment(cs); controller.getfile = Blob.valueof('Test Data'); controller.filename = 'TestFieName'; controller.objcase.Scheduled_Release__c = re[0].Id; test.startTest(); controller.saveBacklog(); test.StopTest(); } }
- Shawn Reichner
- March 24, 2017
- Like
- 0
Capturing attachment on Visualforce page
Hoping that one of you awesome Salesforce experts can help me with the following issue I am having.
I have an force.com Site which has a VisualForce page which should open a custom object record on Salesforce. I also have a need to have an attachment added to this VF page to then be attached to the new record being created upon the user pressing save.
Here is what I am seeign so far, if I do not include the Controller extension, the record gets created just fine, but when I have the extension added to the VF page, no record is created.
I am new to apex, so hoping that someone can look over my code below and provide a solution to my frustration :)
Thank you
Shawn
VF Page Code -
First Extention to pass ID of another custom object record and populate a lookup field when record is created.
And lastly, the second controller extension for handling the attachment.
PLEASE HELP!!!!
I have an force.com Site which has a VisualForce page which should open a custom object record on Salesforce. I also have a need to have an attachment added to this VF page to then be attached to the new record being created upon the user pressing save.
Here is what I am seeign so far, if I do not include the Controller extension, the record gets created just fine, but when I have the extension added to the VF page, no record is created.
I am new to apex, so hoping that someone can look over my code below and provide a solution to my frustration :)
Thank you
Shawn
VF Page Code -
<apex:page standardcontroller="Backlog__c" extensions="backlogAttachment,PopulateSchedRelease" showHeader="true"> <img src="{!$resource.AVISPL_Logo2}"></img><b/><b/> <apex:form > <apex:pageBlock > <apex:pageBlockSection title="Software Enhancement Request" columns="1" showHeader="True" collapsible="False"> </apex:pageBlockSection> </apex:pageBlock> <apex:pageMessages /> <apex:pageBlock > <apex:inputField value="{!objcase.Name}"/> <apex:pageBlockSection title="Request/Requestor Information"> <apex:inputfield value="{!objcase.SER_Requestor__c}" required="True"/> <apex:inputfield value="{!objcase.Priority__c}" required="True"/> <apex:inputField value="{!objcase.SER_Requestor_email__c}" required="True"/> <apex:inputfield value="{!objcase.Stakeholder__c}" required="True"/> <apex:inputField value="{!objcase.Requestor_GL_Code__c}"/> <apex:inputfield value="{!objcase.Executive_Sponsor__c}"/> </apex:pageBlockSection> <apex:pageBlockSection title="Impact of Request"> <apex:inputField value="{!objcase.SER_Category__c}" required="True"/> <apex:inputField value="{!objcase.SER_Sub_Category__c}"/> <apex:inputField value="{!objcase.SER_Designation__c}" required="True"/> <apex:inputField value="{!objcase.Number_of_Users_Affected__c}" required="True"/> <br/> </apex:pageBlockSection> <apex:pageBlockSection title="Request Description Information"> <apex:inputField value="{!objcase.Summary__c}" required="True"/> <apex:inputField value="{!objcase.Reason__c}" required="True"/> <apex:inputField value="{!objcase.Description__c}" required="True"/> <apex:inputField value="{!objcase.Benefit__c}" required="True"/> <br/> </apex:pageBlockSection> <apex:pageBlockSection title="Deadlines and Project Status"> <apex:inputField value="{!objcase.Training_Requirements__c}" required="True"/> <apex:inputField value="{!objcase.Target_Deadline__c}" required="True"/> <apex:inputField value="{!objcase.SOP_Requirements__c}" required="True"/> <apex:inputField value="{!objcase.List_All_U_A_T_Participants__c}" required="True"/> <apex:inputField value="{!objcase.SER_Scheduled_Release__c}"/> <apex:inputField value="{!objcase.Scheduled_Release__c}" rendered="False"/> <br/> </apex:pageBlockSection> <apex:pageBlock title="Upload Attachment"> <apex:inputFile style="width:100%" id="fileToUpload" value="{!objAttachment.Body}" filename="{!objAttachment.Name}" /> </apex:pageBlock> <apex:commandButton value="Submit Request" action="{!saveBacklog}" /> </apex:pageBlock> </apex:form> </apex:page>
First Extention to pass ID of another custom object record and populate a lookup field when record is created.
public class PopulateSchedRelease { public Backlog__c bl; public PopulateSchedRelease(ApexPages.StandardController controller) { this.bl = (Backlog__c)controller.getRecord(); Scheduled_Releases__c sr = getReleaseMethod1(); bl.Scheduled_Release__c = sr.Id; } Scheduled_Releases__c s; public Scheduled_Releases__c getReleaseMethod1() { if(s == null) s = [SELECT Id, Name FROM Scheduled_Releases__c WHERE Name = 'Software Enhancement Request (Default)' LIMIT 1]; return s; } }
And lastly, the second controller extension for handling the attachment.
public class backlogAttachment { public blob getfile{get;set;} public attachment objAttachment{get;set;} public Backlog__c objcase{get;set;} public string filename{get;set;} public backlogAttachment(apexpages.standardcontroller stdCon) { objcase = new Backlog__c(); objAttachment = new Attachment(); } Public PageReference saveBacklog() { insert objcase; objAttachment.body = getfile; objAttachment.ParentId = objcase.Id; objAttachment.name = filename; insert objAttachment; return ApexPages.currentPage(); } }
PLEASE HELP!!!!
- Shawn Reichner
- March 24, 2017
- Like
- 0
SOQL 101 Error Help Please
Thank you for any insight and for spending a few minutes to look over the following code. I am fairly new to apex and I am having issues getting this trigger to run in a batch scenario. I am constantly getting SOQL 101 Govenor Limit error and can not figure out how to properly "Bulkify" this code.
Hoping someone can help out with some advice....Thanks in advance!!!!
The error is showing as hittong the limit from line 27...
Trigger Code:
1. trigger InstallProdDuplicatePreventer on AVISPL_Client_Product__c (before insert, before update) {
2.
3. //They can have the same name provided they have different record types
4.
5. Map<String, AVISPL_Client_Product__c> IPMap = new Map<String, AVISPL_Client_Product__c>();
6. Set<String> ipNameAndRecordTypeIdConcatSet = new Set<String>();
7. for (AVISPL_Client_Product__c IP : System.Trigger.new) {
8. If(IP.Virtual_Product__c == false){
9. String ipNameAndRecordTypeId = IP.name + '' + IP.recordTypeId;
10.
11. // Make sure we don't treat a name that isn't changing during an update as a duplicate.
12. if ((IP.Name != null) &&
13. (System.Trigger.isInsert ||
14. IP.Name != System.Trigger.oldMap.get(IP.Id).Name)) {
15.
16. // Make sure another new Installed Product isn't also a duplicate
17. if (IPMap.containsKey(IP.Name) && ipNameAndRecordTypeIdConcatSet.contains(ipNameAndRecordTypeId)) {
18. IP.Name.addError('Another new Installed Product has the same Name for this Record Type.');
19. } else {
20. IPMap.put(IP.Name, IP);
21. ipNameAndRecordTypeIdConcatSet.add(ipNameAndRecordTypeId);
22. }
23. }
24. }
25.
26. // Using a single database query, find all the Installed Products in the database that have the same name as any of the Installed Products being inserted or updated.
27. for (AVISPL_Client_Product__c Ip2 : [SELECT Name, RecordTypeId FROM AVISPL_Client_Product__c WHERE Name IN :IPMap.KeySet()]) {
28. AVISPL_Client_Product__c newIP = IPMap.get(IP2.Name);
29. String ipNameAndRecordTypeId = Ip2.name + '' + Ip2.recordTypeId;
30.
31. if(ipNameAndRecordTypeIdConcatSet.contains(ipNameAndRecordTypeId)) {
32. newIP.Name.addError('A Installed Product with this name already exists for this Record Type.');
33. }
34. }
35. }
36.}
Hoping someone can help out with some advice....Thanks in advance!!!!
The error is showing as hittong the limit from line 27...
Trigger Code:
1. trigger InstallProdDuplicatePreventer on AVISPL_Client_Product__c (before insert, before update) {
2.
3. //They can have the same name provided they have different record types
4.
5. Map<String, AVISPL_Client_Product__c> IPMap = new Map<String, AVISPL_Client_Product__c>();
6. Set<String> ipNameAndRecordTypeIdConcatSet = new Set<String>();
7. for (AVISPL_Client_Product__c IP : System.Trigger.new) {
8. If(IP.Virtual_Product__c == false){
9. String ipNameAndRecordTypeId = IP.name + '' + IP.recordTypeId;
10.
11. // Make sure we don't treat a name that isn't changing during an update as a duplicate.
12. if ((IP.Name != null) &&
13. (System.Trigger.isInsert ||
14. IP.Name != System.Trigger.oldMap.get(IP.Id).Name)) {
15.
16. // Make sure another new Installed Product isn't also a duplicate
17. if (IPMap.containsKey(IP.Name) && ipNameAndRecordTypeIdConcatSet.contains(ipNameAndRecordTypeId)) {
18. IP.Name.addError('Another new Installed Product has the same Name for this Record Type.');
19. } else {
20. IPMap.put(IP.Name, IP);
21. ipNameAndRecordTypeIdConcatSet.add(ipNameAndRecordTypeId);
22. }
23. }
24. }
25.
26. // Using a single database query, find all the Installed Products in the database that have the same name as any of the Installed Products being inserted or updated.
27. for (AVISPL_Client_Product__c Ip2 : [SELECT Name, RecordTypeId FROM AVISPL_Client_Product__c WHERE Name IN :IPMap.KeySet()]) {
28. AVISPL_Client_Product__c newIP = IPMap.get(IP2.Name);
29. String ipNameAndRecordTypeId = Ip2.name + '' + Ip2.recordTypeId;
30.
31. if(ipNameAndRecordTypeIdConcatSet.contains(ipNameAndRecordTypeId)) {
32. newIP.Name.addError('A Installed Product with this name already exists for this Record Type.');
33. }
34. }
35. }
36.}
- Shawn Reichner
- March 17, 2017
- Like
- 0
Help With Regex Formula FIeld
Hello,
I am fairly nwe to the RegEx game and am struggling with the formula needed to extract some text between the first and second / in a string field. I want to extract the text between the first and second / in the string to then populate a new formula field.
Here is an example of the string itself that I need to extract info from.... Can anyone please help?
Auto Launch Failed / Open Space Linda / Nashua, NH / AVI Development
So in the example above I want to populate my new formula field with only "Open Space Linda"
Hope that makes sense and someone can help me out here.....Thanks in advance
Shawn
I am fairly nwe to the RegEx game and am struggling with the formula needed to extract some text between the first and second / in a string field. I want to extract the text between the first and second / in the string to then populate a new formula field.
Here is an example of the string itself that I need to extract info from.... Can anyone please help?
Auto Launch Failed / Open Space Linda / Nashua, NH / AVI Development
So in the example above I want to populate my new formula field with only "Open Space Linda"
Hope that makes sense and someone can help me out here.....Thanks in advance
Shawn
- Shawn Reichner
- March 15, 2017
- Like
- 0
Visualforce Page On Site Not Showing Validation Rule Message when Case is submitted
Hello, I have an exposed Site with a basic Visualforce page using the standard case controller with an Extension to handle an Attachment upload. All works great however I just added a new Validation rule to the Case Object where the BKR Job field needs to be in a certain format in order to allow the case to save. The format the field is looking for is like the following 000V-11-00000. Anything else not in that format should throw the Validation rule error message at the field. What is happenign on the Site exposed VF page is the case shows it has been submitted to the user but the case is not created in the system because of the V RUle error, however the error message doe snot show on the VF page when submitting. I am pasting my code below in hopes someone can help me figure this one out. As you can see I have try catch and attemptign to show the error message any way I know how but it doesnt seem to diplay the error no matter what I try. PLEASE HELP :)
Controller Extension:
public with sharing class caseattachment
{
public case objcase{get;set;}
public String subj {get;set;}
public String description {get;set;}
public Attachment myAttachment{get;set;}
public string fileName{get;set;}
public Blob fileBody{get;set;}
public caseattachment(Apexpages.standardcontroller controller)
{
objcase = new case();
myAttachment =new Attachment();
}
public pagereference save()
{
String currentPage = null;
Boolean isServiceReadinessPage = false;
if(ApexPages.currentPage() != null && !Test.isRunningTest()) {
currentPage = ApexPages.currentPage().getUrl();
isServiceReadinessPage = currentPage.contains('Service_Readiness_Updated');
}
if(objCase.Requested_Completion_Date__c != null) {
objCase.Contract_Start_Date__c = objCase.Requested_Completion_Date__c;
objCase.Requested_Completion_Date__c = null;
}
if(objCase.Requested_Completion_Date_2__c != null) {
objCase.Contract_End_Date__c = objCase.Requested_Completion_Date_2__c;
objCase.Requested_Completion_Date_2__c = null;
}
Boolean contractStartEndDateFieldsHaveValues = (objCase.Contract_Start_Date__c != null) && (objCase.Contract_End_Date__c != null);
Boolean requiredFieldsHaveValues = true;
//requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Sales_Type__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Customer_Name__c != null);
//requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Request_Type_2__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Manufacturer__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Number_Of_Ports__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Number_Of_Users__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Contract_Start_Date__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Contract_End_Date__c != null);
//requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Salesperson__c != null);
//requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Sales_Engineer__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Trial_Account__c != null);
if(requiredFieldsHaveValues || (objCase.VMR_or_Bridging__c != 'Bridging/VMR' && contractStartEndDateFieldsHaveValues) || (!isServiceReadinessPage && objCase.VMR_or_Bridging__c != 'Bridging/VMR')) {
//if(requiredFieldsHaveValues || objCase.VMR_or_Bridging__c != 'Bridging/VMR') {
try{
insert objcase;
} catch(DMLException e) {
ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, e.getdmlMessage(0));
ApexPages.addMessage(msg);
}
if (fileName != null && fileName.trim().length() > 0 && fileBody != null) {
myAttachment = new Attachment();
Integer i=0;
myAttachment .clear();
myAttachment.Body = fileBody;
myAttachment.Name = this.fileName;
myAttachment.ParentId = objcase.id;
insert myAttachment;
}
pagereference pr = new pagereference('/'+objcase.id);
return pr;
} else {
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Fill in all the required fields before saving.');
ApexPages.addMessage(myMsg);
return null;
}
}
}
VF Page code:
<apex:page standardcontroller="Case" extensions="caseattachment"
showHeader="false">
<img src="{!$resource.AVISPL_Logo2}"></img><b/><b/>
<apex:pageMessages id="errMsg" />
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection title="Professional Service / Onboarding Request" columns="1" showHeader="True" collapsible="False"> </apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock >
<apex:inputField value="{!Case.CaseNumber}"/>
<apex:pageBlockSection title="Requestor Information">
<apex:inputfield value="{!objcase.Requestor_s_First_Name__c}" required="True"/>
<apex:inputfield value="{!objcase.Requestor_s_Last_Name__c}" required="True"/>
<apex:inputfield value="{!objcase.Requestor_Email_Address__c}" required="True"/>
<apex:inputfield value="{!objcase.Requestor_s_Phone_Number__c}" required="True"/>
<apex:inputField value="{!objcase.Account_Name__c}" required="True"/>
<apex:inputField value="{!objcase.Sales_Type__c}" required="True"/>
<apex:inputField value="{!objcase.Customer_Name__c}" required="True"/>
<apex:inputField value="{!objcase.Customer_Type__c}" required="True"/>
<apex:inputField value="{!objcase.Customer_Points_of_Contact__c}" required="True"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Description Information">
<apex:inputField value="{!objcase.Project_Name__c}" required="True"/>
<apex:inputField value="{!objcase.Request_Type_2__c}" required="True"/>
<apex:inputField value="{!objcase.Service_Type__c}" required="True"/>
<apex:inputField value="{!objcase.Connection_Type__c}"/>
<apex:inputField value="{!objcase.Description}" required="True"/>
<apex:inputField value="{!objcase.Manufacturer__c}" required="True"/>
<apex:inputField value="{!objcase.BKR_Opp_or_Quote__c}" label="BKR Job#" required="True"/>
<apex:inputField value="{!objcase.Messaging_Technology__c}" required="True"/>
<apex:inputField value="{!objcase.Target_Deadline__c}" required="True"/>
<apex:inputField value="{!objcase.TSG_Project_Manager_Budgeted_Hours__c}" required="True"/>
<apex:inputField value="{!objcase.TSG_Engineer_Programmer_Budgeted_Hours__c }" label="Engineer Budgeted Hours" required="True"/> <apex:inputField value="{!objcase.Project_Budgeted_Cost__c }" required="True"/>
<br/> >
</apex:pageBlockSection>
<apex:pageBlockSection title="SOW PO & IPT (Attachment)">
<apex:inputFile id="fileToUpload" value="{!fileBody}" filename="{!fileName}" styleClass="input-file"/>
</apex:pageBlockSection> <apex:commandButton value="Submit Request" action="{!Save}" reRender="errMsg" />
<apex:outputLink value="http://avi-spl.force.com/profmanservicemainpage">Return To Main Page</apex:outputLink>
</apex:pageBlock>
</apex:form>
</apex:page>
Controller Extension:
public with sharing class caseattachment
{
public case objcase{get;set;}
public String subj {get;set;}
public String description {get;set;}
public Attachment myAttachment{get;set;}
public string fileName{get;set;}
public Blob fileBody{get;set;}
public caseattachment(Apexpages.standardcontroller controller)
{
objcase = new case();
myAttachment =new Attachment();
}
public pagereference save()
{
String currentPage = null;
Boolean isServiceReadinessPage = false;
if(ApexPages.currentPage() != null && !Test.isRunningTest()) {
currentPage = ApexPages.currentPage().getUrl();
isServiceReadinessPage = currentPage.contains('Service_Readiness_Updated');
}
if(objCase.Requested_Completion_Date__c != null) {
objCase.Contract_Start_Date__c = objCase.Requested_Completion_Date__c;
objCase.Requested_Completion_Date__c = null;
}
if(objCase.Requested_Completion_Date_2__c != null) {
objCase.Contract_End_Date__c = objCase.Requested_Completion_Date_2__c;
objCase.Requested_Completion_Date_2__c = null;
}
Boolean contractStartEndDateFieldsHaveValues = (objCase.Contract_Start_Date__c != null) && (objCase.Contract_End_Date__c != null);
Boolean requiredFieldsHaveValues = true;
//requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Sales_Type__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Customer_Name__c != null);
//requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Request_Type_2__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Manufacturer__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Number_Of_Ports__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Number_Of_Users__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Contract_Start_Date__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Contract_End_Date__c != null);
//requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Salesperson__c != null);
//requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Sales_Engineer__c != null);
requiredFieldsHaveValues = requiredFieldsHaveValues && (objCase.Trial_Account__c != null);
if(requiredFieldsHaveValues || (objCase.VMR_or_Bridging__c != 'Bridging/VMR' && contractStartEndDateFieldsHaveValues) || (!isServiceReadinessPage && objCase.VMR_or_Bridging__c != 'Bridging/VMR')) {
//if(requiredFieldsHaveValues || objCase.VMR_or_Bridging__c != 'Bridging/VMR') {
try{
insert objcase;
} catch(DMLException e) {
ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, e.getdmlMessage(0));
ApexPages.addMessage(msg);
}
if (fileName != null && fileName.trim().length() > 0 && fileBody != null) {
myAttachment = new Attachment();
Integer i=0;
myAttachment .clear();
myAttachment.Body = fileBody;
myAttachment.Name = this.fileName;
myAttachment.ParentId = objcase.id;
insert myAttachment;
}
pagereference pr = new pagereference('/'+objcase.id);
return pr;
} else {
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Fill in all the required fields before saving.');
ApexPages.addMessage(myMsg);
return null;
}
}
}
VF Page code:
<apex:page standardcontroller="Case" extensions="caseattachment"
showHeader="false">
<img src="{!$resource.AVISPL_Logo2}"></img><b/><b/>
<apex:pageMessages id="errMsg" />
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection title="Professional Service / Onboarding Request" columns="1" showHeader="True" collapsible="False"> </apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock >
<apex:inputField value="{!Case.CaseNumber}"/>
<apex:pageBlockSection title="Requestor Information">
<apex:inputfield value="{!objcase.Requestor_s_First_Name__c}" required="True"/>
<apex:inputfield value="{!objcase.Requestor_s_Last_Name__c}" required="True"/>
<apex:inputfield value="{!objcase.Requestor_Email_Address__c}" required="True"/>
<apex:inputfield value="{!objcase.Requestor_s_Phone_Number__c}" required="True"/>
<apex:inputField value="{!objcase.Account_Name__c}" required="True"/>
<apex:inputField value="{!objcase.Sales_Type__c}" required="True"/>
<apex:inputField value="{!objcase.Customer_Name__c}" required="True"/>
<apex:inputField value="{!objcase.Customer_Type__c}" required="True"/>
<apex:inputField value="{!objcase.Customer_Points_of_Contact__c}" required="True"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Description Information">
<apex:inputField value="{!objcase.Project_Name__c}" required="True"/>
<apex:inputField value="{!objcase.Request_Type_2__c}" required="True"/>
<apex:inputField value="{!objcase.Service_Type__c}" required="True"/>
<apex:inputField value="{!objcase.Connection_Type__c}"/>
<apex:inputField value="{!objcase.Description}" required="True"/>
<apex:inputField value="{!objcase.Manufacturer__c}" required="True"/>
<apex:inputField value="{!objcase.BKR_Opp_or_Quote__c}" label="BKR Job#" required="True"/>
<apex:inputField value="{!objcase.Messaging_Technology__c}" required="True"/>
<apex:inputField value="{!objcase.Target_Deadline__c}" required="True"/>
<apex:inputField value="{!objcase.TSG_Project_Manager_Budgeted_Hours__c}" required="True"/>
<apex:inputField value="{!objcase.TSG_Engineer_Programmer_Budgeted_Hours__c }" label="Engineer Budgeted Hours" required="True"/> <apex:inputField value="{!objcase.Project_Budgeted_Cost__c }" required="True"/>
<br/> >
</apex:pageBlockSection>
<apex:pageBlockSection title="SOW PO & IPT (Attachment)">
<apex:inputFile id="fileToUpload" value="{!fileBody}" filename="{!fileName}" styleClass="input-file"/>
</apex:pageBlockSection> <apex:commandButton value="Submit Request" action="{!Save}" reRender="errMsg" />
<apex:outputLink value="http://avi-spl.force.com/profmanservicemainpage">Return To Main Page</apex:outputLink>
</apex:pageBlock>
</apex:form>
</apex:page>
- Shawn Reichner
- March 13, 2017
- Like
- 0
Test Class help needed please
Hello, thnak you very much for the help in advance if you are able to help with the following test class. I am new to Apex and have created a trigger which I am posting below which is working fine. The test class I created is covering roughly 54 percent and I need it higher of course. I am posting the test class below as well with the lines marked that are not being covered. If you can help me get the code coverage up I would greatly appreciate it. Thank you again!
Trigger Code -
List<String> CaseZipList = new List<String>();
For(Case Cases : Trigger.new) {
IF(string.isBlank(Cases.New_Job_Number__c) && Cases.AVISPL_Service_Maintenance_Contract__c != null && !string.isBlank(Cases.New_Company_Database__c) && !string.isBlank(Cases.Address_Zip_Code__c)) {
String zipCode = cases.Address_Zip_Code__c;
//We need to sanitize the incoming zip code. Specifically, the Zip_Code__c object stores 5-digit zip codes only, so a longer zip code (e.g. 17801-7952) needs to be trimmed to match (e.g. 17801).
zipCode = zipCode.left(5);
trigger AVI_SPL_TM_Zip_To_Warehouse on Case (after insert, before update) {
CaseZipList.add(zipCode);
}
}
//If there is at least one Case which meets our criteria...
if(CaseZipList.size() > 0) {
//...then query the appropriate objects and perform the rest of the trigger's functionality.
ID ExternalZipCodeRT = Schema.sObjectType.Zip_Code__c.getRecordTypeInfosByName().get('External Zip Code').getRecordTypeId();
List<Zip_Code__c> zipList = [SELECT ID, Name, Location__Longitude__s,Location__Latitude__s, Warehouse_Code_Selection__c, Company_Database__c
FROM Zip_Code__c
WHERE Name = : CaseZipList
AND RecordTypeId = :ExternalZipCodeRT];
ID InternalZipCodeRT = Schema.sObjectType.Zip_Code__c.getRecordTypeInfosByName().get('Internal Sales Office').getRecordTypeId();
List<Zip_Code__c> SalesZipList = [SELECT ID, Name, Location__Longitude__s,Location__Latitude__s, Warehouse_Code_Selection__c, Company_Database__c
FROM Zip_Code__c
WHERE RecordTypeId = :InternalZipCodeRT];
List<Location> SalesOfficeLocations = new List<Location>();
Map<Location,String> locationToWarehouseCode = new Map<Location,String>();
Map<String,String> warehouseCodeToCompanyDatabase = new Map<String, String>();
For(Zip_Code__c SZ : SalesZipList) {
NOT COVERED Location Loc = Location.newInstance(SZ.Location__Latitude__s,SZ.Location__Longitude__s);
NOT COVERED SalesOfficeLocations.add(Loc);
NOT COVERED locationToWarehouseCode.put(Loc,SZ.Warehouse_Code_Selection__c);
NOT COVERED warehouseCodeToCompanyDatabase.put(SZ.Warehouse_Code_Selection__c, SZ.Company_Database__c);
}
//Loop through each inserted or updated Case.
for(Case Cases : Trigger.new) {
//For each Case that meets our criteria...
IF(string.isBlank(Cases.New_Job_Number__c) && Cases.AVISPL_Service_Maintenance_Contract__c != null && !string.isBlank(Cases.New_Company_Database__c) && !string.isBlank(Cases.Address_Zip_Code__c)) {
//...then loop through each of the External Zip Codes we queried.
For(Zip_Code__c CL : ZipList) {
NOT COVERED String zipCode = Cases.Address_Zip_Code__c;
//We need to sanitize the incoming zip code. Specifically, the Zip_Code__c object stores 5-digit zip codes only, so a longer zip code (e.g. 17801-7952) needs to be trimmed to match (e.g. 17801).
NOT COVERED zipCode = zipCode.left(5);
//When we find the matching External Zip Code...
NOT COVERED if(CL.name == zipCode) {
//...then grab its location so we can compare against the Sales Office Locations.
NOT COVERED Location Loc = Location.newInstance(CL.Location__Latitude__s,CL.Location__Longitude__s);
NOT COVERED Double minDistance = null;
NOT COVERED String closestWarehouseCode = null;
//Loop through all the Sales Office Locations.
NOT COVERED For(Location SOL : SalesOfficeLocations){
//If the Sales Office Location is for the same Company Database value as the Case we're currently examining...
NOT COVERED if(warehouseCodeToCompanyDatabase.get(locationToWarehouseCode.get(SOL)) == cases.New_Company_Database__c) {
//...then determine the distance between them.
NOT COVERED Double distance = Location.getDistance(Loc,SOL,'mi');
//If this is the closest distance we've calculated so far...
NOT COVERED If(minDistance == null || distance < minDistance){
//...then save that distance as our new closest and assign the Warehouse Code as the closest Warehouse.
NOT COVERED minDistance = distance;
NOT COVERED closestWarehouseCode = locationToWarehouseCode.get(SOL);
}//end of If(minDistance == null || distance < minDistance)
}//end of if(warehouseCodeToCompanyDatabase.get(locationToWarehouseCode.get(SOL)) == cases.New_Company_Database__c)
}//end of For(Location SOL : SalesOfficeLocations)
//Having done all of those comparisons, we can now assign the closest Warehouse Code to the Case.
NOT COVERED Cases.AVI_SPL_Rep_Whse_Office_Code_2011__c = closestWarehouseCode;
}//end of if(CL.name == zipCode)
}//end of For(Zip_Code__c CL : ZipList)
}//end of IF(string.isBlank(Cases.New_Job_Number__c) && Cases.AVISPL_Service_Maintenance_Contract__c != null && !string.isBlank(Cases.New_Company_Database__c) && !string.isBlank(Cases.Address_Zip_Code__c))
}//end of for(Case Cases : Trigger.new)
}//end of if(CaseZipList.size() > 0)
//call of existing trigger "SalesExtract" from Case Object. Need this code to fire after Zip actions.
salespersonextraction.salesextract(Trigger.new);
}
Test Class -
@isTest
public class AVI_SPL_TM_Zip_To_Warehouse_Test{
public static Case testCase;
public static AVISPL_Service_Maintenance_Contract__c testSmc;
public static Account testAcc;
@testSetup
private static void myTestData(){
Account a = new Account();
a.Name = 'Test Warehouse Account';
a.CurrencyIsoCode = 'USD';
a.RecordTypeId = '01240000000DhQMAA0';
a.Named_Account__c = 'No';
a.Exclusive_Account__c = 'No';
a.Enterprise_Account__c = 'No';
insert a;
AVI_SPL_TM_Zip_To_Warehouse_Test.testAcc = a;
System.debug('The new Account ID is ' + a.Id);
Contact con = new Contact();
con.FirstName = 'Test Shawn';
con.LastName = 'Contact';
con.Email = 'djsuite015@gmail.com';
con.CurrencyIsoCode = 'USD';
con.AccountId ='0014000000iLrfy';
con.RecordTypeId ='012330000001HMuAAM';
insert con;
System.debug('The new Contact ID is ' + con.Id);
AVISPL_Service_Level_Term__c sla = new AVISPL_Service_Level_Term__c();
sla.Name = 'Test';
sla.Active__c = True;
insert sla;
system.debug('The new SLA Term ID is ' + sla.Id);
AVISPL_Service_Maintenance_Contract__c s = new AVISPL_Service_Maintenance_Contract__c();
s.Name = 'Warehouse Test SMC';
s.Active_Contract__c = True;
s.CurrencyIsoCode = 'USD';
s.Salesperson__c = con.Id;
s.BKR_Customer__c = '12345';
s.Company_Database__c = 'AVI';
s.Contract_Start_Date__c = Date.newInstance(2016, 11, 1);
s.Contract_End_Date__c = Date.newInstance(2017, 11, 1);
s.SLA_Terms__c = sla.Id;
s.Sale_Type__c = 'Service Only - Net New';
// s.Preventative_Maintenance_Visits__c = 'One';
s.RecordTypeId = '012330000001HMpAAM';
insert s;
AVI_SPL_TM_Zip_To_Warehouse_Test.testSmc = s;
system.debug('The new SMC Id is ' + s.Id);
Case c = new Case();
c.RecordTypeId = '01240000000INaqAAG';
c.Status = 'New / Open';
c.Priority = 'P4';
c.Department__c = 'Help Desk';
c.CurrencyIsoCode = 'USD';
c.AccountId = a.Id;
c.AVISPL_Service_Maintenance_Contract__c = s.Id;
c.Sub_Account_Room_Information__c = 'TBD';
c.Type = 'Contract';
c.Origin = 'Phone';
c.Subject = 'Test';
c.Description = 'Test';
c.Svc_Category_Client_Reported_Issue__c = 'A/V';
c.New_Job_Number__c = '';
c.Address_Zip_Code__c = '17801-7952';
c.New_Company_Database__c = s.Company_Database__c;
insert c;
AVI_SPL_TM_Zip_To_Warehouse_Test.testCase = c;
system.debug('The testCase ID is ' + testCase.Id);
system.debug('The new Case Id is ' + c.Id);
}
private static testMethod void tm1(){
AVI_SPL_TM_Zip_To_Warehouse_Test.myTestData();
AVI_SPL_TM_Zip_To_Warehouse_Test.testCase = [SELECT Id, New_Company_Database__c, Address_Zip_Code__c, New_Job_Number__c,
AVI_SPL_Rep_Whse_Office_Code_2011__c FROM Case
WHERE Id = : AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.Id];
If(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.AVI_SPL_Rep_Whse_Office_Code_2011__c != null){
system.assert(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.AVI_SPL_Rep_Whse_Office_Code_2011__c == 'PA_Philadelphia_240S_240600_SPL');
system.assert(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.Address_Zip_Code__c == '17801');
system.assert(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.New_Company_Database__c == 'SPL');
system.assert(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.Address_Zip_Code__c != '17801-7952');
}
}
}
Trigger Code -
List<String> CaseZipList = new List<String>();
For(Case Cases : Trigger.new) {
IF(string.isBlank(Cases.New_Job_Number__c) && Cases.AVISPL_Service_Maintenance_Contract__c != null && !string.isBlank(Cases.New_Company_Database__c) && !string.isBlank(Cases.Address_Zip_Code__c)) {
String zipCode = cases.Address_Zip_Code__c;
//We need to sanitize the incoming zip code. Specifically, the Zip_Code__c object stores 5-digit zip codes only, so a longer zip code (e.g. 17801-7952) needs to be trimmed to match (e.g. 17801).
zipCode = zipCode.left(5);
trigger AVI_SPL_TM_Zip_To_Warehouse on Case (after insert, before update) {
CaseZipList.add(zipCode);
}
}
//If there is at least one Case which meets our criteria...
if(CaseZipList.size() > 0) {
//...then query the appropriate objects and perform the rest of the trigger's functionality.
ID ExternalZipCodeRT = Schema.sObjectType.Zip_Code__c.getRecordTypeInfosByName().get('External Zip Code').getRecordTypeId();
List<Zip_Code__c> zipList = [SELECT ID, Name, Location__Longitude__s,Location__Latitude__s, Warehouse_Code_Selection__c, Company_Database__c
FROM Zip_Code__c
WHERE Name = : CaseZipList
AND RecordTypeId = :ExternalZipCodeRT];
ID InternalZipCodeRT = Schema.sObjectType.Zip_Code__c.getRecordTypeInfosByName().get('Internal Sales Office').getRecordTypeId();
List<Zip_Code__c> SalesZipList = [SELECT ID, Name, Location__Longitude__s,Location__Latitude__s, Warehouse_Code_Selection__c, Company_Database__c
FROM Zip_Code__c
WHERE RecordTypeId = :InternalZipCodeRT];
List<Location> SalesOfficeLocations = new List<Location>();
Map<Location,String> locationToWarehouseCode = new Map<Location,String>();
Map<String,String> warehouseCodeToCompanyDatabase = new Map<String, String>();
For(Zip_Code__c SZ : SalesZipList) {
NOT COVERED Location Loc = Location.newInstance(SZ.Location__Latitude__s,SZ.Location__Longitude__s);
NOT COVERED SalesOfficeLocations.add(Loc);
NOT COVERED locationToWarehouseCode.put(Loc,SZ.Warehouse_Code_Selection__c);
NOT COVERED warehouseCodeToCompanyDatabase.put(SZ.Warehouse_Code_Selection__c, SZ.Company_Database__c);
}
//Loop through each inserted or updated Case.
for(Case Cases : Trigger.new) {
//For each Case that meets our criteria...
IF(string.isBlank(Cases.New_Job_Number__c) && Cases.AVISPL_Service_Maintenance_Contract__c != null && !string.isBlank(Cases.New_Company_Database__c) && !string.isBlank(Cases.Address_Zip_Code__c)) {
//...then loop through each of the External Zip Codes we queried.
For(Zip_Code__c CL : ZipList) {
NOT COVERED String zipCode = Cases.Address_Zip_Code__c;
//We need to sanitize the incoming zip code. Specifically, the Zip_Code__c object stores 5-digit zip codes only, so a longer zip code (e.g. 17801-7952) needs to be trimmed to match (e.g. 17801).
NOT COVERED zipCode = zipCode.left(5);
//When we find the matching External Zip Code...
NOT COVERED if(CL.name == zipCode) {
//...then grab its location so we can compare against the Sales Office Locations.
NOT COVERED Location Loc = Location.newInstance(CL.Location__Latitude__s,CL.Location__Longitude__s);
NOT COVERED Double minDistance = null;
NOT COVERED String closestWarehouseCode = null;
//Loop through all the Sales Office Locations.
NOT COVERED For(Location SOL : SalesOfficeLocations){
//If the Sales Office Location is for the same Company Database value as the Case we're currently examining...
NOT COVERED if(warehouseCodeToCompanyDatabase.get(locationToWarehouseCode.get(SOL)) == cases.New_Company_Database__c) {
//...then determine the distance between them.
NOT COVERED Double distance = Location.getDistance(Loc,SOL,'mi');
//If this is the closest distance we've calculated so far...
NOT COVERED If(minDistance == null || distance < minDistance){
//...then save that distance as our new closest and assign the Warehouse Code as the closest Warehouse.
NOT COVERED minDistance = distance;
NOT COVERED closestWarehouseCode = locationToWarehouseCode.get(SOL);
}//end of If(minDistance == null || distance < minDistance)
}//end of if(warehouseCodeToCompanyDatabase.get(locationToWarehouseCode.get(SOL)) == cases.New_Company_Database__c)
}//end of For(Location SOL : SalesOfficeLocations)
//Having done all of those comparisons, we can now assign the closest Warehouse Code to the Case.
NOT COVERED Cases.AVI_SPL_Rep_Whse_Office_Code_2011__c = closestWarehouseCode;
}//end of if(CL.name == zipCode)
}//end of For(Zip_Code__c CL : ZipList)
}//end of IF(string.isBlank(Cases.New_Job_Number__c) && Cases.AVISPL_Service_Maintenance_Contract__c != null && !string.isBlank(Cases.New_Company_Database__c) && !string.isBlank(Cases.Address_Zip_Code__c))
}//end of for(Case Cases : Trigger.new)
}//end of if(CaseZipList.size() > 0)
//call of existing trigger "SalesExtract" from Case Object. Need this code to fire after Zip actions.
salespersonextraction.salesextract(Trigger.new);
}
Test Class -
@isTest
public class AVI_SPL_TM_Zip_To_Warehouse_Test{
public static Case testCase;
public static AVISPL_Service_Maintenance_Contract__c testSmc;
public static Account testAcc;
@testSetup
private static void myTestData(){
Account a = new Account();
a.Name = 'Test Warehouse Account';
a.CurrencyIsoCode = 'USD';
a.RecordTypeId = '01240000000DhQMAA0';
a.Named_Account__c = 'No';
a.Exclusive_Account__c = 'No';
a.Enterprise_Account__c = 'No';
insert a;
AVI_SPL_TM_Zip_To_Warehouse_Test.testAcc = a;
System.debug('The new Account ID is ' + a.Id);
Contact con = new Contact();
con.FirstName = 'Test Shawn';
con.LastName = 'Contact';
con.Email = 'djsuite015@gmail.com';
con.CurrencyIsoCode = 'USD';
con.AccountId ='0014000000iLrfy';
con.RecordTypeId ='012330000001HMuAAM';
insert con;
System.debug('The new Contact ID is ' + con.Id);
AVISPL_Service_Level_Term__c sla = new AVISPL_Service_Level_Term__c();
sla.Name = 'Test';
sla.Active__c = True;
insert sla;
system.debug('The new SLA Term ID is ' + sla.Id);
AVISPL_Service_Maintenance_Contract__c s = new AVISPL_Service_Maintenance_Contract__c();
s.Name = 'Warehouse Test SMC';
s.Active_Contract__c = True;
s.CurrencyIsoCode = 'USD';
s.Salesperson__c = con.Id;
s.BKR_Customer__c = '12345';
s.Company_Database__c = 'AVI';
s.Contract_Start_Date__c = Date.newInstance(2016, 11, 1);
s.Contract_End_Date__c = Date.newInstance(2017, 11, 1);
s.SLA_Terms__c = sla.Id;
s.Sale_Type__c = 'Service Only - Net New';
// s.Preventative_Maintenance_Visits__c = 'One';
s.RecordTypeId = '012330000001HMpAAM';
insert s;
AVI_SPL_TM_Zip_To_Warehouse_Test.testSmc = s;
system.debug('The new SMC Id is ' + s.Id);
Case c = new Case();
c.RecordTypeId = '01240000000INaqAAG';
c.Status = 'New / Open';
c.Priority = 'P4';
c.Department__c = 'Help Desk';
c.CurrencyIsoCode = 'USD';
c.AccountId = a.Id;
c.AVISPL_Service_Maintenance_Contract__c = s.Id;
c.Sub_Account_Room_Information__c = 'TBD';
c.Type = 'Contract';
c.Origin = 'Phone';
c.Subject = 'Test';
c.Description = 'Test';
c.Svc_Category_Client_Reported_Issue__c = 'A/V';
c.New_Job_Number__c = '';
c.Address_Zip_Code__c = '17801-7952';
c.New_Company_Database__c = s.Company_Database__c;
insert c;
AVI_SPL_TM_Zip_To_Warehouse_Test.testCase = c;
system.debug('The testCase ID is ' + testCase.Id);
system.debug('The new Case Id is ' + c.Id);
}
private static testMethod void tm1(){
AVI_SPL_TM_Zip_To_Warehouse_Test.myTestData();
AVI_SPL_TM_Zip_To_Warehouse_Test.testCase = [SELECT Id, New_Company_Database__c, Address_Zip_Code__c, New_Job_Number__c,
AVI_SPL_Rep_Whse_Office_Code_2011__c FROM Case
WHERE Id = : AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.Id];
If(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.AVI_SPL_Rep_Whse_Office_Code_2011__c != null){
system.assert(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.AVI_SPL_Rep_Whse_Office_Code_2011__c == 'PA_Philadelphia_240S_240600_SPL');
system.assert(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.Address_Zip_Code__c == '17801');
system.assert(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.New_Company_Database__c == 'SPL');
system.assert(AVI_SPL_TM_Zip_To_Warehouse_Test.testCase.Address_Zip_Code__c != '17801-7952');
}
}
}
- Shawn Reichner
- January 26, 2017
- Like
- 0
Visualforce Page only displays White screen in Salesforce1
Hello,
Hoping that someone can help us here! I have a VF page that is to diplay the standard Salesforce calendar in Salesforce1.
I have created the VF page(Marked it as mobile), a VF tab, and placed it in the navigation menu of Salesforce1. I also must point out that this works just fine in our dev sandbox, and this issue of just displaying a white screen is only occuirng in our production instance.
Here is the code for the VF page......does anyone have any suggestions? I am very anxious to hear any as I scoured the web and could not find any leads, so I want to turn it over to the wonderful brilliant friends here.....
<apex:page showHeader="false" sidebar="false" >
<script type="text/javascript">
window.location = "https://ap1.salesforce.com/00U/c?isdtp=mn" </script> </apex:page>
Thank you in advance for any help or suggestions you may be able to provide,
Shawn
Hoping that someone can help us here! I have a VF page that is to diplay the standard Salesforce calendar in Salesforce1.
I have created the VF page(Marked it as mobile), a VF tab, and placed it in the navigation menu of Salesforce1. I also must point out that this works just fine in our dev sandbox, and this issue of just displaying a white screen is only occuirng in our production instance.
Here is the code for the VF page......does anyone have any suggestions? I am very anxious to hear any as I scoured the web and could not find any leads, so I want to turn it over to the wonderful brilliant friends here.....
<apex:page showHeader="false" sidebar="false" >
<script type="text/javascript">
window.location = "https://ap1.salesforce.com/00U/c?isdtp=mn" </script> </apex:page>
Thank you in advance for any help or suggestions you may be able to provide,
Shawn
- Shawn Reichner
- April 22, 2016
- Like
- 0
Unexpected Token error when attempting to test a Test Class - Please Help!
Hello Experts!
I am trying to create a test apex class, which saves just fine, however when I attempt to actually run the test for the test class, i get the following error: Error Message System.QueryException: unexpected token: WHERE
Stack Trace Class.MyClosedIssuesTest.testMyClosedIssues: line 23, column 1
Here is my code, can anyone tell me what I may have done incorrectly, as google searching has yielded no results.
@IsTest(SeeAllData=true)
public class MyClosedIssuesTest {
static testMethod void testMyClosedIssues() {
SObjectType objToken = Schema.getGlobalDescribe().get('Backlog__c');
DescribeSObjectResult objDef = objToken.getDescribe();
Map<String, SObjectField> fields = objDef.fields.getMap();
Set<String> fieldSet = fields.keySet();
String query = 'SELECT ';
Integer counter = 0;
for(String s : fieldSet) {
counter++;
SObjectField fieldToken = fields.get(s);
DescribeFieldResult selectedField = fieldToken.getDescribe();
query = query + selectedField.getName();
if(counter < fieldSet.size()) {
query = query + ', ';
}
}
String query1 = query + 'FROM Backlog__c WHERE createdbyid = \'' + userinfo.getuserid() + '\'order by createddate desc';
Backlog__c testIssue = Database.query(query1);
testIssue.Parent__c = 'a3W180000008ddj';
testIssue.Scheduled_Release__c = 'a3l18000000085c';
testIssue.Environment__c = 'Production';
testIssue.Summary__c = 'Add New Items To Account and Contact';
testIssue.Description__c = 'Test';
update testIssue;
Backlog__c result = [Select ID,Description__c FROM Backlog__c WHERE Id = :testIssue.Id];
}
}
Thank you in advance for any help you may be able to provide
Shawn
I am trying to create a test apex class, which saves just fine, however when I attempt to actually run the test for the test class, i get the following error: Error Message System.QueryException: unexpected token: WHERE
Stack Trace Class.MyClosedIssuesTest.testMyClosedIssues: line 23, column 1
Here is my code, can anyone tell me what I may have done incorrectly, as google searching has yielded no results.
@IsTest(SeeAllData=true)
public class MyClosedIssuesTest {
static testMethod void testMyClosedIssues() {
SObjectType objToken = Schema.getGlobalDescribe().get('Backlog__c');
DescribeSObjectResult objDef = objToken.getDescribe();
Map<String, SObjectField> fields = objDef.fields.getMap();
Set<String> fieldSet = fields.keySet();
String query = 'SELECT ';
Integer counter = 0;
for(String s : fieldSet) {
counter++;
SObjectField fieldToken = fields.get(s);
DescribeFieldResult selectedField = fieldToken.getDescribe();
query = query + selectedField.getName();
if(counter < fieldSet.size()) {
query = query + ', ';
}
}
String query1 = query + 'FROM Backlog__c WHERE createdbyid = \'' + userinfo.getuserid() + '\'order by createddate desc';
Backlog__c testIssue = Database.query(query1);
testIssue.Parent__c = 'a3W180000008ddj';
testIssue.Scheduled_Release__c = 'a3l18000000085c';
testIssue.Environment__c = 'Production';
testIssue.Summary__c = 'Add New Items To Account and Contact';
testIssue.Description__c = 'Test';
update testIssue;
Backlog__c result = [Select ID,Description__c FROM Backlog__c WHERE Id = :testIssue.Id];
}
}
Thank you in advance for any help you may be able to provide
Shawn
- Shawn Reichner
- December 30, 2016
- Like
- 0