-
ChatterFeed
-
0Best Answers
-
1Likes Received
-
0Likes Given
-
24Questions
-
9Replies
JQuery Data Table not working
We are trying to develop a Visual Force page to show some product data and configure it in a Jquery data table that will allow us to sort, paginate, and search throught the records. We currently have a VF page that does exactly that and works fine however when we try to use the save Jquery and HTML in this new page it does not allow us to sort, paginate or search. Can any one point us in the right direction? Our page and class are below.
PAGE:
<apex:page controller="SalesHardWareProductDetails" readOnly="true" showHeader="False" title="Sales Hardware Product Details" >
<head>
<apex:includeScript value="https:////code.jquery.com/jquery-1.12.3.js"/>
<apex:includeScript value="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"/>
<apex:stylesheet value="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"/>
<apex:includeScript value="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.min.js"/>
<apex:includeScript value="https://cdn.datatables.net/buttons/1.2.2/js/buttons.flash.min.js"/>
<apex:includeScript value="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"/>
<apex:includeScript value="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/pdfmake.min.js"/>
<apex:includeScript value="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/vfs_fonts.js"/>
<apex:includeScript value="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.min.js"/>
<apex:includeScript value="https://cdn.datatables.net/buttons/1.2.2/js/buttons.print.min.js"/>
<apex:stylesheet value="https://cdn.datatables.net/buttons/1.2.2/css/buttons.dataTables.min.css"/>
<script>
$(document).ready(function() {
$('#tracking').DataTable( {
dom: 'Bfrtip',
buttons: [
'excel', 'csv',
{
extend: 'pdf',
text: 'PDF',
orientation: 'landscape',
title: 'Four Winds Interactive Tracking Information',
}
]
} );
} );
</script>
</head>
<table id="tracking" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Product Type</th>
<th>Brand</th>
<th>Manufacturer Part Number</th>
<th>FWI Sell Price</th>
<th>Native Resolutions</th>
<th>Diagonal (in)</th>
<th>Width (in)</th>
<th>Height (in)</th>
<th>Depth (in)</th>
<th>Bezel (mm)</th>
<th>Brightness (nits)</th>
<th>VESA Pattern</th>
<th>Power Consumption</th>
<th>Screen Orientation</th>
<th>Product Warranty</th>
<th>Product Datasheet</th>
</tr>
</thead>
<apex:repeat value="{!itemDetails}" var="i">
<tr>
<td>{!i.productType}</td>
<td>{!i.brand}</td>
<td>{!i.itemNumber} </td>
<td>{!i.manufacturerPartNumber}</td>
<td>{!i.fwiSellPrice }</td>
<td>{!i.nativeResolutions}</td>
<td>{!i.diagonal}</td>
<td>{!i.width}</td>
<td>{!i.height} </td>
<td>{!i.depth}</td>
<td>{!i.bezel}</td>
<td>{!i.brightness}</td>
<td>{!i.vesa} </td>
<td>{!i.powerConsumption}</td>
<td>{!i.screenOrientation}</td>
<td>{!i.productWarranty}</td>
<td>{!i.productDatasheet}</td>
</tr>
</apex:repeat>
</table>
</apex:page>
CLASS
public class SalesHardWareProductDetails {
public List<SCMC__Item__c> items {get; set;}
public List<itemDetails> itemDetails {get; set;}
public SalesHardWareProductDetails() {
itemDetails = new List<itemDetails>();
getitems();
getitemDetails();
}
public class itemDetails
{
public string productType {get; set;}
public string brand {get; set;}
public string itemNumber {get; set;}
public string manufacturerPartNumber {get; set;}
public decimal fwiSellPrice {get;set;}
public string nativeResolutions {get;set;}
public string diagonal {get;set;}
public string width {get;set;}
public string height {get;set;}
public string depth {get;set;}
public string bezel {get; set;}
public string brightness {get;set;}
public string vesa{get;set;}
public string powerConsumption {get;set;}
public string screenOrientation {get;set;}
public string productWarranty{get;set;}
public string productDatasheet {get;set;}
public itemDetails(){}
}
public list <SCMC__Item__c> getitems(){
items = [select Product_Type__c, Id, Brand__c, Name, Manufacturer_Part_Number__c, FWi_Sell_Price_Price_Name__c, Native_Resolutions__c, Product_Diagonal_Screen_Size__c, Width_in__c, Height_in__c,
Depth_in__c, Bezel_mm__c, Brightness_nits__c, VESA_Pattern__c, Power_Consumption__c, Screen_Orientation__c, Product_Warranty__c, Product_Datasheet__c, Subcategory__c
From SCMC__Item__c
WHERE Brand__C != Null AND Subcategory__c != 'Product End Of Life (Only use for PCR)' Order by Product_Type__c asc];
system.debug(' item size '+items.size());
return items;
}
public list<itemDetails> getitemDetails(){
itemDetails = new list<itemDetails>();
for(SCMC__Item__c i :items){
itemDetails add = new itemDetails();
add.productType = i.Product_Type__c;
add.brand = i.Brand__c;
add.itemNumber = i.Name;
add.manufacturerPartNumber = i.Manufacturer_Part_Number__c;
add.fwiSellPrice = i.FWi_Sell_Price_Price_Name__c;
add.nativeResolutions = i.Native_Resolutions__c;
add.diagonal = i.Product_Diagonal_Screen_Size__c;
add.width = i.Width_in__c;
add.height = i.Height_in__c;
add.depth = i.Depth_in__c;
add.bezel = i.Bezel_mm__c;
add.brightness = i.Brightness_nits__c;
add.vesa = i.VESA_Pattern__c;
add.powerConsumption = i.Power_Consumption__c;
add.screenOrientation = i.Screen_Orientation__c;
add.productWarranty = i.Product_Warranty__c;
add.productDatasheet = i.Product_Datasheet__c;
itemDetails.add(add);
}
return itemDetails;
}
}
PAGE:
<apex:page controller="SalesHardWareProductDetails" readOnly="true" showHeader="False" title="Sales Hardware Product Details" >
<head>
<apex:includeScript value="https:////code.jquery.com/jquery-1.12.3.js"/>
<apex:includeScript value="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"/>
<apex:stylesheet value="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"/>
<apex:includeScript value="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.min.js"/>
<apex:includeScript value="https://cdn.datatables.net/buttons/1.2.2/js/buttons.flash.min.js"/>
<apex:includeScript value="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"/>
<apex:includeScript value="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/pdfmake.min.js"/>
<apex:includeScript value="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/vfs_fonts.js"/>
<apex:includeScript value="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.min.js"/>
<apex:includeScript value="https://cdn.datatables.net/buttons/1.2.2/js/buttons.print.min.js"/>
<apex:stylesheet value="https://cdn.datatables.net/buttons/1.2.2/css/buttons.dataTables.min.css"/>
<script>
$(document).ready(function() {
$('#tracking').DataTable( {
dom: 'Bfrtip',
buttons: [
'excel', 'csv',
{
extend: 'pdf',
text: 'PDF',
orientation: 'landscape',
title: 'Four Winds Interactive Tracking Information',
}
]
} );
} );
</script>
</head>
<table id="tracking" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Product Type</th>
<th>Brand</th>
<th>Manufacturer Part Number</th>
<th>FWI Sell Price</th>
<th>Native Resolutions</th>
<th>Diagonal (in)</th>
<th>Width (in)</th>
<th>Height (in)</th>
<th>Depth (in)</th>
<th>Bezel (mm)</th>
<th>Brightness (nits)</th>
<th>VESA Pattern</th>
<th>Power Consumption</th>
<th>Screen Orientation</th>
<th>Product Warranty</th>
<th>Product Datasheet</th>
</tr>
</thead>
<apex:repeat value="{!itemDetails}" var="i">
<tr>
<td>{!i.productType}</td>
<td>{!i.brand}</td>
<td>{!i.itemNumber} </td>
<td>{!i.manufacturerPartNumber}</td>
<td>{!i.fwiSellPrice }</td>
<td>{!i.nativeResolutions}</td>
<td>{!i.diagonal}</td>
<td>{!i.width}</td>
<td>{!i.height} </td>
<td>{!i.depth}</td>
<td>{!i.bezel}</td>
<td>{!i.brightness}</td>
<td>{!i.vesa} </td>
<td>{!i.powerConsumption}</td>
<td>{!i.screenOrientation}</td>
<td>{!i.productWarranty}</td>
<td>{!i.productDatasheet}</td>
</tr>
</apex:repeat>
</table>
</apex:page>
CLASS
public class SalesHardWareProductDetails {
public List<SCMC__Item__c> items {get; set;}
public List<itemDetails> itemDetails {get; set;}
public SalesHardWareProductDetails() {
itemDetails = new List<itemDetails>();
getitems();
getitemDetails();
}
public class itemDetails
{
public string productType {get; set;}
public string brand {get; set;}
public string itemNumber {get; set;}
public string manufacturerPartNumber {get; set;}
public decimal fwiSellPrice {get;set;}
public string nativeResolutions {get;set;}
public string diagonal {get;set;}
public string width {get;set;}
public string height {get;set;}
public string depth {get;set;}
public string bezel {get; set;}
public string brightness {get;set;}
public string vesa{get;set;}
public string powerConsumption {get;set;}
public string screenOrientation {get;set;}
public string productWarranty{get;set;}
public string productDatasheet {get;set;}
public itemDetails(){}
}
public list <SCMC__Item__c> getitems(){
items = [select Product_Type__c, Id, Brand__c, Name, Manufacturer_Part_Number__c, FWi_Sell_Price_Price_Name__c, Native_Resolutions__c, Product_Diagonal_Screen_Size__c, Width_in__c, Height_in__c,
Depth_in__c, Bezel_mm__c, Brightness_nits__c, VESA_Pattern__c, Power_Consumption__c, Screen_Orientation__c, Product_Warranty__c, Product_Datasheet__c, Subcategory__c
From SCMC__Item__c
WHERE Brand__C != Null AND Subcategory__c != 'Product End Of Life (Only use for PCR)' Order by Product_Type__c asc];
system.debug(' item size '+items.size());
return items;
}
public list<itemDetails> getitemDetails(){
itemDetails = new list<itemDetails>();
for(SCMC__Item__c i :items){
itemDetails add = new itemDetails();
add.productType = i.Product_Type__c;
add.brand = i.Brand__c;
add.itemNumber = i.Name;
add.manufacturerPartNumber = i.Manufacturer_Part_Number__c;
add.fwiSellPrice = i.FWi_Sell_Price_Price_Name__c;
add.nativeResolutions = i.Native_Resolutions__c;
add.diagonal = i.Product_Diagonal_Screen_Size__c;
add.width = i.Width_in__c;
add.height = i.Height_in__c;
add.depth = i.Depth_in__c;
add.bezel = i.Bezel_mm__c;
add.brightness = i.Brightness_nits__c;
add.vesa = i.VESA_Pattern__c;
add.powerConsumption = i.Power_Consumption__c;
add.screenOrientation = i.Screen_Orientation__c;
add.productWarranty = i.Product_Warranty__c;
add.productDatasheet = i.Product_Datasheet__c;
itemDetails.add(add);
}
return itemDetails;
}
}
- Andrew Aldis
- August 08, 2017
- Like
- 0
Test Class System.QueryException List has no rows for assignment to SObject
I am trying to write a test class for for the class below, which I had deployed to our production before, I made some little modifications ot the class to query a list of related items and put them into a select option list for a Picklist field on a VF page. I thought it was a small change but it seems to have completely messed up my test class and I am not sure why. I get the error: System.QueryException: List has no rows for assignment to SObject. I'd appreciate any assistance.
APEX CLASS
public class RiskEditPage {
Risk__c risk;
PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
public List<Work_Order__c> woTemp = new List<Work_Order__c>();
public List<SelectOption> woList {get;set;}
public RiskEditPage(apexPages.StandardController controller){
risk = [Select Name, Assign_To__c, OpId__c, Risk_Mitigation__r.OpId__c, FWI_Work_Order__c, Consequence_of_Failure__c, Covered_in_SOW_Hrs__c,
Custom_Development_Required__c, Description__c, Function__c, Risk_Mitigation__c, Risk_of_Failure__c,
Risk_Mitigation__r.Name, Signoff__c, Signoff2__c, Status__c, Strategy_to_Mitigate_Risk__c, Triggering_Action__c, Type__c,
User_Impact__c, Create_Task__c, Risk_of_Failure_Score__c from Risk__c
where Id = :ApexPages.currentPage().getparameters().get('id')];
woTemp = [Select s.Name, s.Id, s.Status__c, s.Type__c From Work_Order__c s where Opportunity__c = :risk.Risk_Mitigation__r.OpId__c Order By Name Asc];
woList = new List<SelectOption>();
for(Work_Order__c temp : woTemp)
{
woList.add(new SelectOption(temp.Id, temp.Name+': '+temp.Type__c));
}
}
public PageReference saveRisk()
{
update risk;
PageReference pageref = new PageReference('/'+risk.Risk_Mitigation__c);
pageRef.setRedirect(true);
return pageRef;
}
public PageReference saveNew()
{
upsert risk;
PageReference pageref = new PageReference('/apex/RiskNewPage?retURL='+risk.Risk_Mitigation__c+'&CF00N4D000000bXd5='+risk.Risk_Mitigation__r.Name+'kid=aDS4D0000004CAB&CF00N4D000000bXd5_lkid='+risk.Risk_Mitigation__c+'&retURL='+risk.Risk_Mitigation__c+'&scontrolCaching=1&sfdc.override=1');
pageRef.setRedirect(true);
return pageRef;
}
}
TEST CLASS
@istest(seealldata=true)
public class RiskEditPageTest {
static Risk_Mitigation__c setupServicePartner() {
Risk_Mitigation__c partner = new Risk_Mitigation__c();
partner.Name = 'test';
partner.Client_Workbook__c = 'a9f34000000TN1F';
insert partner;
return partner;
}
static Risk__c setupServiceLineItem(final Risk_Mitigation__c partner) {
Risk__c lineItem = new Risk__c();
lineItem.Risk_Mitigation__c = partner.Id;
insert lineItem;
return lineItem;
}
static testmethod void deliverablesCnt_Should_SaveLineItemChanges() {
//Given
Risk_Mitigation__c aBasicPartner = setupServicePartner();
Risk__c unsavedLineItem = new Risk__c();
unsavedLineItem.Risk_Mitigation__c = aBasicPartner.Id;
//when
Test.startTest();
Test.setCurrentPage(Page.RiskEditPage);
RiskEditPage deliverablesCnt = new RiskEditPage(new ApexPages.StandardController(unsavedLineItem));
//deliverablesCnt.getrisk().add(unsavedLineItem);
PageReference pageRef = deliverablesCnt.saveRisk();
Test.stopTest();
//then
List<Risk__c> associatedLineItems = [
SELECT Risk_Mitigation__c
FROM Risk__c
WHERE Risk_Mitigation__c = :aBasicPartner.Id
];
System.assertEquals(1, associatedLineItems.size(), 'The unsaved service partner line item should have been saved');
System.assertEquals(true, pageRef.getRedirect(), 'Page should redirect');
}
static testmethod void deliverablesCnt_Should_SaveNewLineItemChanges() {
//Given
Risk_Mitigation__c aBasicPartner = setupServicePartner();
Risk__c unsavedLineItem = new Risk__c();
unsavedLineItem.Risk_Mitigation__c = aBasicPartner.Id;
//when
Test.startTest();
Test.setCurrentPage(Page.RiskEditPage);
RiskEditPage deliverablesCnt = new RiskEditPage(new ApexPages.StandardController(unsavedLineItem));
//deliverablesCnt.getrisk().add(unsavedLineItem);
PageReference pageRef = deliverablesCnt.saveNew();
Test.stopTest();
//then
List<Risk__c> associatedLineItems = [
SELECT Risk_Mitigation__c
FROM Risk__c
WHERE Risk_Mitigation__c = :aBasicPartner.Id
];
System.assertEquals(1, associatedLineItems.size(), 'The unsaved service partner line item should have been saved');
System.assertEquals(true, pageRef.getRedirect(), 'Page should redirect');
}
}
APEX CLASS
public class RiskEditPage {
Risk__c risk;
PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
public List<Work_Order__c> woTemp = new List<Work_Order__c>();
public List<SelectOption> woList {get;set;}
public RiskEditPage(apexPages.StandardController controller){
risk = [Select Name, Assign_To__c, OpId__c, Risk_Mitigation__r.OpId__c, FWI_Work_Order__c, Consequence_of_Failure__c, Covered_in_SOW_Hrs__c,
Custom_Development_Required__c, Description__c, Function__c, Risk_Mitigation__c, Risk_of_Failure__c,
Risk_Mitigation__r.Name, Signoff__c, Signoff2__c, Status__c, Strategy_to_Mitigate_Risk__c, Triggering_Action__c, Type__c,
User_Impact__c, Create_Task__c, Risk_of_Failure_Score__c from Risk__c
where Id = :ApexPages.currentPage().getparameters().get('id')];
woTemp = [Select s.Name, s.Id, s.Status__c, s.Type__c From Work_Order__c s where Opportunity__c = :risk.Risk_Mitigation__r.OpId__c Order By Name Asc];
woList = new List<SelectOption>();
for(Work_Order__c temp : woTemp)
{
woList.add(new SelectOption(temp.Id, temp.Name+': '+temp.Type__c));
}
}
public PageReference saveRisk()
{
update risk;
PageReference pageref = new PageReference('/'+risk.Risk_Mitigation__c);
pageRef.setRedirect(true);
return pageRef;
}
public PageReference saveNew()
{
upsert risk;
PageReference pageref = new PageReference('/apex/RiskNewPage?retURL='+risk.Risk_Mitigation__c+'&CF00N4D000000bXd5='+risk.Risk_Mitigation__r.Name+'kid=aDS4D0000004CAB&CF00N4D000000bXd5_lkid='+risk.Risk_Mitigation__c+'&retURL='+risk.Risk_Mitigation__c+'&scontrolCaching=1&sfdc.override=1');
pageRef.setRedirect(true);
return pageRef;
}
}
TEST CLASS
@istest(seealldata=true)
public class RiskEditPageTest {
static Risk_Mitigation__c setupServicePartner() {
Risk_Mitigation__c partner = new Risk_Mitigation__c();
partner.Name = 'test';
partner.Client_Workbook__c = 'a9f34000000TN1F';
insert partner;
return partner;
}
static Risk__c setupServiceLineItem(final Risk_Mitigation__c partner) {
Risk__c lineItem = new Risk__c();
lineItem.Risk_Mitigation__c = partner.Id;
insert lineItem;
return lineItem;
}
static testmethod void deliverablesCnt_Should_SaveLineItemChanges() {
//Given
Risk_Mitigation__c aBasicPartner = setupServicePartner();
Risk__c unsavedLineItem = new Risk__c();
unsavedLineItem.Risk_Mitigation__c = aBasicPartner.Id;
//when
Test.startTest();
Test.setCurrentPage(Page.RiskEditPage);
RiskEditPage deliverablesCnt = new RiskEditPage(new ApexPages.StandardController(unsavedLineItem));
//deliverablesCnt.getrisk().add(unsavedLineItem);
PageReference pageRef = deliverablesCnt.saveRisk();
Test.stopTest();
//then
List<Risk__c> associatedLineItems = [
SELECT Risk_Mitigation__c
FROM Risk__c
WHERE Risk_Mitigation__c = :aBasicPartner.Id
];
System.assertEquals(1, associatedLineItems.size(), 'The unsaved service partner line item should have been saved');
System.assertEquals(true, pageRef.getRedirect(), 'Page should redirect');
}
static testmethod void deliverablesCnt_Should_SaveNewLineItemChanges() {
//Given
Risk_Mitigation__c aBasicPartner = setupServicePartner();
Risk__c unsavedLineItem = new Risk__c();
unsavedLineItem.Risk_Mitigation__c = aBasicPartner.Id;
//when
Test.startTest();
Test.setCurrentPage(Page.RiskEditPage);
RiskEditPage deliverablesCnt = new RiskEditPage(new ApexPages.StandardController(unsavedLineItem));
//deliverablesCnt.getrisk().add(unsavedLineItem);
PageReference pageRef = deliverablesCnt.saveNew();
Test.stopTest();
//then
List<Risk__c> associatedLineItems = [
SELECT Risk_Mitigation__c
FROM Risk__c
WHERE Risk_Mitigation__c = :aBasicPartner.Id
];
System.assertEquals(1, associatedLineItems.size(), 'The unsaved service partner line item should have been saved');
System.assertEquals(true, pageRef.getRedirect(), 'Page should redirect');
}
}
- Andrew Aldis
- July 24, 2017
- Like
- 0
Google Geo Code API wont update the record
I wrote a trigger and class to call out to the Google Geo location api and return the latitude and longitude then update a geolocation field on a location record. Everything seems to work with the API I can see from Debug Logs that the class gets the location but it stops short of updating the record. My trigger and class are below.
CLASS
public class FslLocationGeocodeAddress {
// static variable to determine if geocoding has already occurred
private static Boolean geocodingCalled = false;
// wrapper method to prevent calling futuremethods from an existing future context
public static void DoAddressGeocode(id locationId) {
if(geocodingCalled || System.isFuture()) {
System.debug(LoggingLevel.WARN,'***Address Geocoding Future Method Already Called - Aborting...');
return;
}
// if not being called from future context, geocode the address
geocodingCalled = true;
geocodeAddress(locationId);
}
// we need a future method to call Google Geocoding API from Salesforce
@future (callout=true)
static private void geocodeAddress(id locationId)
{
// Key for Google Maps Geocoding API
String geocodingKey = 'AIzaSyDsXhgOWw8h98l2rWnOcRy4j8_l8Evx3Ms';
// get the passed in address
CKSW_BASE__Location__c geoLocation = [SELECT Street_Address__c, City__c, State_Providence__c, Country__c, Zipcode__c FROM CKSW_BASE__Location__c WHERE id = :locationId];
//check that we have enough information to geocode the address
if((geoLocation.Street_Address__c == null) || (geoLocation.City__c == null)) {
System.debug(LoggingLevel.WARN,'Insufficient Data to Geocode Address');
return;
}
//create a string for the address to pass to Google Geocoding API
String geoAddress = '';
if(geoLocation.Street_Address__c != null)
geoAddress += geoLocation.Street_Address__c + ', ';
if(geoLocation.City__c != null)
geoAddress += geoLocation.City__c + ', ';
if(geoLocation.State_Providence__c != null)
geoAddress+= geoLocation.State_Providence__c + ', ';
if(geoLocation.Country__c != null)
geoAddress+= geoLocation.Country__c + ', ';
if(geoLocation.Zipcode__c != null)
geoAddress+= geoLocation.Zipcode__c;
System.debug('GeoAddress is set '+geoAddress);
//encode the string so we can pass it as part of URL
geoAddress= EncodingUtil.urlEncode(geoAddress, 'UTF-8');
//build and make the callout to the Geocoding API
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?address='+geoAddress + '&key=' + geocodingKey + '&sensor=false');
request.setMethod('GET');
request.setTimeout(60000);
try {
//make the http callout
HttpResponse response = http.send(request);
System.debug('The Http response is '+response);
string body = response.getBody();
System.debug('The response body is' + body);
//parse JSON to extract co-ordinates
JSONParser responseParser = JSON.createParser(response.getBody());
system.debug('The response parser is'+responseParser);
//initialize co-ordinates
double latitude = null;
double longitude = null;
system.debug('Next token prior to the while nextToken != Null is '+responseParser.nextToken());
//while loop 1
while(responseParser.nextToken() != null ) {
if((responseParser.getCurrentToken() == JSONToken.FIELD_NAME) && (responseParser.getText() == 'location')) {
system.debug('If condition true');
system.debug('Current Token = '+responseParser.getCurrentToken()+' Current text = '+responseParser.getText());
responseParser.nextToken();
system.debug('Next Token = '+responseParser.nextToken());
while (responseParser.nextToken() != JSONToken.END_OBJECT) {
system.debug('While condition 2 true');
String locationText = responseParser.getText();
latitude = responseParser.getDoubleValue();
system.debug('responseParser.getText() = '+responseParser.getText());
system.debug('responseParser.getDoubleValue() = '+responseParser.getDoubleValue());
latitude = responseParser.getDoubleValue();
system.debug(latitude);
responseParser.nextToken();
system.debug('responseParser.nextToken() = '+responseParser.nextToken());
system.debug('text ='+responseParser.getText());
system.debug('responseParser.getDoubleValue() = '+responseParser.getDoubleValue());
longitude = responseParser.getDoubleValue();
system.debug(longitude);
}
}
}
system.debug('Latitude = '+latitude);
system.debug('Longitude = '+longitude);
if (longitude != null && latitude != null){
system.debug('latitude != null');
geoLocation.Geolocation__Latitude__s = latitude;
system.debug('Latitude is '+geoLocation.Geolocation__Latitude__s);
geoLocation.Geolocation__Longitude__s = longitude;
system.debug('Longitude is '+geoLocation.Geolocation__Longitude__s);
system.debug('geoLocation id '+geoLocation.Geolocation__c);
update Geolocation;
}
} catch(Exception e) {
System.debug(LoggingLevel.ERROR, 'Error Geocoding Address - ' + e.getMessage());
}
}
}
TRIGGER
trigger FslLocationGeocodeAddress on CKSW_BASE__Location__c (after insert, after update) {
//bulkify trigger in case of multiple locations
for(CKSW_BASE__Location__c location : trigger.new) {
//check if Billing Address has been updated
Boolean addressChangedFlag = false;
if(Trigger.isUpdate) {
CKSW_BASE__Location__c oldLocation = Trigger.oldMap.get(location.Id);
if((location.Street_Address__c != oldLocation.Street_Address__c) || (location.City__c != oldLocation.City__c) ||
(location.Country__c != oldLocation.Country__c) || (location.Zipcode__c != oldLocation.Zipcode__c)) {
addressChangedFlag = true;
System.debug(LoggingLevel.DEBUG, '***Address changed for - ' + oldLocation.Name);
}
}
// if address is null or has been changed, geocode it
if((location.Geolocation__Latitude__s == null && location.Geolocation__Longitude__s == null) || (addressChangedFlag == true)) {
System.debug(LoggingLevel.DEBUG,'***Geocoding CKSW_BASE__Location__c - ' + location.Name);
FslLocationGeocodeAddress.DoAddressGeocode(location.id);
}
}
}
CLASS
public class FslLocationGeocodeAddress {
// static variable to determine if geocoding has already occurred
private static Boolean geocodingCalled = false;
// wrapper method to prevent calling futuremethods from an existing future context
public static void DoAddressGeocode(id locationId) {
if(geocodingCalled || System.isFuture()) {
System.debug(LoggingLevel.WARN,'***Address Geocoding Future Method Already Called - Aborting...');
return;
}
// if not being called from future context, geocode the address
geocodingCalled = true;
geocodeAddress(locationId);
}
// we need a future method to call Google Geocoding API from Salesforce
@future (callout=true)
static private void geocodeAddress(id locationId)
{
// Key for Google Maps Geocoding API
String geocodingKey = 'AIzaSyDsXhgOWw8h98l2rWnOcRy4j8_l8Evx3Ms';
// get the passed in address
CKSW_BASE__Location__c geoLocation = [SELECT Street_Address__c, City__c, State_Providence__c, Country__c, Zipcode__c FROM CKSW_BASE__Location__c WHERE id = :locationId];
//check that we have enough information to geocode the address
if((geoLocation.Street_Address__c == null) || (geoLocation.City__c == null)) {
System.debug(LoggingLevel.WARN,'Insufficient Data to Geocode Address');
return;
}
//create a string for the address to pass to Google Geocoding API
String geoAddress = '';
if(geoLocation.Street_Address__c != null)
geoAddress += geoLocation.Street_Address__c + ', ';
if(geoLocation.City__c != null)
geoAddress += geoLocation.City__c + ', ';
if(geoLocation.State_Providence__c != null)
geoAddress+= geoLocation.State_Providence__c + ', ';
if(geoLocation.Country__c != null)
geoAddress+= geoLocation.Country__c + ', ';
if(geoLocation.Zipcode__c != null)
geoAddress+= geoLocation.Zipcode__c;
System.debug('GeoAddress is set '+geoAddress);
//encode the string so we can pass it as part of URL
geoAddress= EncodingUtil.urlEncode(geoAddress, 'UTF-8');
//build and make the callout to the Geocoding API
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?address='+geoAddress + '&key=' + geocodingKey + '&sensor=false');
request.setMethod('GET');
request.setTimeout(60000);
try {
//make the http callout
HttpResponse response = http.send(request);
System.debug('The Http response is '+response);
string body = response.getBody();
System.debug('The response body is' + body);
//parse JSON to extract co-ordinates
JSONParser responseParser = JSON.createParser(response.getBody());
system.debug('The response parser is'+responseParser);
//initialize co-ordinates
double latitude = null;
double longitude = null;
system.debug('Next token prior to the while nextToken != Null is '+responseParser.nextToken());
//while loop 1
while(responseParser.nextToken() != null ) {
if((responseParser.getCurrentToken() == JSONToken.FIELD_NAME) && (responseParser.getText() == 'location')) {
system.debug('If condition true');
system.debug('Current Token = '+responseParser.getCurrentToken()+' Current text = '+responseParser.getText());
responseParser.nextToken();
system.debug('Next Token = '+responseParser.nextToken());
while (responseParser.nextToken() != JSONToken.END_OBJECT) {
system.debug('While condition 2 true');
String locationText = responseParser.getText();
latitude = responseParser.getDoubleValue();
system.debug('responseParser.getText() = '+responseParser.getText());
system.debug('responseParser.getDoubleValue() = '+responseParser.getDoubleValue());
latitude = responseParser.getDoubleValue();
system.debug(latitude);
responseParser.nextToken();
system.debug('responseParser.nextToken() = '+responseParser.nextToken());
system.debug('text ='+responseParser.getText());
system.debug('responseParser.getDoubleValue() = '+responseParser.getDoubleValue());
longitude = responseParser.getDoubleValue();
system.debug(longitude);
}
}
}
system.debug('Latitude = '+latitude);
system.debug('Longitude = '+longitude);
if (longitude != null && latitude != null){
system.debug('latitude != null');
geoLocation.Geolocation__Latitude__s = latitude;
system.debug('Latitude is '+geoLocation.Geolocation__Latitude__s);
geoLocation.Geolocation__Longitude__s = longitude;
system.debug('Longitude is '+geoLocation.Geolocation__Longitude__s);
system.debug('geoLocation id '+geoLocation.Geolocation__c);
update Geolocation;
}
} catch(Exception e) {
System.debug(LoggingLevel.ERROR, 'Error Geocoding Address - ' + e.getMessage());
}
}
}
TRIGGER
trigger FslLocationGeocodeAddress on CKSW_BASE__Location__c (after insert, after update) {
//bulkify trigger in case of multiple locations
for(CKSW_BASE__Location__c location : trigger.new) {
//check if Billing Address has been updated
Boolean addressChangedFlag = false;
if(Trigger.isUpdate) {
CKSW_BASE__Location__c oldLocation = Trigger.oldMap.get(location.Id);
if((location.Street_Address__c != oldLocation.Street_Address__c) || (location.City__c != oldLocation.City__c) ||
(location.Country__c != oldLocation.Country__c) || (location.Zipcode__c != oldLocation.Zipcode__c)) {
addressChangedFlag = true;
System.debug(LoggingLevel.DEBUG, '***Address changed for - ' + oldLocation.Name);
}
}
// if address is null or has been changed, geocode it
if((location.Geolocation__Latitude__s == null && location.Geolocation__Longitude__s == null) || (addressChangedFlag == true)) {
System.debug(LoggingLevel.DEBUG,'***Geocoding CKSW_BASE__Location__c - ' + location.Name);
FslLocationGeocodeAddress.DoAddressGeocode(location.id);
}
}
}
- Andrew Aldis
- June 23, 2017
- Like
- 0
Iterating through a query using list results.
I am writing a class that will query a list of subsidiary accounts and return the account id's then iterate over those query results to return a list of related contacts, but I keep getting errors. The object I am querying from is a custom object called account plans and I am trying to query a child records of a junction object called subsidiary accounts, I then want to take those list results and and query contacts related to the subsidiary accounts and add them to select options list for a VF page. The error I get is 'Invalid bind expression type of Subsidiary_Accounts__c does not match domain of foreign key' and my code is below.
system.debug('conList list = '+conList.Size());
subs = [Select Account__c From Subsidiary_Accounts__c Where Account_Plan__c = :plan.Id];
system.debug('Subs list = '+subs.Size());
system.debug('subs id 1 ='+subs[0]);
system.debug('subs account id 1 ='+subs[0].Account__c);
subConTemp =[Select c.Name, c.Title, c.Id From Contact c Where ContactInformation__c = true and Contact.AccountId in :subs Order by Name Asc];
for(Contact temp :subConTemp){
conList.add(new SelectOption(temp.Id+' '+temp.Title, temp.Name));
}
system.debug('conList list = '+conList.Size());
subs = [Select Account__c From Subsidiary_Accounts__c Where Account_Plan__c = :plan.Id];
system.debug('Subs list = '+subs.Size());
system.debug('subs id 1 ='+subs[0]);
system.debug('subs account id 1 ='+subs[0].Account__c);
subConTemp =[Select c.Name, c.Title, c.Id From Contact c Where ContactInformation__c = true and Contact.AccountId in :subs Order by Name Asc];
for(Contact temp :subConTemp){
conList.add(new SelectOption(temp.Id+' '+temp.Title, temp.Name));
}
- Andrew Aldis
- June 06, 2017
- Like
- 0
Convert a string variable to a Id in a test class.
I wrote a trigger that parses values from the Description field on our case object. The purpose is to parse out values from our internal monitoring service to update fields and the appropriate accounts. The parsing works and the trigger has worked consistantly in our sandbox but I cannot write a test class that passes. I keep getting an the following error: "System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, RmmEmailCaseUpdate: execution of AfterInsert
caused by: System.StringException: Invalid id:
Trigger.RmmEmailCaseUpdate: line 51, column 1: []"
The account I am using in the string is correct and always sets the account when I use the trigger in Sandbox but does not work when I write the test class. My class and test class are below.
trigger RmmEmailCaseUpdate on Case (after insert) {
if (trigger.isAfter){
if (trigger.isUpdate || trigger.isInsert){
//Create set of Opportunity Ids based on updated Opportunity/s
Set <String> caseIds = new Set <String>();
for (Case ca : trigger.new){
caseIds.add(ca.ID);
}
Map <String, case>matchingcasecomps = new Map <String, case> ();
for(case c: [select Id, Subject, Description, SuppliedEmail, RMM_Alert_Date_and_Time__c , RMM_Action_Required__c, RMM_Computer_Name__c, RMM_Error_Message__c ,
RMM_Client_Location__c, RMM_Last_Contact_with_Player__c from case where Id in :caseIds])
{
IF( c.SuppliedEmail == 'nocmonitoring@fourwindsinteractive.com' && c.subject.startswith('FWIRMM - Offline Players:')){
{
string body = c.Description;
string sub = c.Subject;
string fromAdd = c.SuppliedEmail;
dateTime alertDate = system.now();
string action;
string computer;
string alert;
string location;
string contact;
string accRmm;
string accTrimFront;
string accTrimRear;
Id accId;
List<string> parse = body.split('\\n');
alert = parse[0];
computer = parse[1];
location = parse[3];
contact = parse[4];
action = parse[5];
accRmm = parse[8];
accTrimFront = accRmm.replaceFirst('\\[(?:rmm)\\:', '');
accTrimRear = accTrimFront.replaceFirst('\\:(?:rmm)\\]', '');
string accString = accTrimRear;
/*List<Account> accQuery = [Select Id from Account Where Id =:accString];
FOR(Account accQ: accQuery){
IF(accQuery[0] != Null){
accId = [Select Id from Account Where Id =:accString].Id;
}else{
accId='';
}}*/
accId = Id.valueOf(accString);
c.RMM_Alert_Date_and_Time__c = system.now();
c.RMM_Action_Required__c = action;
c.RMM_Computer_Name__c = computer;
c.RMM_Error_Message__c = alert;
c.RMM_Client_Location__c = location;
c.RMM_Last_Contact_with_Player__c = contact;
c.AccountId = accId;
update c;
}
@isTest(seealldata = true)
public class RmmEmailCaseUpdateTest {
static testMethod void RmmEmailCaseUpdate(){
Case c = new Case(
subject ='FWIRMM - Offline Players:',
Description = 'Alert issue - Content Player PC is unreachable \r\n Computer - CLTSD \r\n PC Type/Serial Number - FWPW-QUAD-WIFI-SW / GIG41327 \r\n \r\n Alert Date and Time - 4/25/2017 3:17:27 AM Client/Location - SpringHill Suites / SpringHill Suites Site \r\n Last contact with Player: ~4/25/2017 12:29:52 AM id 4113~ FAILED \r\n \r\n ACTION REQUIRED - Investigate computer logs. If no fault found, contact client to get PC back online. \r\n \r\n [rmm:0018000000MEgf1:rmm]',
Origin = 'NOC',
Status = 'New',
RecordTypeId = '0123400000046GJ',
SuppliedEmail = 'nocmonitoring@fourwindsinteractive.com');{
insert c;
}
}
}
caused by: System.StringException: Invalid id:
Trigger.RmmEmailCaseUpdate: line 51, column 1: []"
The account I am using in the string is correct and always sets the account when I use the trigger in Sandbox but does not work when I write the test class. My class and test class are below.
trigger RmmEmailCaseUpdate on Case (after insert) {
if (trigger.isAfter){
if (trigger.isUpdate || trigger.isInsert){
//Create set of Opportunity Ids based on updated Opportunity/s
Set <String> caseIds = new Set <String>();
for (Case ca : trigger.new){
caseIds.add(ca.ID);
}
Map <String, case>matchingcasecomps = new Map <String, case> ();
for(case c: [select Id, Subject, Description, SuppliedEmail, RMM_Alert_Date_and_Time__c , RMM_Action_Required__c, RMM_Computer_Name__c, RMM_Error_Message__c ,
RMM_Client_Location__c, RMM_Last_Contact_with_Player__c from case where Id in :caseIds])
{
IF( c.SuppliedEmail == 'nocmonitoring@fourwindsinteractive.com' && c.subject.startswith('FWIRMM - Offline Players:')){
{
string body = c.Description;
string sub = c.Subject;
string fromAdd = c.SuppliedEmail;
dateTime alertDate = system.now();
string action;
string computer;
string alert;
string location;
string contact;
string accRmm;
string accTrimFront;
string accTrimRear;
Id accId;
List<string> parse = body.split('\\n');
alert = parse[0];
computer = parse[1];
location = parse[3];
contact = parse[4];
action = parse[5];
accRmm = parse[8];
accTrimFront = accRmm.replaceFirst('\\[(?:rmm)\\:', '');
accTrimRear = accTrimFront.replaceFirst('\\:(?:rmm)\\]', '');
string accString = accTrimRear;
/*List<Account> accQuery = [Select Id from Account Where Id =:accString];
FOR(Account accQ: accQuery){
IF(accQuery[0] != Null){
accId = [Select Id from Account Where Id =:accString].Id;
}else{
accId='';
}}*/
accId = Id.valueOf(accString);
c.RMM_Alert_Date_and_Time__c = system.now();
c.RMM_Action_Required__c = action;
c.RMM_Computer_Name__c = computer;
c.RMM_Error_Message__c = alert;
c.RMM_Client_Location__c = location;
c.RMM_Last_Contact_with_Player__c = contact;
c.AccountId = accId;
update c;
}
@isTest(seealldata = true)
public class RmmEmailCaseUpdateTest {
static testMethod void RmmEmailCaseUpdate(){
Case c = new Case(
subject ='FWIRMM - Offline Players:',
Description = 'Alert issue - Content Player PC is unreachable \r\n Computer - CLTSD \r\n PC Type/Serial Number - FWPW-QUAD-WIFI-SW / GIG41327 \r\n \r\n Alert Date and Time - 4/25/2017 3:17:27 AM Client/Location - SpringHill Suites / SpringHill Suites Site \r\n Last contact with Player: ~4/25/2017 12:29:52 AM id 4113~ FAILED \r\n \r\n ACTION REQUIRED - Investigate computer logs. If no fault found, contact client to get PC back online. \r\n \r\n [rmm:0018000000MEgf1:rmm]',
Origin = 'NOC',
Status = 'New',
RecordTypeId = '0123400000046GJ',
SuppliedEmail = 'nocmonitoring@fourwindsinteractive.com');{
insert c;
}
}
}
- Andrew Aldis
- April 26, 2017
- Like
- 0
System.QueryException: List has no rows for assignment to SObject on test class
I am trying to write a test class for a controller extension and cannot seem to get it to work I keep getting a error: "System.QueryException: List has no rows for assignment to SObject on test class" and cannot figure out why. My controller and test class are below.
public class HardwareWoSalesOrderLineEdit {
public HardwareWoSalesOrderLineEdit(ApexPages.StandardController controller) {
//parent record
this.proj =[select Sales_Order__c, Id, X2nd_Sales_Order__c From Work_Order__c Where Id = :ApexPages.currentPage().getParameters().get('id')];
// child records
this.line = [ SELECT SCMC__Quantity__c, Item_Name__c,SCMC__Quantity_Shipped__c, Category__c, SCMC__Item_Description__c, PM_Ordering_Details__c, Quantity_to_Ship__c, Remaining_Quantity__c
FROM SCMC__Sales_Order_Line_Item__c
WHERE (Item_Type__c = 'Hardware' AND SCMC__Status__c != 'Completed' AND SCMC__Status__c != 'Shipped' AND Category__c != 'Physical Install' AND SCMC__Status__c != 'Cancelled' AND SCMC__Sales_Order__c = :proj.Sales_Order__c) OR
(Item_Type__c = 'Hardware' AND SCMC__Status__c != 'Completed' AND SCMC__Status__c != 'Shipped' AND Category__c != 'Physical Install' AND SCMC__Status__c != 'Cancelled' AND SCMC__Sales_Order__c = :proj.X2nd_Sales_Order__c) ORDER BY Category__c ASC ];
}
//get sales order lines
public SCMC__Sales_Order_Line_Item__c[] getline() {
return this.line;
}
// save method to save changes to the sales order lines
public pagereference saveChanges() {
upsert this.line;
pageRef.setRedirect(true);
return pageRef;
}
// class variables
public PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
public Work_Order__c proj;
public SCMC__Sales_Order_Line_Item__c[] line;
}
TEST CLASS
@istest(seealldata=true)
public class HardwareWoSalesOrderLineEditTest{
static testMethod void HardwareWoSalesOrderLineEditTest(){
Test.startTest();
SCMC__Sales_Order_Line_Item__c sol = [Select Id, SCMC__Item_Master__c, SCMC__Sales_Order__c, SCMC__Sales_Order__r.Installation__c, CreatedById,
SCMC__Sales_Order__r.SCMC__Customer_Account__c
from SCMC__Sales_Order_Line_Item__c where Item_Type__c = 'Hardware' AND SCMC__Status__c != 'Completed'
AND SCMC__Status__c != 'Shipped' AND Category__c != 'Physical Install' limit 1];
system.assertnotEquals(null, sol);
system.debug(sol.Id);
Work_Order__c wo = new Work_Order__c(
Account__c = sol.SCMC__Sales_Order__r.SCMC__Customer_Account__c,
Sales_Order__c = sol.SCMC__Sales_Order__c,
Installation__c = sol.SCMC__Sales_Order__r.Installation__c,
Resource__c = sol.CreatedById,
Type__c = 'Hardware Order',
Start_Date__c = system.today(),
Due_Date__c = system.today(),
Confirm_address_is_correct__c = true,
RecordTypeId = '01234000000Bmk8',
Name = 'testwo123');{
insert wo;}
system.assertnotEquals(null, wo);
system.debug(wo.Id);
Work_Order__c w = [Select Id from Work_Order__c Where Name = 'testwo123' Limit 1];
system.assertnotEquals(null, w);
system.debug(w);
Test.setCurrentPage(Page.HardwareWoSalesOrderLineEdit);
ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(w);
system.debug(sc);
HardwareWoSalesOrderLineEdit myPageCon = new HardwareWoSalesOrderLineEdit(sc);
system.debug(myPageCon);
myPageCon.getline().add(sol);
myPageCon.saveChanges();
Test.stopTest();
}
}
public class HardwareWoSalesOrderLineEdit {
public HardwareWoSalesOrderLineEdit(ApexPages.StandardController controller) {
//parent record
this.proj =[select Sales_Order__c, Id, X2nd_Sales_Order__c From Work_Order__c Where Id = :ApexPages.currentPage().getParameters().get('id')];
// child records
this.line = [ SELECT SCMC__Quantity__c, Item_Name__c,SCMC__Quantity_Shipped__c, Category__c, SCMC__Item_Description__c, PM_Ordering_Details__c, Quantity_to_Ship__c, Remaining_Quantity__c
FROM SCMC__Sales_Order_Line_Item__c
WHERE (Item_Type__c = 'Hardware' AND SCMC__Status__c != 'Completed' AND SCMC__Status__c != 'Shipped' AND Category__c != 'Physical Install' AND SCMC__Status__c != 'Cancelled' AND SCMC__Sales_Order__c = :proj.Sales_Order__c) OR
(Item_Type__c = 'Hardware' AND SCMC__Status__c != 'Completed' AND SCMC__Status__c != 'Shipped' AND Category__c != 'Physical Install' AND SCMC__Status__c != 'Cancelled' AND SCMC__Sales_Order__c = :proj.X2nd_Sales_Order__c) ORDER BY Category__c ASC ];
}
//get sales order lines
public SCMC__Sales_Order_Line_Item__c[] getline() {
return this.line;
}
// save method to save changes to the sales order lines
public pagereference saveChanges() {
upsert this.line;
pageRef.setRedirect(true);
return pageRef;
}
// class variables
public PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
public Work_Order__c proj;
public SCMC__Sales_Order_Line_Item__c[] line;
}
TEST CLASS
@istest(seealldata=true)
public class HardwareWoSalesOrderLineEditTest{
static testMethod void HardwareWoSalesOrderLineEditTest(){
Test.startTest();
SCMC__Sales_Order_Line_Item__c sol = [Select Id, SCMC__Item_Master__c, SCMC__Sales_Order__c, SCMC__Sales_Order__r.Installation__c, CreatedById,
SCMC__Sales_Order__r.SCMC__Customer_Account__c
from SCMC__Sales_Order_Line_Item__c where Item_Type__c = 'Hardware' AND SCMC__Status__c != 'Completed'
AND SCMC__Status__c != 'Shipped' AND Category__c != 'Physical Install' limit 1];
system.assertnotEquals(null, sol);
system.debug(sol.Id);
Work_Order__c wo = new Work_Order__c(
Account__c = sol.SCMC__Sales_Order__r.SCMC__Customer_Account__c,
Sales_Order__c = sol.SCMC__Sales_Order__c,
Installation__c = sol.SCMC__Sales_Order__r.Installation__c,
Resource__c = sol.CreatedById,
Type__c = 'Hardware Order',
Start_Date__c = system.today(),
Due_Date__c = system.today(),
Confirm_address_is_correct__c = true,
RecordTypeId = '01234000000Bmk8',
Name = 'testwo123');{
insert wo;}
system.assertnotEquals(null, wo);
system.debug(wo.Id);
Work_Order__c w = [Select Id from Work_Order__c Where Name = 'testwo123' Limit 1];
system.assertnotEquals(null, w);
system.debug(w);
Test.setCurrentPage(Page.HardwareWoSalesOrderLineEdit);
ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(w);
system.debug(sc);
HardwareWoSalesOrderLineEdit myPageCon = new HardwareWoSalesOrderLineEdit(sc);
system.debug(myPageCon);
myPageCon.getline().add(sol);
myPageCon.saveChanges();
Test.stopTest();
}
}
- Andrew Aldis
- April 21, 2017
- Like
- 0
Flow from a visual force page
I am trying to call a flow from a visual force page to launch a simple wizard to create records. I am trying to call the flow from a button on a Tabbed Visual force page with a related list. All I need to do is set the flows variable with the ID from the I have tried using a standard controller of the parent object and the child object as well as multiple classes, and none of them seem to be able to set the variable. Below is my Class and VF page.
public class SignInstanceWizardVfPageClass {
Public String VarId = ApexPages.currentPage().getParameters().get('id');
public Client_Workbook__c CwId {get; set;}
public SignInstanceWizardVfPageClass() {
CwId = [SELECT Id FROM Client_Workbook__c WHERE Id = :VarId LIMIT 1];
}
}
<apex:page Controller="SignInstanceWizardVfPageClass" >
<flow:interview name="SignInstanceWizard" >
<apex:param name="ClientWorkbookId" value="{!CwId}"/>
</flow:interview>
</apex:page>
public class SignInstanceWizardVfPageClass {
Public String VarId = ApexPages.currentPage().getParameters().get('id');
public Client_Workbook__c CwId {get; set;}
public SignInstanceWizardVfPageClass() {
CwId = [SELECT Id FROM Client_Workbook__c WHERE Id = :VarId LIMIT 1];
}
}
<apex:page Controller="SignInstanceWizardVfPageClass" >
<flow:interview name="SignInstanceWizard" >
<apex:param name="ClientWorkbookId" value="{!CwId}"/>
</flow:interview>
</apex:page>
- Andrew Aldis
- April 10, 2017
- Like
- 0
Retrieve a list of child records for a VF picklist
I am trying to create a VF page that will allow me to query related records and use the list as options for a VF page Picklist. I got it working but when I add a where condition to my Query I get this error "Content cannot be displayed: SObject row was retrieved via SOQL without querying the requested field: Package__c.Client_Workbook__c" I am not sure why it does not accept my where clause. Can someone let me know where I went wrong.
public class PackageSignInstanceJunctionController {
// Constructor
public PackageSignInstanceJunctionController(ApexPages.StandardController controller)
//master
{
this.proj = (Package__c)controller.getRecord();
this.clientWorkbook = proj.Client_Workbook__c;
this.junction = [ SELECT t.Package__c, t.Sign_Instance__c, t.Name, t.Id, t.Record_Type_Name__c, t.CreatedDate
FROM Package_Sign_Instance_Junction__c t
WHERE t.Package__c = :proj.Id ORDER BY t.CreatedDate Desc];
//Picklist Options
signTemp = [Select s.Name, s.Id From Sign_Instance__c s where Client_Workbook__c = :clientWorkbook];
signList = new List<SelectOption>();
for(Sign_Instance__c temp : signTemp)
{
signList.add(new SelectOption(temp.Id, temp.Name));
}
}
// Insert new Staff junction
public pagereference insertmethod()
{
Package_Sign_Instance_Junction__c cc= new Package_Sign_Instance_Junction__c();
cc.Package__c = proj.id;
insert cc;
return null;
}
public Package_Sign_Instance_Junction__c[] getjunction() {
return this.junction;
}
// Action Method called from page button
public pagereference saveChanges() {
upsert this.junction;
pageRef.setRedirect(true);
return pageRef;
}
// Action Method called from page link
public pagereference newjunction() {
Package_Sign_Instance_Junction__c d = new Package_Sign_Instance_Junction__c();
d.Package__c = this.proj.id;
junction.add( d );
getjunction();
return null;
}
public pagereference DeleteAccount()
{
// if for any reason we are missing the reference
if (SelectedAccountId == null)
{
return null;
}
// find the account record within the collection
Package_Sign_Instance_Junction__c tobeDeleted = null;
for(Package_Sign_Instance_Junction__c a : this.junction)
if (a.Id == SelectedAccountId)
{
tobeDeleted = a;
break;
}
//if account record found delete it
if (tobeDeleted != null)
{
Delete tobeDeleted;
}
pageRef.setRedirect(true);
return pageRef;
}
// class variables
PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
public List<Sign_Instance__c> signTemp = new List<Sign_Instance__c>();
Package__c proj;
Package_Sign_Instance_Junction__c[] junction;
Sign_Instance__c[] sign;
public string SelectedAccountId { get; set; }
public string clientWorkbook { get; set; }
public List<SelectOption> signList {get;set;}
}
public class PackageSignInstanceJunctionController {
// Constructor
public PackageSignInstanceJunctionController(ApexPages.StandardController controller)
//master
{
this.proj = (Package__c)controller.getRecord();
this.clientWorkbook = proj.Client_Workbook__c;
this.junction = [ SELECT t.Package__c, t.Sign_Instance__c, t.Name, t.Id, t.Record_Type_Name__c, t.CreatedDate
FROM Package_Sign_Instance_Junction__c t
WHERE t.Package__c = :proj.Id ORDER BY t.CreatedDate Desc];
//Picklist Options
signTemp = [Select s.Name, s.Id From Sign_Instance__c s where Client_Workbook__c = :clientWorkbook];
signList = new List<SelectOption>();
for(Sign_Instance__c temp : signTemp)
{
signList.add(new SelectOption(temp.Id, temp.Name));
}
}
// Insert new Staff junction
public pagereference insertmethod()
{
Package_Sign_Instance_Junction__c cc= new Package_Sign_Instance_Junction__c();
cc.Package__c = proj.id;
insert cc;
return null;
}
public Package_Sign_Instance_Junction__c[] getjunction() {
return this.junction;
}
// Action Method called from page button
public pagereference saveChanges() {
upsert this.junction;
pageRef.setRedirect(true);
return pageRef;
}
// Action Method called from page link
public pagereference newjunction() {
Package_Sign_Instance_Junction__c d = new Package_Sign_Instance_Junction__c();
d.Package__c = this.proj.id;
junction.add( d );
getjunction();
return null;
}
public pagereference DeleteAccount()
{
// if for any reason we are missing the reference
if (SelectedAccountId == null)
{
return null;
}
// find the account record within the collection
Package_Sign_Instance_Junction__c tobeDeleted = null;
for(Package_Sign_Instance_Junction__c a : this.junction)
if (a.Id == SelectedAccountId)
{
tobeDeleted = a;
break;
}
//if account record found delete it
if (tobeDeleted != null)
{
Delete tobeDeleted;
}
pageRef.setRedirect(true);
return pageRef;
}
// class variables
PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
public List<Sign_Instance__c> signTemp = new List<Sign_Instance__c>();
Package__c proj;
Package_Sign_Instance_Junction__c[] junction;
Sign_Instance__c[] sign;
public string SelectedAccountId { get; set; }
public string clientWorkbook { get; set; }
public List<SelectOption> signList {get;set;}
}
- Andrew Aldis
- March 21, 2017
- Like
- 0
Add attachment to a task with Inbound Email Handler
I am creating a inbound email handler class to create a task when an email is recieved. I would like any attachment to be added to the task as well but cannot seem to get that part to work. The class will create a task correclty it just won't create the attachment. My code is below.
global class partnerTaskEmailClass implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.Inboundenvelope envelope){
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
Contact Contact;
if([select count() from Contact where Email = :email.fromAddress ] == 0)
{
Contact = [Select ID, Account_Id__c from Contact where email = 'tcaldwell@fourwindsinteractive.com' AND Account_Id__c = '0018000001BeR5A' limit 1];
}
else {
Contact = [Select ID, Account_Id__c from Contact where email = :email.fromAddress ];
}
task t = new task();
t.WhoId = Contact.Id;
t.whatId = Contact.Account_Id__c;
t.Subject = email.subject;
t.description = email.PlainTextBody;
t.Partner_Email_Address__c = email.fromAddress;
t.Type = 'Partner Request';
t.ActivityDate = Date.today().addDays(1);
t.RecordTypeId = '0121b000000CkAG';
t.OwnerId = '00580000004V5YW';
t.Priority = 'Normal';
insert t;
if(email.textAttachments != null)
{
Task newtask = [Select Id from Task where Subject = : email.subject order by CreatedDate Desc Limit 1];
for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
Attachment attachment = new Attachment();
attachment.Name = tAttachment.fileName;
attachment.Body = Blob.valueOf(tAttachment.body);
attachment.ParentId = newtask.Id;
insert attachment;
}
}
Return Result;
}
}
global class partnerTaskEmailClass implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.Inboundenvelope envelope){
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
Contact Contact;
if([select count() from Contact where Email = :email.fromAddress ] == 0)
{
Contact = [Select ID, Account_Id__c from Contact where email = 'tcaldwell@fourwindsinteractive.com' AND Account_Id__c = '0018000001BeR5A' limit 1];
}
else {
Contact = [Select ID, Account_Id__c from Contact where email = :email.fromAddress ];
}
task t = new task();
t.WhoId = Contact.Id;
t.whatId = Contact.Account_Id__c;
t.Subject = email.subject;
t.description = email.PlainTextBody;
t.Partner_Email_Address__c = email.fromAddress;
t.Type = 'Partner Request';
t.ActivityDate = Date.today().addDays(1);
t.RecordTypeId = '0121b000000CkAG';
t.OwnerId = '00580000004V5YW';
t.Priority = 'Normal';
insert t;
if(email.textAttachments != null)
{
Task newtask = [Select Id from Task where Subject = : email.subject order by CreatedDate Desc Limit 1];
for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
Attachment attachment = new Attachment();
attachment.Name = tAttachment.fileName;
attachment.Body = Blob.valueOf(tAttachment.body);
attachment.ParentId = newtask.Id;
insert attachment;
}
}
Return Result;
}
}
- Andrew Aldis
- January 13, 2017
- Like
- 0
A problem with the OnClick JavaScript for this button or link was encountered: records[i] is undefined
I have a custom button which is generate child records. The button works perfectly but before in creates the record I get the following error message. A problem with the OnClick JavaScript for this button or link was encountered: records[i] is undefined. I cannot get rid of that error message but other that that it works perfectly can someone let me know what I need to do to get rid of that error? My Code is below.
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")}
var userId = '{!$User.Id}';
var utc = new Date().toJSON().slice(0,10);
var sol = "Select Id, PSA_Assigned_to_ID__c, PSA_BIllable_Hours__c, PSA_Duration__c,PSA_Task_Automation__c, PSA_Task_Automation_Notes__c, PSA_Task_Automation_Role__c, PSA_Task_Automation_Task_Name__c From SCMC__Sales_Order_Line_Item__c where PSA_Task_Automation__c = True AND PSA_Created__c = False AND SCMC__Sales_Order__r.Installation__c = '{!SFDC_Project__c.Id}'";
var query = sforce.connection.query(sol);
var records = query.getArray("records");
if(userId != "00580000008JMjO" )
{alert("Only authorized staff can auto create Project Tasks, if you need to auto-create Project Tasks contact bi@fourwindsinteractive.com to request access.")
}else{
confirm("There are "+records.length+" Sales Order Line Items that will auto-create Project Tasks. Click OK to create tasks.");
for(var i=0; i<=records.length; i++){
var psa = new sforce.SObject("Project_Task__c");
psa.Project__c = '{!SFDC_Project__c.Id}';
psa.Assigned_To__c = records[i].PSA_Assigned_to_ID__c;
psa.Project_Task_Notes__c = records[i].PSA_Task_Automation_Notes__c;
psa.Role__c = records[i].PSA_Task_Automation_Role__c;
psa.Task__c = records[i].PSA_Task_Automation_Task_Name__c;
psa.Start_Date__c = utc;
psa.Duration__c = records[i].PSA_Duration__c;
psa.Budgeted_Billable_Hours__c = records[i].PSA_BIllable_Hours__c;
console.log(psa);
result=sforce.connection.create([psa]);
console.log(result);
}
}
{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")}
var userId = '{!$User.Id}';
var utc = new Date().toJSON().slice(0,10);
var sol = "Select Id, PSA_Assigned_to_ID__c, PSA_BIllable_Hours__c, PSA_Duration__c,PSA_Task_Automation__c, PSA_Task_Automation_Notes__c, PSA_Task_Automation_Role__c, PSA_Task_Automation_Task_Name__c From SCMC__Sales_Order_Line_Item__c where PSA_Task_Automation__c = True AND PSA_Created__c = False AND SCMC__Sales_Order__r.Installation__c = '{!SFDC_Project__c.Id}'";
var query = sforce.connection.query(sol);
var records = query.getArray("records");
if(userId != "00580000008JMjO" )
{alert("Only authorized staff can auto create Project Tasks, if you need to auto-create Project Tasks contact bi@fourwindsinteractive.com to request access.")
}else{
confirm("There are "+records.length+" Sales Order Line Items that will auto-create Project Tasks. Click OK to create tasks.");
for(var i=0; i<=records.length; i++){
var psa = new sforce.SObject("Project_Task__c");
psa.Project__c = '{!SFDC_Project__c.Id}';
psa.Assigned_To__c = records[i].PSA_Assigned_to_ID__c;
psa.Project_Task_Notes__c = records[i].PSA_Task_Automation_Notes__c;
psa.Role__c = records[i].PSA_Task_Automation_Role__c;
psa.Task__c = records[i].PSA_Task_Automation_Task_Name__c;
psa.Start_Date__c = utc;
psa.Duration__c = records[i].PSA_Duration__c;
psa.Budgeted_Billable_Hours__c = records[i].PSA_BIllable_Hours__c;
console.log(psa);
result=sforce.connection.create([psa]);
console.log(result);
}
}
- Andrew Aldis
- September 14, 2016
- Like
- 0
Custom Button to Create Child Records
I am trying to create a button that will run a quary then create child records. The query seems to be working but the insert fails, usually do to incorrect data types such as dates and ids coming across as strings. I have rewritten it a couple of time to upsert and create the records but run into the same problem either way. When I remove the quotes from the values I am going to insert it fails to recognize the values. Can some one help I feel like there are just 1 or 2 little tweaks needed to get this working.
{!REQUIRESCRIPT("/soap/ajax/25.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")}
var sol = sforce.connection.query("Select Id, Name, SCMC__Sales_Order__c, SCMC__Sales_Order__r.Id, Installation_ID__c, SCMC__Item_Master__r.Id, SCMC__Item_Master__r.PSA_Task_Automation__c, SCMC__Item_Master__r.PSA_Task_Automation_Assigned_To__c, SCMC__Item_Master__r.PSA_Task_Automation_Budg_Bill_Hours__c, SCMC__Item_Master__r.PSA_Task_Automation_Duration__c, SCMC__Item_Master__r.PSA_Task_Automation_Notes__c, SCMC__Item_Master__r.PSA_Task_Automation_Role__c, SCMC__Item_Master__r.PSA_Task_Automation_Task_Name__c, PSA_Created__c, PSA_Task_Automation__c From SCMC__Sales_Order_Line_Item__c where PSA_Task_Automation__c = True AND PSA_Created__c = False AND SCMC__Sales_Order__r.Installation__c = '{!SFDC_Project__c.Id}'");
var records = sol.getArray("records");
if("{!$User.Id}"== "00580000008JMjO" ){
confirm("This will create "+records.length+" Project Tasks.");
for(var i=0; i<=records.length; i++){
var psa = new sforce.SObject("Project_Task__c");
psa.Project__c = '{!SFDC_Project__c.Id}';
psa.Assigned_To__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Assigned_To__c';
psa.Project_Task_Notes__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Notes__c';
psa.Role__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Role__c';
psa.Task__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Task_Name__c';
psa.Start_Date__c = '{!TODAY()}';
psa.Duration__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Duration__c';
}
var result = sforce.connection.upsert('Id',[psa]);
if (result[0].getBoolean("success")) {
alert("new tasks created with id " + result[0].id);
} else {
alert("failed to create tasks " + result[0]);
}
alert('There are no automated tasks to create.');
}
{!REQUIRESCRIPT("/soap/ajax/25.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")}
var sol = sforce.connection.query("Select Id, Name, SCMC__Sales_Order__c, SCMC__Sales_Order__r.Id, Installation_ID__c, SCMC__Item_Master__r.Id, SCMC__Item_Master__r.PSA_Task_Automation__c, SCMC__Item_Master__r.PSA_Task_Automation_Assigned_To__c, SCMC__Item_Master__r.PSA_Task_Automation_Budg_Bill_Hours__c, SCMC__Item_Master__r.PSA_Task_Automation_Duration__c, SCMC__Item_Master__r.PSA_Task_Automation_Notes__c, SCMC__Item_Master__r.PSA_Task_Automation_Role__c, SCMC__Item_Master__r.PSA_Task_Automation_Task_Name__c, PSA_Created__c, PSA_Task_Automation__c From SCMC__Sales_Order_Line_Item__c where PSA_Task_Automation__c = True AND PSA_Created__c = False AND SCMC__Sales_Order__r.Installation__c = '{!SFDC_Project__c.Id}'");
var records = sol.getArray("records");
if("{!$User.Id}"== "00580000008JMjO" ){
confirm("This will create "+records.length+" Project Tasks.");
for(var i=0; i<=records.length; i++){
var psa = new sforce.SObject("Project_Task__c");
psa.Project__c = '{!SFDC_Project__c.Id}';
psa.Assigned_To__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Assigned_To__c';
psa.Project_Task_Notes__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Notes__c';
psa.Role__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Role__c';
psa.Task__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Task_Name__c';
psa.Start_Date__c = '{!TODAY()}';
psa.Duration__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Duration__c';
}
var result = sforce.connection.upsert('Id',[psa]);
if (result[0].getBoolean("success")) {
alert("new tasks created with id " + result[0].id);
} else {
alert("failed to create tasks " + result[0]);
}
alert('There are no automated tasks to create.');
}
- Andrew Aldis
- September 13, 2016
- Like
- 0
Redirect a Visual Force Page to another VF Page
I created a Visual Force page using a standard controller only. When the user saves I want the page to redirect to a second page that reders the information as a PDF. Is there a way to do this?
<apex:page StandardController="Work_Order__c" >
<apex:form >
<apex:pageBlock >
<apex:pageBlockButtons >
<apex:commandButton action="{!URLFOR($Action.Work_Order__c.HotSwapFormInput)}" value="Edit"/>
<apex:commandButton Action="{!URLFOR($Action.Work_Order__c.Download_PDF)}" Value="Download PDF"/>
</apex:pageBlockButtons>
<center>
<table Width="100%" Style="border:.5px solid blank;" cellspacing="0">
<tr >
<th colspan="2" Style="background-color:grey; Border:1px solid black; background-color:#cccccc"><b>Request Information</b></th>
</tr>
<tr>
<td Style="border-collapse: separate;border-spacing: 0px 0px; Border:Solid Black .5pt; width: 200px">Requested Date</td>
<td Style="border-collapse: separate; border-spacing: 0px 0px; Border:Solid Black .5pt; width: 600px"><apex:outputField value="{!Work_Order__c.WorkOrderDate__c}"/></td>
</tr>
<tr>
<td Style="border-collapse: separate; border-spacing: 0px 0px; Border:Solid Black .5pt">Requested By</td>
<td Style="border-collapse: separate; border-spacing: 0px 0px; Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Name}"/></td>
</tr>
<tr>
<td Style="border-collapse: separate; border-spacing: 0px 0px; Border:Solid Black .5pt">Four Winds Case number</td>
<td Style="border-collapse: separate; border-spacing: 0px 0px; Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Case__c}"/></td>
</tr>
</table>
<br/>
<table Width="100%" Style="border:.5px solid blank;" cellspacing="0" >
<tr Style="background-color:grey">
<th colspan="2" Style="background-color:grey; Border:1px solid black; background-color:#cccccc"><b>Media Player Information</b></th>
</tr>
<tr>
<td Style="Border:Solid Black .5pt; width: 200px">Frontier Serial Number</td>
<td Style="Border:Solid Black .5pt; width: 600px"><apex:outputField value="{!Work_Order__c.Serial_Number_Frontier_Tag__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Player Model # if available</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Media_Player_Model__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Was F9 restore attempted</td>
<td Style="Border:Solid Black .5pt">
<apex:outputField value="{!Work_Order__c.Was_F9_restore_attempted__c}" rendered="{!IF(Work_Order__c.Was_F9_restore_attempted__c !=Null,true,false)}"/>
<apex:inputField value="{!Work_Order__c.Was_F9_restore_attempted__c}" rendered="{!IF(Work_Order__c.Was_F9_restore_attempted__c ==Null,true,false)}"/>
</td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Description of Problem</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Description_of_Problem__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Trouble Shooting Performed</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Trouble_Shooting_Performed__c}"/></td>
</tr>
</table>
<br/>
<table Width="100%" Style="border:.5px solid blank;" cellspacing="0" >
<tr Style="background-color:grey">
<th colspan="2" Style="background-color:grey; Border:1px solid black; background-color:#cccccc"><b>Customer Ship to Information</b></th>
</tr>
<tr>
<td Style="Border:Solid Black .5pt; width: 200px">Company</td>
<td Style="Border:Solid Black .5pt; width: 600px"><apex:outputField value="{!Work_Order__c.Name}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Contact</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Account__r.Name}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Address 1:</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Ship_To_Address_1__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Address 2:</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Ship_to_Address_2__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">City, State, Zip:</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Ship_To_City_State_Zip__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Contact Phone:</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Ship_to_Phone_Number__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Contact Email: </td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Ship_to_Email_Address__c}"/></td>
</tr>
</table>
<br/>
<table Width="100%" Style="border:.5px solid blank" cellspacing="0" >
<tr Style="background-color:grey">
<th colspan="2" Style="background-color:grey; Border:1px solid black; background-color:#cccccc">Shipping Method<br/>*If other than standard ground shipping we will need your shipping number*</th>
</tr>
<tr>
<td Style="Border:Solid Black .5pt; width: 200px">Customer Shipping Number</td>
<td Style="Border:Solid Black .5pt; width: 600px"><apex:outputField value="{!Work_Order__c.Customer_Shipping_Number__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Method of Shipment</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Method_of_Shipment__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Ship Via</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Ship_Via__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Other</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Other__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">List of Items to ship</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.List_of_Items_to_ship__c}"/></td>
</tr>
</table>
</center>
</apex:pageBlock>
</apex:form>
</apex:page>
<apex:page StandardController="Work_Order__c" >
<apex:form >
<apex:pageBlock >
<apex:pageBlockButtons >
<apex:commandButton action="{!URLFOR($Action.Work_Order__c.HotSwapFormInput)}" value="Edit"/>
<apex:commandButton Action="{!URLFOR($Action.Work_Order__c.Download_PDF)}" Value="Download PDF"/>
</apex:pageBlockButtons>
<center>
<table Width="100%" Style="border:.5px solid blank;" cellspacing="0">
<tr >
<th colspan="2" Style="background-color:grey; Border:1px solid black; background-color:#cccccc"><b>Request Information</b></th>
</tr>
<tr>
<td Style="border-collapse: separate;border-spacing: 0px 0px; Border:Solid Black .5pt; width: 200px">Requested Date</td>
<td Style="border-collapse: separate; border-spacing: 0px 0px; Border:Solid Black .5pt; width: 600px"><apex:outputField value="{!Work_Order__c.WorkOrderDate__c}"/></td>
</tr>
<tr>
<td Style="border-collapse: separate; border-spacing: 0px 0px; Border:Solid Black .5pt">Requested By</td>
<td Style="border-collapse: separate; border-spacing: 0px 0px; Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Name}"/></td>
</tr>
<tr>
<td Style="border-collapse: separate; border-spacing: 0px 0px; Border:Solid Black .5pt">Four Winds Case number</td>
<td Style="border-collapse: separate; border-spacing: 0px 0px; Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Case__c}"/></td>
</tr>
</table>
<br/>
<table Width="100%" Style="border:.5px solid blank;" cellspacing="0" >
<tr Style="background-color:grey">
<th colspan="2" Style="background-color:grey; Border:1px solid black; background-color:#cccccc"><b>Media Player Information</b></th>
</tr>
<tr>
<td Style="Border:Solid Black .5pt; width: 200px">Frontier Serial Number</td>
<td Style="Border:Solid Black .5pt; width: 600px"><apex:outputField value="{!Work_Order__c.Serial_Number_Frontier_Tag__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Player Model # if available</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Media_Player_Model__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Was F9 restore attempted</td>
<td Style="Border:Solid Black .5pt">
<apex:outputField value="{!Work_Order__c.Was_F9_restore_attempted__c}" rendered="{!IF(Work_Order__c.Was_F9_restore_attempted__c !=Null,true,false)}"/>
<apex:inputField value="{!Work_Order__c.Was_F9_restore_attempted__c}" rendered="{!IF(Work_Order__c.Was_F9_restore_attempted__c ==Null,true,false)}"/>
</td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Description of Problem</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Description_of_Problem__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Trouble Shooting Performed</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Trouble_Shooting_Performed__c}"/></td>
</tr>
</table>
<br/>
<table Width="100%" Style="border:.5px solid blank;" cellspacing="0" >
<tr Style="background-color:grey">
<th colspan="2" Style="background-color:grey; Border:1px solid black; background-color:#cccccc"><b>Customer Ship to Information</b></th>
</tr>
<tr>
<td Style="Border:Solid Black .5pt; width: 200px">Company</td>
<td Style="Border:Solid Black .5pt; width: 600px"><apex:outputField value="{!Work_Order__c.Name}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Contact</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Account__r.Name}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Address 1:</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Ship_To_Address_1__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Address 2:</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Ship_to_Address_2__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">City, State, Zip:</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Ship_To_City_State_Zip__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Contact Phone:</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Ship_to_Phone_Number__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Contact Email: </td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Ship_to_Email_Address__c}"/></td>
</tr>
</table>
<br/>
<table Width="100%" Style="border:.5px solid blank" cellspacing="0" >
<tr Style="background-color:grey">
<th colspan="2" Style="background-color:grey; Border:1px solid black; background-color:#cccccc">Shipping Method<br/>*If other than standard ground shipping we will need your shipping number*</th>
</tr>
<tr>
<td Style="Border:Solid Black .5pt; width: 200px">Customer Shipping Number</td>
<td Style="Border:Solid Black .5pt; width: 600px"><apex:outputField value="{!Work_Order__c.Customer_Shipping_Number__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Method of Shipment</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Method_of_Shipment__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Ship Via</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Ship_Via__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">Other</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.Other__c}"/></td>
</tr>
<tr>
<td Style="Border:Solid Black .5pt">List of Items to ship</td>
<td Style="Border:Solid Black .5pt"><apex:outputField value="{!Work_Order__c.List_of_Items_to_ship__c}"/></td>
</tr>
</table>
</center>
</apex:pageBlock>
</apex:form>
</apex:page>
- Andrew Aldis
- July 12, 2016
- Like
- 0
Visual Force picklist with other records
I have 3 objects Scoping which is a parent object for both Packages and Sign Instances, I created a junction object so users could relate sign isntances to the appropriate packages. Both Sign Instances and packages can be related to multiple records in both objects. I then created a visualforce page which is inserted into the Packages object that will automatically create and display the junction records. I want to crate a picklist to pull in all sign instances related to the scoping object so users do not have to use a look up field, but I cannot find an example of this scenario.
Apex Class
public class PackageSignInstanceJunctionController {
// Constructor
public PackageSignInstanceJunctionController(ApexPages.StandardController controller)
//master
{
this.proj = (Package__c)controller.getRecord();
// child
this.junction = [ SELECT
t.Package__c, t.Sign_Instance__c, t.Name, t.Id
FROM Package_Sign_Instance_Junction__c t
WHERE
t.Package__c = :proj.id
ORDER BY t.CreatedDate Desc];
}
//Picklist Options
// Insert new Staff junction
public pagereference insertmethod()
{
Package_Sign_Instance_Junction__c cc= new Package_Sign_Instance_Junction__c();
cc.Package__c = proj.id;
insert cc;
return null;
}
public Package_Sign_Instance_Junction__c[] getjunction() {
return this.junction;
}
// Action Method called from page button
public pagereference saveChanges() {
upsert this.junction;
pageRef.setRedirect(true);
return pageRef;
}
// Action Method called from page link
public pagereference newjunction() {
Package_Sign_Instance_Junction__c d = new Package_Sign_Instance_Junction__c();
d.Package__c = this.proj.id;
junction.add( d );
getjunction();
return null;
}
public pagereference DeleteAccount()
{
// if for any reason we are missing the reference
if (SelectedAccountId == null)
{
return null;
}
// find the account record within the collection
Package_Sign_Instance_Junction__c tobeDeleted = null;
for(Package_Sign_Instance_Junction__c a : this.junction)
if (a.Id == SelectedAccountId)
{
tobeDeleted = a;
break;
}
//if account record found delete it
if (tobeDeleted != null)
{
Delete tobeDeleted;
}
pageRef.setRedirect(true);
return pageRef;
}
// class variables
PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
Package__c proj;
Package_Sign_Instance_Junction__c[] junction;
Sign_Instance__c[] sign;
public string SelectedAccountId { get; set; }
}
Visual Force Page
<apex:page standardController="Package__c" extensions="PackageSignInstanceJunctionController">
<apex:messages />
<apex:form >
<apex:PageBlock id="happy" >
<apex:pageBlockButtons >
<apex:commandLink value="Save" action="{!savechanges}" rerender="main" styleClass="btn" style="text-decoration:none;padding:4px;"/>
<apex:commandButton action="{!newjunction}" value="New" />
</apex:pageBlockButtons>
<apex:actionStatus id="ajaxStatus" startText="Updating schedules...">
<apex:facet name="stop">
<apex:outputPanel id="main" >
<table>
<tr>
<td style="width:50px; margin-right:50px"><b>Sign</b></td>
</tr>
<apex:repeat value="{!junction}" var="a">
<tr>
<td><apex:inputField value="{!a.Sign_Instance__c}" style="width:200px" rendered="{!IF(a.Sign_Instance__c =null,true,false)}"/>
<apex:OutputField value="{!a.Sign_Instance__c}" style="width:200px" rendered="{!IF(a.Sign_Instance__c !=null,true,false)}"/></td>
<td><a href="javascript:if (window.confirm('Are you sure?')) DeleteAccount('{!a.Id}');" style="font-weight:bold">Del</a></td>
</tr>
</apex:repeat>
</table>
</apex:outputPanel>
</apex:facet>
</apex:actionStatus>
<apex:actionFunction action="{!DeleteAccount}" name="DeleteAccount" reRender="main" >
<apex:param name="accountid" value="" assignTo="{!SelectedAccountId}"/>
</apex:actionFunction>
</apex:pageblock>
</apex:form>
</apex:page>
Apex Class
public class PackageSignInstanceJunctionController {
// Constructor
public PackageSignInstanceJunctionController(ApexPages.StandardController controller)
//master
{
this.proj = (Package__c)controller.getRecord();
// child
this.junction = [ SELECT
t.Package__c, t.Sign_Instance__c, t.Name, t.Id
FROM Package_Sign_Instance_Junction__c t
WHERE
t.Package__c = :proj.id
ORDER BY t.CreatedDate Desc];
}
//Picklist Options
// Insert new Staff junction
public pagereference insertmethod()
{
Package_Sign_Instance_Junction__c cc= new Package_Sign_Instance_Junction__c();
cc.Package__c = proj.id;
insert cc;
return null;
}
public Package_Sign_Instance_Junction__c[] getjunction() {
return this.junction;
}
// Action Method called from page button
public pagereference saveChanges() {
upsert this.junction;
pageRef.setRedirect(true);
return pageRef;
}
// Action Method called from page link
public pagereference newjunction() {
Package_Sign_Instance_Junction__c d = new Package_Sign_Instance_Junction__c();
d.Package__c = this.proj.id;
junction.add( d );
getjunction();
return null;
}
public pagereference DeleteAccount()
{
// if for any reason we are missing the reference
if (SelectedAccountId == null)
{
return null;
}
// find the account record within the collection
Package_Sign_Instance_Junction__c tobeDeleted = null;
for(Package_Sign_Instance_Junction__c a : this.junction)
if (a.Id == SelectedAccountId)
{
tobeDeleted = a;
break;
}
//if account record found delete it
if (tobeDeleted != null)
{
Delete tobeDeleted;
}
pageRef.setRedirect(true);
return pageRef;
}
// class variables
PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
Package__c proj;
Package_Sign_Instance_Junction__c[] junction;
Sign_Instance__c[] sign;
public string SelectedAccountId { get; set; }
}
Visual Force Page
<apex:page standardController="Package__c" extensions="PackageSignInstanceJunctionController">
<apex:messages />
<apex:form >
<apex:PageBlock id="happy" >
<apex:pageBlockButtons >
<apex:commandLink value="Save" action="{!savechanges}" rerender="main" styleClass="btn" style="text-decoration:none;padding:4px;"/>
<apex:commandButton action="{!newjunction}" value="New" />
</apex:pageBlockButtons>
<apex:actionStatus id="ajaxStatus" startText="Updating schedules...">
<apex:facet name="stop">
<apex:outputPanel id="main" >
<table>
<tr>
<td style="width:50px; margin-right:50px"><b>Sign</b></td>
</tr>
<apex:repeat value="{!junction}" var="a">
<tr>
<td><apex:inputField value="{!a.Sign_Instance__c}" style="width:200px" rendered="{!IF(a.Sign_Instance__c =null,true,false)}"/>
<apex:OutputField value="{!a.Sign_Instance__c}" style="width:200px" rendered="{!IF(a.Sign_Instance__c !=null,true,false)}"/></td>
<td><a href="javascript:if (window.confirm('Are you sure?')) DeleteAccount('{!a.Id}');" style="font-weight:bold">Del</a></td>
</tr>
</apex:repeat>
</table>
</apex:outputPanel>
</apex:facet>
</apex:actionStatus>
<apex:actionFunction action="{!DeleteAccount}" name="DeleteAccount" reRender="main" >
<apex:param name="accountid" value="" assignTo="{!SelectedAccountId}"/>
</apex:actionFunction>
</apex:pageblock>
</apex:form>
</apex:page>
- Andrew Aldis
- June 09, 2016
- Like
- 0
Add chart to VF page
I am trying to add a chart to a VF page with a standard controller. The only examples of VF page charts work with controllers so when I try to add my chart as a extension I get he following error. 'Unknown construction 'BurnReportPieChartController.BurnReportPieChartController(ApexPages.StandardController controller)' how can I add a chart to my page? My controller and page are below.
COntroller
public class BurnReportPieChartController {
public List<PieWedgeData> getPieData()
{
List<PieWedgeData> data = new List<PieWedgeData>();
List<SFDC_Project__c> install = new List<SFDC_Project__c>();
String sql = 'SELECT id, Logged_Billable_Time_All_Roles__c, Remaining_All_Budgeted_Hours__c FROM SFDC_Project__c';
install = Database.Query(sql);
for(SFDC_Project__c temp:install)
{
data.add(new PieWedgeData('Logged Billable Hours',temp.Logged_Billable_Time_All_Roles__c));
data.add(new PieWedgeData('Remaining Billable Hours',temp.Logged_Billable_Time_All_Roles__c));
}
return data;
}
// Wrapper class
public class PieWedgeData
{
public String name { get; set; }
public Decimal data { get; set; }
public PieWedgeData(String name, Decimal data)
{
this.name = name;
this.data = data;
}
}
}
VF page
<apex:page standardController="SFDC_Project__c" extensions="BurnReportPieChartController" DOCType="HTML-5.0" RenderAS="PDF">
<apex:sectionHeader title="Installation" subtitle="{!SFDC_Project__c.Name}"/>
<apex:pageBlock >
<apex:pageBlockSection title="General Project Information" columns="1" >
<apex:outputField title="Account" value="{!SFDC_Project__c.Account__c}"/>
<apex:outputField title="Installation Number" value="{!SFDC_Project__c.Name}" />
<apex:outputField title="FWi Project Manager" value="{!SFDC_Project__c.SFDC_Project_Manager__c}" />
</apex:pageBlockSection>
<br/><br/>
<Table Class="T">
<tr Class="R1">
<td Class="C1" style='width:350px; padding-right:40px'></td>
<td Class="C2" >Budgeted</td>
<td Class="C2">Logged</td>
<td Class="C2">Remaining</td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Total</td>
<td Class="C2" style='width:150px; padding-right:15px'><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Hours__c}"/></td>
<td Class="C2" style='width:150px; padding-right:15px'><apex:outputField Value="{!SFDC_Project__c.Logged_Billable_Time_All_Roles__c}"/></td>
<td Class="C2" style='width:150px; padding-right:15px'><apex:outputField value="{!SFDC_Project__c.Remaining_All_Budgeted_Hours__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-ASD</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_ASD__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_ASD__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Hours_ASD__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Creative</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Creative__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Creative__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Creative__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Custom Development</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Custom_Dev__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Custom_Dev__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Custom_Dev__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Project Management</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Project_Mgmt__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_PM__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_PM__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Quality Assurance</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Hours_Time_QA__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_QA__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_QA__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Sign Architecture 1</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Signage_Arch_1__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Sign_Arch_1__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Sign_Arch_1__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Sign Architecture 2</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Signage_Arch_2__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Sign_Arch_2__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Sign_Arch_2__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-System Engineer</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Systems_Engineer__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Systems_Engineer__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Systems_Engineer__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Training</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Training__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Training__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Training__c}"/></td>
</tr>
</Table>
<apex:pageblock title="Logged vs. Remaining Billable Hours" >
<apex:chart height="250" width="350" data="{!pieData}">
<apex:pieSeries tips="true" dataField="data" labelField="name"/>
<apex:legend position="bottom"/>
</apex:chart>
</apex:pageblock>
</apex:pageBlock>
</apex:page>
COntroller
public class BurnReportPieChartController {
public List<PieWedgeData> getPieData()
{
List<PieWedgeData> data = new List<PieWedgeData>();
List<SFDC_Project__c> install = new List<SFDC_Project__c>();
String sql = 'SELECT id, Logged_Billable_Time_All_Roles__c, Remaining_All_Budgeted_Hours__c FROM SFDC_Project__c';
install = Database.Query(sql);
for(SFDC_Project__c temp:install)
{
data.add(new PieWedgeData('Logged Billable Hours',temp.Logged_Billable_Time_All_Roles__c));
data.add(new PieWedgeData('Remaining Billable Hours',temp.Logged_Billable_Time_All_Roles__c));
}
return data;
}
// Wrapper class
public class PieWedgeData
{
public String name { get; set; }
public Decimal data { get; set; }
public PieWedgeData(String name, Decimal data)
{
this.name = name;
this.data = data;
}
}
}
VF page
<apex:page standardController="SFDC_Project__c" extensions="BurnReportPieChartController" DOCType="HTML-5.0" RenderAS="PDF">
<apex:sectionHeader title="Installation" subtitle="{!SFDC_Project__c.Name}"/>
<apex:pageBlock >
<apex:pageBlockSection title="General Project Information" columns="1" >
<apex:outputField title="Account" value="{!SFDC_Project__c.Account__c}"/>
<apex:outputField title="Installation Number" value="{!SFDC_Project__c.Name}" />
<apex:outputField title="FWi Project Manager" value="{!SFDC_Project__c.SFDC_Project_Manager__c}" />
</apex:pageBlockSection>
<br/><br/>
<Table Class="T">
<tr Class="R1">
<td Class="C1" style='width:350px; padding-right:40px'></td>
<td Class="C2" >Budgeted</td>
<td Class="C2">Logged</td>
<td Class="C2">Remaining</td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Total</td>
<td Class="C2" style='width:150px; padding-right:15px'><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Hours__c}"/></td>
<td Class="C2" style='width:150px; padding-right:15px'><apex:outputField Value="{!SFDC_Project__c.Logged_Billable_Time_All_Roles__c}"/></td>
<td Class="C2" style='width:150px; padding-right:15px'><apex:outputField value="{!SFDC_Project__c.Remaining_All_Budgeted_Hours__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-ASD</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_ASD__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_ASD__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Hours_ASD__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Creative</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Creative__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Creative__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Creative__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Custom Development</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Custom_Dev__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Custom_Dev__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Custom_Dev__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Project Management</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Project_Mgmt__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_PM__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_PM__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Quality Assurance</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Hours_Time_QA__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_QA__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_QA__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Sign Architecture 1</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Signage_Arch_1__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Sign_Arch_1__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Sign_Arch_1__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Sign Architecture 2</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Signage_Arch_2__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Sign_Arch_2__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Sign_Arch_2__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-System Engineer</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Systems_Engineer__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Systems_Engineer__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Systems_Engineer__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Training</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Training__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Training__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Training__c}"/></td>
</tr>
</Table>
<apex:pageblock title="Logged vs. Remaining Billable Hours" >
<apex:chart height="250" width="350" data="{!pieData}">
<apex:pieSeries tips="true" dataField="data" labelField="name"/>
<apex:legend position="bottom"/>
</apex:chart>
</apex:pageblock>
</apex:pageBlock>
</apex:page>
- Andrew Aldis
- May 03, 2016
- Like
- 1
SOQL Query on Activity History
I need to pull a query from SF that pulls in the number of activities related to accounts as a count of the number of records and group it by the account owner. The activity history is a subquery and will not let me aggregate the data. I am also not able to pull the query directly from activities because it says it in not queryable. How can I get this to work?
Select
(SELECT OWNER.Name
FROM ActivityHistories
where (ActivityType = 'Discovery Demo' AND ActivityDate=This_month) OR (ActivityType = 'Discovery Interview' AND ActivityDate=This_Month )
)
From Account
Where Target_Account__c = True OR Target_Prospect__c = True
Select
(SELECT OWNER.Name
FROM ActivityHistories
where (ActivityType = 'Discovery Demo' AND ActivityDate=This_month) OR (ActivityType = 'Discovery Interview' AND ActivityDate=This_Month )
)
From Account
Where Target_Account__c = True OR Target_Prospect__c = True
- Andrew Aldis
- February 04, 2016
- Like
- 0
How can I query activity history
I am trying to write a query that pulls a list of account Owners and their activity history then aggregates the activity histry using count(), but it will not let me count on a sub query. I am also not able to query the activity history without querying the account. Is there a way around either of these restrictions?
Select
(SELECT OWNER.Name
FROM ActivityHistories
where (ActivityType = 'Discovery Demo' ) OR (ActivityType = 'Discovery Interview')
)
From Account
Where Target_Account__c = True OR Target_Prospect__c = True
Select
(SELECT OWNER.Name
FROM ActivityHistories
where (ActivityType = 'Discovery Demo' ) OR (ActivityType = 'Discovery Interview')
)
From Account
Where Target_Account__c = True OR Target_Prospect__c = True
- Andrew Aldis
- February 04, 2016
- Like
- 0
Apex Detail
I built an object with about 8 child objects. I would like to add a button that renders the page as a PDF, can I use APEX:Detail to render the parent object as well as child objects as PDF's on the page.
- Andrew Aldis
- January 22, 2016
- Like
- 0
How can I add white space inbetween an outputfields field label and value?
I am trying to create a VF Page to render as a PDF, but am having trouble getting it to format. I have an output Field <apex:outputField Value="{!Client_Workbook__c.Name}"/> but when I generate the PDF there is no space inbetween the label and the value.
It shows up like this "Client Workbook NameCWB-0001" The label is Client Workbook Name and the value is CWB-0001, I want it to appear with a space in between the two like "Client Workbook NameCWB-0001". I have tried using a label with a space added in the parenthesis like this <apex:outputField Value="{!Client_Workbook__c.Name}" label="Client Workbook Name: "/><br/> but it does the same thing. How can I get it to properly space between the value and the label?
It shows up like this "Client Workbook NameCWB-0001" The label is Client Workbook Name and the value is CWB-0001, I want it to appear with a space in between the two like "Client Workbook NameCWB-0001". I have tried using a label with a space added in the parenthesis like this <apex:outputField Value="{!Client_Workbook__c.Name}" label="Client Workbook Name: "/><br/> but it does the same thing. How can I get it to properly space between the value and the label?
- Andrew Aldis
- January 22, 2016
- Like
- 0
Is there a way to Query a Report Chart or Dashboard Component URL so we can display it?
My company uses an internal signage network that lets us display SFDC information using SOQL. Basically our signs use SOQL to pull information onto our signs where it can be displayed. Is there a way to pull a Report Chart or Dashboard Component using SOQL so we can display that on the sign?
- Andrew Aldis
- December 31, 2016
- Like
- 0
Calculations in SOQL
I am trying to write a soql query that divides the sum value of the amount on an opportunity with the max value of a sales commitment on the opportunity. I need the calculation to be done in the query if at all possible. I basically to pull the sum from one field, and divide it by the max of another. The query I am using is below.
Select Owner.UserRole.Name, SUM(Total_Net_Software_Reporting__c),Max(Owner.Director_Monthly_Commit_Software__c) ,SUM(Total_Net_Software_Reporting__c)/Max(Owner.Director_Monthly_Commit_Software__c) as TNS_Commit_To_Actual
FROM Opportunity
Where Owner.Sales_Rep__c=True AND CloseDate=This_Month
Group By Owner.UserRole.Name
Select Owner.UserRole.Name, SUM(Total_Net_Software_Reporting__c),Max(Owner.Director_Monthly_Commit_Software__c) ,SUM(Total_Net_Software_Reporting__c)/Max(Owner.Director_Monthly_Commit_Software__c) as TNS_Commit_To_Actual
FROM Opportunity
Where Owner.Sales_Rep__c=True AND CloseDate=This_Month
Group By Owner.UserRole.Name
- Andrew Aldis
- November 23, 2015
- Like
- 0
Add chart to VF page
I am trying to add a chart to a VF page with a standard controller. The only examples of VF page charts work with controllers so when I try to add my chart as a extension I get he following error. 'Unknown construction 'BurnReportPieChartController.BurnReportPieChartController(ApexPages.StandardController controller)' how can I add a chart to my page? My controller and page are below.
COntroller
public class BurnReportPieChartController {
public List<PieWedgeData> getPieData()
{
List<PieWedgeData> data = new List<PieWedgeData>();
List<SFDC_Project__c> install = new List<SFDC_Project__c>();
String sql = 'SELECT id, Logged_Billable_Time_All_Roles__c, Remaining_All_Budgeted_Hours__c FROM SFDC_Project__c';
install = Database.Query(sql);
for(SFDC_Project__c temp:install)
{
data.add(new PieWedgeData('Logged Billable Hours',temp.Logged_Billable_Time_All_Roles__c));
data.add(new PieWedgeData('Remaining Billable Hours',temp.Logged_Billable_Time_All_Roles__c));
}
return data;
}
// Wrapper class
public class PieWedgeData
{
public String name { get; set; }
public Decimal data { get; set; }
public PieWedgeData(String name, Decimal data)
{
this.name = name;
this.data = data;
}
}
}
VF page
<apex:page standardController="SFDC_Project__c" extensions="BurnReportPieChartController" DOCType="HTML-5.0" RenderAS="PDF">
<apex:sectionHeader title="Installation" subtitle="{!SFDC_Project__c.Name}"/>
<apex:pageBlock >
<apex:pageBlockSection title="General Project Information" columns="1" >
<apex:outputField title="Account" value="{!SFDC_Project__c.Account__c}"/>
<apex:outputField title="Installation Number" value="{!SFDC_Project__c.Name}" />
<apex:outputField title="FWi Project Manager" value="{!SFDC_Project__c.SFDC_Project_Manager__c}" />
</apex:pageBlockSection>
<br/><br/>
<Table Class="T">
<tr Class="R1">
<td Class="C1" style='width:350px; padding-right:40px'></td>
<td Class="C2" >Budgeted</td>
<td Class="C2">Logged</td>
<td Class="C2">Remaining</td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Total</td>
<td Class="C2" style='width:150px; padding-right:15px'><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Hours__c}"/></td>
<td Class="C2" style='width:150px; padding-right:15px'><apex:outputField Value="{!SFDC_Project__c.Logged_Billable_Time_All_Roles__c}"/></td>
<td Class="C2" style='width:150px; padding-right:15px'><apex:outputField value="{!SFDC_Project__c.Remaining_All_Budgeted_Hours__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-ASD</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_ASD__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_ASD__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Hours_ASD__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Creative</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Creative__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Creative__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Creative__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Custom Development</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Custom_Dev__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Custom_Dev__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Custom_Dev__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Project Management</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Project_Mgmt__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_PM__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_PM__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Quality Assurance</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Hours_Time_QA__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_QA__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_QA__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Sign Architecture 1</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Signage_Arch_1__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Sign_Arch_1__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Sign_Arch_1__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Sign Architecture 2</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Signage_Arch_2__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Sign_Arch_2__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Sign_Arch_2__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-System Engineer</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Systems_Engineer__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Systems_Engineer__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Systems_Engineer__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Training</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Training__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Training__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Training__c}"/></td>
</tr>
</Table>
<apex:pageblock title="Logged vs. Remaining Billable Hours" >
<apex:chart height="250" width="350" data="{!pieData}">
<apex:pieSeries tips="true" dataField="data" labelField="name"/>
<apex:legend position="bottom"/>
</apex:chart>
</apex:pageblock>
</apex:pageBlock>
</apex:page>
COntroller
public class BurnReportPieChartController {
public List<PieWedgeData> getPieData()
{
List<PieWedgeData> data = new List<PieWedgeData>();
List<SFDC_Project__c> install = new List<SFDC_Project__c>();
String sql = 'SELECT id, Logged_Billable_Time_All_Roles__c, Remaining_All_Budgeted_Hours__c FROM SFDC_Project__c';
install = Database.Query(sql);
for(SFDC_Project__c temp:install)
{
data.add(new PieWedgeData('Logged Billable Hours',temp.Logged_Billable_Time_All_Roles__c));
data.add(new PieWedgeData('Remaining Billable Hours',temp.Logged_Billable_Time_All_Roles__c));
}
return data;
}
// Wrapper class
public class PieWedgeData
{
public String name { get; set; }
public Decimal data { get; set; }
public PieWedgeData(String name, Decimal data)
{
this.name = name;
this.data = data;
}
}
}
VF page
<apex:page standardController="SFDC_Project__c" extensions="BurnReportPieChartController" DOCType="HTML-5.0" RenderAS="PDF">
<apex:sectionHeader title="Installation" subtitle="{!SFDC_Project__c.Name}"/>
<apex:pageBlock >
<apex:pageBlockSection title="General Project Information" columns="1" >
<apex:outputField title="Account" value="{!SFDC_Project__c.Account__c}"/>
<apex:outputField title="Installation Number" value="{!SFDC_Project__c.Name}" />
<apex:outputField title="FWi Project Manager" value="{!SFDC_Project__c.SFDC_Project_Manager__c}" />
</apex:pageBlockSection>
<br/><br/>
<Table Class="T">
<tr Class="R1">
<td Class="C1" style='width:350px; padding-right:40px'></td>
<td Class="C2" >Budgeted</td>
<td Class="C2">Logged</td>
<td Class="C2">Remaining</td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Total</td>
<td Class="C2" style='width:150px; padding-right:15px'><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Hours__c}"/></td>
<td Class="C2" style='width:150px; padding-right:15px'><apex:outputField Value="{!SFDC_Project__c.Logged_Billable_Time_All_Roles__c}"/></td>
<td Class="C2" style='width:150px; padding-right:15px'><apex:outputField value="{!SFDC_Project__c.Remaining_All_Budgeted_Hours__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-ASD</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_ASD__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_ASD__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Hours_ASD__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Creative</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Creative__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Creative__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Creative__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Custom Development</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Custom_Dev__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Custom_Dev__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Custom_Dev__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Project Management</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Project_Mgmt__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_PM__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_PM__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Quality Assurance</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Hours_Time_QA__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_QA__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_QA__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Sign Architecture 1</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Signage_Arch_1__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Sign_Arch_1__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Sign_Arch_1__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Sign Architecture 2</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Signage_Arch_2__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Sign_Arch_2__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Sign_Arch_2__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-System Engineer</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Systems_Engineer__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Systems_Engineer__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Systems_Engineer__c}"/></td>
</tr>
<tr Class="R">
<td Class="C1">Billable Time-Training</td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Budgeted_Billable_Time_Training__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Logged_Billable_Time_Training__c}"/></td>
<td Class="C2"><apex:outputField value="{!SFDC_Project__c.Remaining_Billable_Time_Training__c}"/></td>
</tr>
</Table>
<apex:pageblock title="Logged vs. Remaining Billable Hours" >
<apex:chart height="250" width="350" data="{!pieData}">
<apex:pieSeries tips="true" dataField="data" labelField="name"/>
<apex:legend position="bottom"/>
</apex:chart>
</apex:pageblock>
</apex:pageBlock>
</apex:page>
- Andrew Aldis
- May 03, 2016
- Like
- 1
Test Class System.QueryException List has no rows for assignment to SObject
I am trying to write a test class for for the class below, which I had deployed to our production before, I made some little modifications ot the class to query a list of related items and put them into a select option list for a Picklist field on a VF page. I thought it was a small change but it seems to have completely messed up my test class and I am not sure why. I get the error: System.QueryException: List has no rows for assignment to SObject. I'd appreciate any assistance.
APEX CLASS
public class RiskEditPage {
Risk__c risk;
PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
public List<Work_Order__c> woTemp = new List<Work_Order__c>();
public List<SelectOption> woList {get;set;}
public RiskEditPage(apexPages.StandardController controller){
risk = [Select Name, Assign_To__c, OpId__c, Risk_Mitigation__r.OpId__c, FWI_Work_Order__c, Consequence_of_Failure__c, Covered_in_SOW_Hrs__c,
Custom_Development_Required__c, Description__c, Function__c, Risk_Mitigation__c, Risk_of_Failure__c,
Risk_Mitigation__r.Name, Signoff__c, Signoff2__c, Status__c, Strategy_to_Mitigate_Risk__c, Triggering_Action__c, Type__c,
User_Impact__c, Create_Task__c, Risk_of_Failure_Score__c from Risk__c
where Id = :ApexPages.currentPage().getparameters().get('id')];
woTemp = [Select s.Name, s.Id, s.Status__c, s.Type__c From Work_Order__c s where Opportunity__c = :risk.Risk_Mitigation__r.OpId__c Order By Name Asc];
woList = new List<SelectOption>();
for(Work_Order__c temp : woTemp)
{
woList.add(new SelectOption(temp.Id, temp.Name+': '+temp.Type__c));
}
}
public PageReference saveRisk()
{
update risk;
PageReference pageref = new PageReference('/'+risk.Risk_Mitigation__c);
pageRef.setRedirect(true);
return pageRef;
}
public PageReference saveNew()
{
upsert risk;
PageReference pageref = new PageReference('/apex/RiskNewPage?retURL='+risk.Risk_Mitigation__c+'&CF00N4D000000bXd5='+risk.Risk_Mitigation__r.Name+'kid=aDS4D0000004CAB&CF00N4D000000bXd5_lkid='+risk.Risk_Mitigation__c+'&retURL='+risk.Risk_Mitigation__c+'&scontrolCaching=1&sfdc.override=1');
pageRef.setRedirect(true);
return pageRef;
}
}
TEST CLASS
@istest(seealldata=true)
public class RiskEditPageTest {
static Risk_Mitigation__c setupServicePartner() {
Risk_Mitigation__c partner = new Risk_Mitigation__c();
partner.Name = 'test';
partner.Client_Workbook__c = 'a9f34000000TN1F';
insert partner;
return partner;
}
static Risk__c setupServiceLineItem(final Risk_Mitigation__c partner) {
Risk__c lineItem = new Risk__c();
lineItem.Risk_Mitigation__c = partner.Id;
insert lineItem;
return lineItem;
}
static testmethod void deliverablesCnt_Should_SaveLineItemChanges() {
//Given
Risk_Mitigation__c aBasicPartner = setupServicePartner();
Risk__c unsavedLineItem = new Risk__c();
unsavedLineItem.Risk_Mitigation__c = aBasicPartner.Id;
//when
Test.startTest();
Test.setCurrentPage(Page.RiskEditPage);
RiskEditPage deliverablesCnt = new RiskEditPage(new ApexPages.StandardController(unsavedLineItem));
//deliverablesCnt.getrisk().add(unsavedLineItem);
PageReference pageRef = deliverablesCnt.saveRisk();
Test.stopTest();
//then
List<Risk__c> associatedLineItems = [
SELECT Risk_Mitigation__c
FROM Risk__c
WHERE Risk_Mitigation__c = :aBasicPartner.Id
];
System.assertEquals(1, associatedLineItems.size(), 'The unsaved service partner line item should have been saved');
System.assertEquals(true, pageRef.getRedirect(), 'Page should redirect');
}
static testmethod void deliverablesCnt_Should_SaveNewLineItemChanges() {
//Given
Risk_Mitigation__c aBasicPartner = setupServicePartner();
Risk__c unsavedLineItem = new Risk__c();
unsavedLineItem.Risk_Mitigation__c = aBasicPartner.Id;
//when
Test.startTest();
Test.setCurrentPage(Page.RiskEditPage);
RiskEditPage deliverablesCnt = new RiskEditPage(new ApexPages.StandardController(unsavedLineItem));
//deliverablesCnt.getrisk().add(unsavedLineItem);
PageReference pageRef = deliverablesCnt.saveNew();
Test.stopTest();
//then
List<Risk__c> associatedLineItems = [
SELECT Risk_Mitigation__c
FROM Risk__c
WHERE Risk_Mitigation__c = :aBasicPartner.Id
];
System.assertEquals(1, associatedLineItems.size(), 'The unsaved service partner line item should have been saved');
System.assertEquals(true, pageRef.getRedirect(), 'Page should redirect');
}
}
APEX CLASS
public class RiskEditPage {
Risk__c risk;
PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
public List<Work_Order__c> woTemp = new List<Work_Order__c>();
public List<SelectOption> woList {get;set;}
public RiskEditPage(apexPages.StandardController controller){
risk = [Select Name, Assign_To__c, OpId__c, Risk_Mitigation__r.OpId__c, FWI_Work_Order__c, Consequence_of_Failure__c, Covered_in_SOW_Hrs__c,
Custom_Development_Required__c, Description__c, Function__c, Risk_Mitigation__c, Risk_of_Failure__c,
Risk_Mitigation__r.Name, Signoff__c, Signoff2__c, Status__c, Strategy_to_Mitigate_Risk__c, Triggering_Action__c, Type__c,
User_Impact__c, Create_Task__c, Risk_of_Failure_Score__c from Risk__c
where Id = :ApexPages.currentPage().getparameters().get('id')];
woTemp = [Select s.Name, s.Id, s.Status__c, s.Type__c From Work_Order__c s where Opportunity__c = :risk.Risk_Mitigation__r.OpId__c Order By Name Asc];
woList = new List<SelectOption>();
for(Work_Order__c temp : woTemp)
{
woList.add(new SelectOption(temp.Id, temp.Name+': '+temp.Type__c));
}
}
public PageReference saveRisk()
{
update risk;
PageReference pageref = new PageReference('/'+risk.Risk_Mitigation__c);
pageRef.setRedirect(true);
return pageRef;
}
public PageReference saveNew()
{
upsert risk;
PageReference pageref = new PageReference('/apex/RiskNewPage?retURL='+risk.Risk_Mitigation__c+'&CF00N4D000000bXd5='+risk.Risk_Mitigation__r.Name+'kid=aDS4D0000004CAB&CF00N4D000000bXd5_lkid='+risk.Risk_Mitigation__c+'&retURL='+risk.Risk_Mitigation__c+'&scontrolCaching=1&sfdc.override=1');
pageRef.setRedirect(true);
return pageRef;
}
}
TEST CLASS
@istest(seealldata=true)
public class RiskEditPageTest {
static Risk_Mitigation__c setupServicePartner() {
Risk_Mitigation__c partner = new Risk_Mitigation__c();
partner.Name = 'test';
partner.Client_Workbook__c = 'a9f34000000TN1F';
insert partner;
return partner;
}
static Risk__c setupServiceLineItem(final Risk_Mitigation__c partner) {
Risk__c lineItem = new Risk__c();
lineItem.Risk_Mitigation__c = partner.Id;
insert lineItem;
return lineItem;
}
static testmethod void deliverablesCnt_Should_SaveLineItemChanges() {
//Given
Risk_Mitigation__c aBasicPartner = setupServicePartner();
Risk__c unsavedLineItem = new Risk__c();
unsavedLineItem.Risk_Mitigation__c = aBasicPartner.Id;
//when
Test.startTest();
Test.setCurrentPage(Page.RiskEditPage);
RiskEditPage deliverablesCnt = new RiskEditPage(new ApexPages.StandardController(unsavedLineItem));
//deliverablesCnt.getrisk().add(unsavedLineItem);
PageReference pageRef = deliverablesCnt.saveRisk();
Test.stopTest();
//then
List<Risk__c> associatedLineItems = [
SELECT Risk_Mitigation__c
FROM Risk__c
WHERE Risk_Mitigation__c = :aBasicPartner.Id
];
System.assertEquals(1, associatedLineItems.size(), 'The unsaved service partner line item should have been saved');
System.assertEquals(true, pageRef.getRedirect(), 'Page should redirect');
}
static testmethod void deliverablesCnt_Should_SaveNewLineItemChanges() {
//Given
Risk_Mitigation__c aBasicPartner = setupServicePartner();
Risk__c unsavedLineItem = new Risk__c();
unsavedLineItem.Risk_Mitigation__c = aBasicPartner.Id;
//when
Test.startTest();
Test.setCurrentPage(Page.RiskEditPage);
RiskEditPage deliverablesCnt = new RiskEditPage(new ApexPages.StandardController(unsavedLineItem));
//deliverablesCnt.getrisk().add(unsavedLineItem);
PageReference pageRef = deliverablesCnt.saveNew();
Test.stopTest();
//then
List<Risk__c> associatedLineItems = [
SELECT Risk_Mitigation__c
FROM Risk__c
WHERE Risk_Mitigation__c = :aBasicPartner.Id
];
System.assertEquals(1, associatedLineItems.size(), 'The unsaved service partner line item should have been saved');
System.assertEquals(true, pageRef.getRedirect(), 'Page should redirect');
}
}
- Andrew Aldis
- July 24, 2017
- Like
- 0
Convert a string variable to a Id in a test class.
I wrote a trigger that parses values from the Description field on our case object. The purpose is to parse out values from our internal monitoring service to update fields and the appropriate accounts. The parsing works and the trigger has worked consistantly in our sandbox but I cannot write a test class that passes. I keep getting an the following error: "System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, RmmEmailCaseUpdate: execution of AfterInsert
caused by: System.StringException: Invalid id:
Trigger.RmmEmailCaseUpdate: line 51, column 1: []"
The account I am using in the string is correct and always sets the account when I use the trigger in Sandbox but does not work when I write the test class. My class and test class are below.
trigger RmmEmailCaseUpdate on Case (after insert) {
if (trigger.isAfter){
if (trigger.isUpdate || trigger.isInsert){
//Create set of Opportunity Ids based on updated Opportunity/s
Set <String> caseIds = new Set <String>();
for (Case ca : trigger.new){
caseIds.add(ca.ID);
}
Map <String, case>matchingcasecomps = new Map <String, case> ();
for(case c: [select Id, Subject, Description, SuppliedEmail, RMM_Alert_Date_and_Time__c , RMM_Action_Required__c, RMM_Computer_Name__c, RMM_Error_Message__c ,
RMM_Client_Location__c, RMM_Last_Contact_with_Player__c from case where Id in :caseIds])
{
IF( c.SuppliedEmail == 'nocmonitoring@fourwindsinteractive.com' && c.subject.startswith('FWIRMM - Offline Players:')){
{
string body = c.Description;
string sub = c.Subject;
string fromAdd = c.SuppliedEmail;
dateTime alertDate = system.now();
string action;
string computer;
string alert;
string location;
string contact;
string accRmm;
string accTrimFront;
string accTrimRear;
Id accId;
List<string> parse = body.split('\\n');
alert = parse[0];
computer = parse[1];
location = parse[3];
contact = parse[4];
action = parse[5];
accRmm = parse[8];
accTrimFront = accRmm.replaceFirst('\\[(?:rmm)\\:', '');
accTrimRear = accTrimFront.replaceFirst('\\:(?:rmm)\\]', '');
string accString = accTrimRear;
/*List<Account> accQuery = [Select Id from Account Where Id =:accString];
FOR(Account accQ: accQuery){
IF(accQuery[0] != Null){
accId = [Select Id from Account Where Id =:accString].Id;
}else{
accId='';
}}*/
accId = Id.valueOf(accString);
c.RMM_Alert_Date_and_Time__c = system.now();
c.RMM_Action_Required__c = action;
c.RMM_Computer_Name__c = computer;
c.RMM_Error_Message__c = alert;
c.RMM_Client_Location__c = location;
c.RMM_Last_Contact_with_Player__c = contact;
c.AccountId = accId;
update c;
}
@isTest(seealldata = true)
public class RmmEmailCaseUpdateTest {
static testMethod void RmmEmailCaseUpdate(){
Case c = new Case(
subject ='FWIRMM - Offline Players:',
Description = 'Alert issue - Content Player PC is unreachable \r\n Computer - CLTSD \r\n PC Type/Serial Number - FWPW-QUAD-WIFI-SW / GIG41327 \r\n \r\n Alert Date and Time - 4/25/2017 3:17:27 AM Client/Location - SpringHill Suites / SpringHill Suites Site \r\n Last contact with Player: ~4/25/2017 12:29:52 AM id 4113~ FAILED \r\n \r\n ACTION REQUIRED - Investigate computer logs. If no fault found, contact client to get PC back online. \r\n \r\n [rmm:0018000000MEgf1:rmm]',
Origin = 'NOC',
Status = 'New',
RecordTypeId = '0123400000046GJ',
SuppliedEmail = 'nocmonitoring@fourwindsinteractive.com');{
insert c;
}
}
}
caused by: System.StringException: Invalid id:
Trigger.RmmEmailCaseUpdate: line 51, column 1: []"
The account I am using in the string is correct and always sets the account when I use the trigger in Sandbox but does not work when I write the test class. My class and test class are below.
trigger RmmEmailCaseUpdate on Case (after insert) {
if (trigger.isAfter){
if (trigger.isUpdate || trigger.isInsert){
//Create set of Opportunity Ids based on updated Opportunity/s
Set <String> caseIds = new Set <String>();
for (Case ca : trigger.new){
caseIds.add(ca.ID);
}
Map <String, case>matchingcasecomps = new Map <String, case> ();
for(case c: [select Id, Subject, Description, SuppliedEmail, RMM_Alert_Date_and_Time__c , RMM_Action_Required__c, RMM_Computer_Name__c, RMM_Error_Message__c ,
RMM_Client_Location__c, RMM_Last_Contact_with_Player__c from case where Id in :caseIds])
{
IF( c.SuppliedEmail == 'nocmonitoring@fourwindsinteractive.com' && c.subject.startswith('FWIRMM - Offline Players:')){
{
string body = c.Description;
string sub = c.Subject;
string fromAdd = c.SuppliedEmail;
dateTime alertDate = system.now();
string action;
string computer;
string alert;
string location;
string contact;
string accRmm;
string accTrimFront;
string accTrimRear;
Id accId;
List<string> parse = body.split('\\n');
alert = parse[0];
computer = parse[1];
location = parse[3];
contact = parse[4];
action = parse[5];
accRmm = parse[8];
accTrimFront = accRmm.replaceFirst('\\[(?:rmm)\\:', '');
accTrimRear = accTrimFront.replaceFirst('\\:(?:rmm)\\]', '');
string accString = accTrimRear;
/*List<Account> accQuery = [Select Id from Account Where Id =:accString];
FOR(Account accQ: accQuery){
IF(accQuery[0] != Null){
accId = [Select Id from Account Where Id =:accString].Id;
}else{
accId='';
}}*/
accId = Id.valueOf(accString);
c.RMM_Alert_Date_and_Time__c = system.now();
c.RMM_Action_Required__c = action;
c.RMM_Computer_Name__c = computer;
c.RMM_Error_Message__c = alert;
c.RMM_Client_Location__c = location;
c.RMM_Last_Contact_with_Player__c = contact;
c.AccountId = accId;
update c;
}
@isTest(seealldata = true)
public class RmmEmailCaseUpdateTest {
static testMethod void RmmEmailCaseUpdate(){
Case c = new Case(
subject ='FWIRMM - Offline Players:',
Description = 'Alert issue - Content Player PC is unreachable \r\n Computer - CLTSD \r\n PC Type/Serial Number - FWPW-QUAD-WIFI-SW / GIG41327 \r\n \r\n Alert Date and Time - 4/25/2017 3:17:27 AM Client/Location - SpringHill Suites / SpringHill Suites Site \r\n Last contact with Player: ~4/25/2017 12:29:52 AM id 4113~ FAILED \r\n \r\n ACTION REQUIRED - Investigate computer logs. If no fault found, contact client to get PC back online. \r\n \r\n [rmm:0018000000MEgf1:rmm]',
Origin = 'NOC',
Status = 'New',
RecordTypeId = '0123400000046GJ',
SuppliedEmail = 'nocmonitoring@fourwindsinteractive.com');{
insert c;
}
}
}
- Andrew Aldis
- April 26, 2017
- Like
- 0
System.QueryException: List has no rows for assignment to SObject on test class
I am trying to write a test class for a controller extension and cannot seem to get it to work I keep getting a error: "System.QueryException: List has no rows for assignment to SObject on test class" and cannot figure out why. My controller and test class are below.
public class HardwareWoSalesOrderLineEdit {
public HardwareWoSalesOrderLineEdit(ApexPages.StandardController controller) {
//parent record
this.proj =[select Sales_Order__c, Id, X2nd_Sales_Order__c From Work_Order__c Where Id = :ApexPages.currentPage().getParameters().get('id')];
// child records
this.line = [ SELECT SCMC__Quantity__c, Item_Name__c,SCMC__Quantity_Shipped__c, Category__c, SCMC__Item_Description__c, PM_Ordering_Details__c, Quantity_to_Ship__c, Remaining_Quantity__c
FROM SCMC__Sales_Order_Line_Item__c
WHERE (Item_Type__c = 'Hardware' AND SCMC__Status__c != 'Completed' AND SCMC__Status__c != 'Shipped' AND Category__c != 'Physical Install' AND SCMC__Status__c != 'Cancelled' AND SCMC__Sales_Order__c = :proj.Sales_Order__c) OR
(Item_Type__c = 'Hardware' AND SCMC__Status__c != 'Completed' AND SCMC__Status__c != 'Shipped' AND Category__c != 'Physical Install' AND SCMC__Status__c != 'Cancelled' AND SCMC__Sales_Order__c = :proj.X2nd_Sales_Order__c) ORDER BY Category__c ASC ];
}
//get sales order lines
public SCMC__Sales_Order_Line_Item__c[] getline() {
return this.line;
}
// save method to save changes to the sales order lines
public pagereference saveChanges() {
upsert this.line;
pageRef.setRedirect(true);
return pageRef;
}
// class variables
public PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
public Work_Order__c proj;
public SCMC__Sales_Order_Line_Item__c[] line;
}
TEST CLASS
@istest(seealldata=true)
public class HardwareWoSalesOrderLineEditTest{
static testMethod void HardwareWoSalesOrderLineEditTest(){
Test.startTest();
SCMC__Sales_Order_Line_Item__c sol = [Select Id, SCMC__Item_Master__c, SCMC__Sales_Order__c, SCMC__Sales_Order__r.Installation__c, CreatedById,
SCMC__Sales_Order__r.SCMC__Customer_Account__c
from SCMC__Sales_Order_Line_Item__c where Item_Type__c = 'Hardware' AND SCMC__Status__c != 'Completed'
AND SCMC__Status__c != 'Shipped' AND Category__c != 'Physical Install' limit 1];
system.assertnotEquals(null, sol);
system.debug(sol.Id);
Work_Order__c wo = new Work_Order__c(
Account__c = sol.SCMC__Sales_Order__r.SCMC__Customer_Account__c,
Sales_Order__c = sol.SCMC__Sales_Order__c,
Installation__c = sol.SCMC__Sales_Order__r.Installation__c,
Resource__c = sol.CreatedById,
Type__c = 'Hardware Order',
Start_Date__c = system.today(),
Due_Date__c = system.today(),
Confirm_address_is_correct__c = true,
RecordTypeId = '01234000000Bmk8',
Name = 'testwo123');{
insert wo;}
system.assertnotEquals(null, wo);
system.debug(wo.Id);
Work_Order__c w = [Select Id from Work_Order__c Where Name = 'testwo123' Limit 1];
system.assertnotEquals(null, w);
system.debug(w);
Test.setCurrentPage(Page.HardwareWoSalesOrderLineEdit);
ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(w);
system.debug(sc);
HardwareWoSalesOrderLineEdit myPageCon = new HardwareWoSalesOrderLineEdit(sc);
system.debug(myPageCon);
myPageCon.getline().add(sol);
myPageCon.saveChanges();
Test.stopTest();
}
}
public class HardwareWoSalesOrderLineEdit {
public HardwareWoSalesOrderLineEdit(ApexPages.StandardController controller) {
//parent record
this.proj =[select Sales_Order__c, Id, X2nd_Sales_Order__c From Work_Order__c Where Id = :ApexPages.currentPage().getParameters().get('id')];
// child records
this.line = [ SELECT SCMC__Quantity__c, Item_Name__c,SCMC__Quantity_Shipped__c, Category__c, SCMC__Item_Description__c, PM_Ordering_Details__c, Quantity_to_Ship__c, Remaining_Quantity__c
FROM SCMC__Sales_Order_Line_Item__c
WHERE (Item_Type__c = 'Hardware' AND SCMC__Status__c != 'Completed' AND SCMC__Status__c != 'Shipped' AND Category__c != 'Physical Install' AND SCMC__Status__c != 'Cancelled' AND SCMC__Sales_Order__c = :proj.Sales_Order__c) OR
(Item_Type__c = 'Hardware' AND SCMC__Status__c != 'Completed' AND SCMC__Status__c != 'Shipped' AND Category__c != 'Physical Install' AND SCMC__Status__c != 'Cancelled' AND SCMC__Sales_Order__c = :proj.X2nd_Sales_Order__c) ORDER BY Category__c ASC ];
}
//get sales order lines
public SCMC__Sales_Order_Line_Item__c[] getline() {
return this.line;
}
// save method to save changes to the sales order lines
public pagereference saveChanges() {
upsert this.line;
pageRef.setRedirect(true);
return pageRef;
}
// class variables
public PageReference pageRef = new PageReference(ApexPages.currentPage().getUrl());
public Work_Order__c proj;
public SCMC__Sales_Order_Line_Item__c[] line;
}
TEST CLASS
@istest(seealldata=true)
public class HardwareWoSalesOrderLineEditTest{
static testMethod void HardwareWoSalesOrderLineEditTest(){
Test.startTest();
SCMC__Sales_Order_Line_Item__c sol = [Select Id, SCMC__Item_Master__c, SCMC__Sales_Order__c, SCMC__Sales_Order__r.Installation__c, CreatedById,
SCMC__Sales_Order__r.SCMC__Customer_Account__c
from SCMC__Sales_Order_Line_Item__c where Item_Type__c = 'Hardware' AND SCMC__Status__c != 'Completed'
AND SCMC__Status__c != 'Shipped' AND Category__c != 'Physical Install' limit 1];
system.assertnotEquals(null, sol);
system.debug(sol.Id);
Work_Order__c wo = new Work_Order__c(
Account__c = sol.SCMC__Sales_Order__r.SCMC__Customer_Account__c,
Sales_Order__c = sol.SCMC__Sales_Order__c,
Installation__c = sol.SCMC__Sales_Order__r.Installation__c,
Resource__c = sol.CreatedById,
Type__c = 'Hardware Order',
Start_Date__c = system.today(),
Due_Date__c = system.today(),
Confirm_address_is_correct__c = true,
RecordTypeId = '01234000000Bmk8',
Name = 'testwo123');{
insert wo;}
system.assertnotEquals(null, wo);
system.debug(wo.Id);
Work_Order__c w = [Select Id from Work_Order__c Where Name = 'testwo123' Limit 1];
system.assertnotEquals(null, w);
system.debug(w);
Test.setCurrentPage(Page.HardwareWoSalesOrderLineEdit);
ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(w);
system.debug(sc);
HardwareWoSalesOrderLineEdit myPageCon = new HardwareWoSalesOrderLineEdit(sc);
system.debug(myPageCon);
myPageCon.getline().add(sol);
myPageCon.saveChanges();
Test.stopTest();
}
}
- Andrew Aldis
- April 21, 2017
- Like
- 0
Add attachment to a task with Inbound Email Handler
I am creating a inbound email handler class to create a task when an email is recieved. I would like any attachment to be added to the task as well but cannot seem to get that part to work. The class will create a task correclty it just won't create the attachment. My code is below.
global class partnerTaskEmailClass implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.Inboundenvelope envelope){
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
Contact Contact;
if([select count() from Contact where Email = :email.fromAddress ] == 0)
{
Contact = [Select ID, Account_Id__c from Contact where email = 'tcaldwell@fourwindsinteractive.com' AND Account_Id__c = '0018000001BeR5A' limit 1];
}
else {
Contact = [Select ID, Account_Id__c from Contact where email = :email.fromAddress ];
}
task t = new task();
t.WhoId = Contact.Id;
t.whatId = Contact.Account_Id__c;
t.Subject = email.subject;
t.description = email.PlainTextBody;
t.Partner_Email_Address__c = email.fromAddress;
t.Type = 'Partner Request';
t.ActivityDate = Date.today().addDays(1);
t.RecordTypeId = '0121b000000CkAG';
t.OwnerId = '00580000004V5YW';
t.Priority = 'Normal';
insert t;
if(email.textAttachments != null)
{
Task newtask = [Select Id from Task where Subject = : email.subject order by CreatedDate Desc Limit 1];
for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
Attachment attachment = new Attachment();
attachment.Name = tAttachment.fileName;
attachment.Body = Blob.valueOf(tAttachment.body);
attachment.ParentId = newtask.Id;
insert attachment;
}
}
Return Result;
}
}
global class partnerTaskEmailClass implements Messaging.InboundEmailHandler {
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.Inboundenvelope envelope){
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
Contact Contact;
if([select count() from Contact where Email = :email.fromAddress ] == 0)
{
Contact = [Select ID, Account_Id__c from Contact where email = 'tcaldwell@fourwindsinteractive.com' AND Account_Id__c = '0018000001BeR5A' limit 1];
}
else {
Contact = [Select ID, Account_Id__c from Contact where email = :email.fromAddress ];
}
task t = new task();
t.WhoId = Contact.Id;
t.whatId = Contact.Account_Id__c;
t.Subject = email.subject;
t.description = email.PlainTextBody;
t.Partner_Email_Address__c = email.fromAddress;
t.Type = 'Partner Request';
t.ActivityDate = Date.today().addDays(1);
t.RecordTypeId = '0121b000000CkAG';
t.OwnerId = '00580000004V5YW';
t.Priority = 'Normal';
insert t;
if(email.textAttachments != null)
{
Task newtask = [Select Id from Task where Subject = : email.subject order by CreatedDate Desc Limit 1];
for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
Attachment attachment = new Attachment();
attachment.Name = tAttachment.fileName;
attachment.Body = Blob.valueOf(tAttachment.body);
attachment.ParentId = newtask.Id;
insert attachment;
}
}
Return Result;
}
}
- Andrew Aldis
- January 13, 2017
- Like
- 0
Custom Button to Create Child Records
I am trying to create a button that will run a quary then create child records. The query seems to be working but the insert fails, usually do to incorrect data types such as dates and ids coming across as strings. I have rewritten it a couple of time to upsert and create the records but run into the same problem either way. When I remove the quotes from the values I am going to insert it fails to recognize the values. Can some one help I feel like there are just 1 or 2 little tweaks needed to get this working.
{!REQUIRESCRIPT("/soap/ajax/25.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")}
var sol = sforce.connection.query("Select Id, Name, SCMC__Sales_Order__c, SCMC__Sales_Order__r.Id, Installation_ID__c, SCMC__Item_Master__r.Id, SCMC__Item_Master__r.PSA_Task_Automation__c, SCMC__Item_Master__r.PSA_Task_Automation_Assigned_To__c, SCMC__Item_Master__r.PSA_Task_Automation_Budg_Bill_Hours__c, SCMC__Item_Master__r.PSA_Task_Automation_Duration__c, SCMC__Item_Master__r.PSA_Task_Automation_Notes__c, SCMC__Item_Master__r.PSA_Task_Automation_Role__c, SCMC__Item_Master__r.PSA_Task_Automation_Task_Name__c, PSA_Created__c, PSA_Task_Automation__c From SCMC__Sales_Order_Line_Item__c where PSA_Task_Automation__c = True AND PSA_Created__c = False AND SCMC__Sales_Order__r.Installation__c = '{!SFDC_Project__c.Id}'");
var records = sol.getArray("records");
if("{!$User.Id}"== "00580000008JMjO" ){
confirm("This will create "+records.length+" Project Tasks.");
for(var i=0; i<=records.length; i++){
var psa = new sforce.SObject("Project_Task__c");
psa.Project__c = '{!SFDC_Project__c.Id}';
psa.Assigned_To__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Assigned_To__c';
psa.Project_Task_Notes__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Notes__c';
psa.Role__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Role__c';
psa.Task__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Task_Name__c';
psa.Start_Date__c = '{!TODAY()}';
psa.Duration__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Duration__c';
}
var result = sforce.connection.upsert('Id',[psa]);
if (result[0].getBoolean("success")) {
alert("new tasks created with id " + result[0].id);
} else {
alert("failed to create tasks " + result[0]);
}
alert('There are no automated tasks to create.');
}
{!REQUIRESCRIPT("/soap/ajax/25.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")}
var sol = sforce.connection.query("Select Id, Name, SCMC__Sales_Order__c, SCMC__Sales_Order__r.Id, Installation_ID__c, SCMC__Item_Master__r.Id, SCMC__Item_Master__r.PSA_Task_Automation__c, SCMC__Item_Master__r.PSA_Task_Automation_Assigned_To__c, SCMC__Item_Master__r.PSA_Task_Automation_Budg_Bill_Hours__c, SCMC__Item_Master__r.PSA_Task_Automation_Duration__c, SCMC__Item_Master__r.PSA_Task_Automation_Notes__c, SCMC__Item_Master__r.PSA_Task_Automation_Role__c, SCMC__Item_Master__r.PSA_Task_Automation_Task_Name__c, PSA_Created__c, PSA_Task_Automation__c From SCMC__Sales_Order_Line_Item__c where PSA_Task_Automation__c = True AND PSA_Created__c = False AND SCMC__Sales_Order__r.Installation__c = '{!SFDC_Project__c.Id}'");
var records = sol.getArray("records");
if("{!$User.Id}"== "00580000008JMjO" ){
confirm("This will create "+records.length+" Project Tasks.");
for(var i=0; i<=records.length; i++){
var psa = new sforce.SObject("Project_Task__c");
psa.Project__c = '{!SFDC_Project__c.Id}';
psa.Assigned_To__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Assigned_To__c';
psa.Project_Task_Notes__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Notes__c';
psa.Role__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Role__c';
psa.Task__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Task_Name__c';
psa.Start_Date__c = '{!TODAY()}';
psa.Duration__c = 'sol.SCMC__Item_Master__r.PSA_Task_Automation_Duration__c';
}
var result = sforce.connection.upsert('Id',[psa]);
if (result[0].getBoolean("success")) {
alert("new tasks created with id " + result[0].id);
} else {
alert("failed to create tasks " + result[0]);
}
alert('There are no automated tasks to create.');
}
- Andrew Aldis
- September 13, 2016
- Like
- 0
Apex Detail
I built an object with about 8 child objects. I would like to add a button that renders the page as a PDF, can I use APEX:Detail to render the parent object as well as child objects as PDF's on the page.
- Andrew Aldis
- January 22, 2016
- Like
- 0