• Derek Davis 7
  • NEWBIE
  • 45 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 7
    Questions
  • 17
    Replies
I have a relatively simple search controller, but I am not sure of best practices for writing the required test coverage. Could anyone offer potential test coverage or general guidance? Thanks in advance for any feedback! Here is the code:
public class ServiceRequestSearchController {
public list <Service_Request__c> sr {get;set;} 
   public string searchstring {get;set;}
   public string myFacilityid {get;set;}   
    

   public ServiceRequestSearchController(ApexPages.StandardController controller) {
   } 
 
   //perform search when "Search" button is clicked//
   public void search(){
       System.debug('::myFacilityid::'+myFacilityid);
       string searchquery='select Site_Number__r.name,Name_of_Contact2__c,Assigned_To__r.Name,Site_Number__r.Facility__c,Name,Created_Date_Only__c,Status__c,Subject__c,Priority__c,id from service_request__c where (Site_Number__r.Facility__c= \''+myFacilityid+'\') and (Site_Number__r.name like \'%'+searchstring+'%\') order by createddate DESC Limit 20';
     sr= Database.query(searchquery);
   }  
   public void clear(){  
   sr.clear();  
  
 }
}

 
Hello,
I have an Apex Controller and a Visualforce page. My controller does several things, amoung them it gets values of a List; and those values are used to populate a Drop Down Field of Departments names on the Visualforce page. The list only shows departments that are related to a facility id. Below is an exerpt from my controller:

This Works:
List<Department__c> Departments = [select id ,name from Department__c where Facility__c = '00160000010NjFa'] ;


This Doesn't Work:
List<Department__c> Departments = [select id ,name from Department__c where Facility__c = {!myFacilityid} ] ;

The variable myFacilityid is populated in the controller (code to populate the variable not shown here, but I do know it's working because I reference this variable in a different searchquery as \''+myFacilityid+'\').

I also attempted to reference the variable as:
  • \''+myFacilityid+'\'
  • :myFacilityid
  • {!myFacilityid}
None of these attempts work.

How do I reference the variable in the Where clause shown above?
Hello,

I am trying to pass a variable from a URL into my Controller Extension, and then use that variable in a SOQL Where Clause within the same extension. I still learning to code and I'm not doing somthing correctly. Any guidance would be much appreciated!

This is what I have:

Passing the variable through the URL:
  • There's a simple varable called "varFacilityID" assigned a value via the URL. For example: /apex/search_service_request?varFacilityID=00160000010NjFa
 
  • I included the following parameter on my Visualforce Page:
    <apex:param name="varFacilityID" value="{!$CurrentPage.parameters.varFacilityID}"/>
    
  • I added the following string to my controller:
    //get Facility ID //     
    public String MyFacilityID = ApexPages.currentPage().getParameters().get('varFacilityID')

Adding the variable into the where clause:
  • I have the following query... (Note: This was working prior to adding the additional "where" condition for MyFacilityID.
    //perform search - return specified fields from the record that meets the where clause // 
       public void search(){  
           string searchquery='select Philips_Site_Number__r.name,Name,SR_Created_Date__c,Status__c,Subject__c,Priority__c,id from service_request__c where Philips_Site_Number__r.Facility__c = MyFacilityID AND Philips_Site_Number__r.name like \'%'+searchstring+'%\' order by createddate DESC Limit 20';
         sr= Database.query(searchquery);  
       }
This is the full code below:

Controller Extension:
public class ServiceRequestSearchController {
public list <Service_Request__c> sr {get;set;}  
 
//get Facility ID //     
public String MyFacilityID = ApexPages.currentPage().getParameters().get('varFacilityID');
    
        
   public string searchstring { get; set;}  
   public ServiceRequestSearchController(ApexPages.StandardController controller) {  
   }     
    
    //perform search - return specified fields from the record that meets the where clause // 
   public void search(){  
       string searchquery='select Philips_Site_Number__r.name,Name,SR_Created_Date__c,Status__c,Subject__c,Priority__c,id from service_request__c where Philips_Site_Number__r.Facility__c = MyFacilityID AND Philips_Site_Number__r.name like \'%'+searchstring+'%\' order by createddate DESC Limit 20';
     sr= Database.query(searchquery);  
   }  
   public void clear(){  
   sr.clear();  
   } 
 }



Visual Force Page:
<apex:page standardController="Service_Request__c" showHeader="false" extensions="ServiceRequestSearchController">  
If your Service Request has been Accepted, then click the "Search for Work Order" link to see the details of your Service Request and related Work Order. <br></br>
  <apex:form >  
 <apex:param name="varFacilityID" value="{!$CurrentPage.parameters.varFacilityID}"/>
 <apex:inputText value="{!searchstring}" label="Input"/>   
  <apex:commandButton value="Search records" action="{!search}"/>  
  <apex:commandButton value="Clear records" action="{!search}"/>  
   <apex:pageBlock title="Search Result">  
    <apex:pageblockTable width="80%" value="{!sr}" var="s">  
     <apex:column headerValue="Asset Name" >
        <apex:outputText >{!s.Philips_Site_Number__r.Name}</apex:outputText>
     </apex:column>        
     <apex:column headerValue="Service Request #" >
        <apex:outputText >{!s.Name}</apex:outputText>
     </apex:column>  
     <apex:column headerValue="SR Status" >  
        <apex:outputText >{!s.Status__c}</apex:outputText>  &nbsp;<apex:outputText rendered="{!s.Status__c='Accepted'}" ><a href="A PRIVATE URL IS LOCATED HERE... THIS HAS BEEN INTENTIONALLY REMOVED PRIOR TO POSTING ON SFDC DEV FORMS AS IT DOESN'T RELATE TO ISSUE" Target="_blank">(Search for Work Order)</a></apex:outputText>
     </apex:column>   
    <apex:column headerValue="Problem Reported" >  
        <apex:outputText >{!s.Subject__c}</apex:outputText>  
     </apex:column>     
    <apex:column headerValue="Priority" >  
        <apex:outputText >{!s.Priority__c}</apex:outputText>  
     </apex:column>         
     <apex:column headerValue="Created Date" >  
        <apex:outputText >{!s.SR_Created_Date__c}</apex:outputText>  
     </apex:column>           
    </apex:pageBlockTable>     
   </apex:pageBlock>  
  </apex:form>  
 </apex:page>



 
Hello All,

I'm sure this is something simple... I have an Apex Controller and Visualforce page that simply allows a user to search for a name of an "Asset" (custom object) and it returns "Service Request" (another custom object) that are related to that Asset. 

I am limiting the search to only return 20 results, but I would like to to return the most recent 20 records. Right now it seems to be returning the first 20 records created instead of the last (most recent) 20 records created.

This is my controller:
public class ServiceRequestSearchController {
public list <Service_Request__c> sr {get;set;}  
   public string searchstring {get;set;}  
   public ServiceRequestSearchController(ApexPages.StandardController controller) {  
   }  
   public void search(){  
     string searchquery='select Philips_Site_Number__r.name,Name,SR_Created_Date__c,Status__c,Subject__c,Priority__c,id from service_request__c where Philips_Site_Number__r.name like \'%'+searchstring+'%\' Limit 20';
     sr= Database.query(searchquery);  
   }  
   public void clear(){  
   sr.clear();  
   } 
 }


This is my visualforce page:
<apex:page standardController="Service_Request__c" showHeader="false" extensions="ServiceRequestSearchController">  
  <apex:form >  
 <apex:inputText value="{!searchstring}" label="Input"/>   
  <apex:commandButton value="Search records" action="{!search}"/>  
  <apex:commandButton value="Clear records" action="{!search}"/>  
   <apex:pageBlock title="Search Result">  
    <apex:pageblockTable value="{!sr}" var="s">  
     <apex:column headerValue="Service Request #" >
        <apex:outputText>{!s.Name}</apex:outputText>
     </apex:column>  
     <apex:column headerValue="SR Status" >  
      	<apex:outputText>{!s.Status__c}</apex:outputText>  
     </apex:column>   
	<apex:column headerValue="Problem Reported" >  
      	<apex:outputText>{!s.Subject__c}</apex:outputText>  
     </apex:column>     
	<apex:column headerValue="Priority" >  
      	<apex:outputText>{!s.Priority__c}</apex:outputText>  
     </apex:column>         
     <apex:column headerValue="Created Date" >  
      	<apex:outputText>{!s.SR_Created_Date__c}</apex:outputText>  
     </apex:column>           
    </apex:pageBlockTable>     
   </apex:pageBlock>   
  </apex:form>  
 </apex:page>


Any assistance you can provide would be greatly appreciated!! Thanks in advance!


 
Hello Everyone!

I was able to create a Bitly Integration using the awesome instructions provided by Doug Ayers shown here: https://douglascayers.wordpress.com/2015/10/21/salesforce-create-short-urls-with-bitly-process-builder-and-apex/

This is working well in the Sandbox, but I am not a new to APEX and attempting to create a Test Class so I can move to Production.

There are two different APEX Classes:
  • BitlyService
  • BitlyShortenURLInvocable
Could anyone give suggestions on how to create test classes? The full code is shown below. I understand that I need to create test data within the class, then use the test data to actually perform test, but I'm not understanding what that would look like in this senario. Any direction is appreciated. Thanks in advance!!

BitlyService Apex Class:
/**
 * Simple service to make http callout to
 * Bitly url shortener service.
 */
public class BitlyService {
    
    // reusable access token for oauth,
    // required when making API requests
    private String accessToken;
    
    public BitlyService() {
        this.accessToken = getAccessToken();
    }
    
    /**
     * Given a long URL will return the shortened version.
     * http://dev.bitly.com/links.html#v3_shorten
     */
    public String shorten( String url ) {
        
        HttpRequest req = new HttpRequest();
        req.setEndpoint(
            'callout:Bitly/v3/shorten' +
            '?access_token=' + this.accessToken +
            '&longUrl=' + EncodingUtil.urlEncode( url, 'UTF-8' ) +
            '&format=txt'
        );
        req.setMethod('GET');
        
        Http http = new Http();
        HttpResponse res = http.send(req);
        return res.getBody();
    }
    
    /**
     * Get the access token to make authenticated oauth calls.
     * The actual username/password credentials are stored in
     * Named Credentials so that the password is stored securely.
     * 
     * This does require an extra http request when instantiating
     * the service which adds to latency. Alternatively, you could
     * store the generated access token in a custom setting and simply
     * reference it from your code, but then anyone who can view
     * custom settings can view the access token and use the API.
     * Trade-offs.
     */
    private String getAccessToken() {
        
        HttpRequest req = new HttpRequest();
        req.setEndpoint('callout:Bitly/oauth/access_token');
        req.setMethod('POST');
        
        Http http = new Http();
        HttpResponse res = http.send(req);
        return res.getBody();
    }
    
}



BitlyShortenURLInvocable APEX Class:
public class BitlyShortenURLInvocable {
    
    @InvocableMethod(
        label = 'shorten'
        description = 'Given service request IDs then generates a bitly short url for them'
    )
    public static List<String> shorten( List<ID> srIds ) {
        
        // You can't invoke http callouts from Process Builder or Flow
        // because the database transaction has not committed yet, you will get error:
        // "System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out"
        // To get around this then we'll actually make the call in a @Future method asynchronously.
        shortenAsync( srIds );
        
    return new List<String>();
    }
    
    @Future( callout = true )
    private static void shortenAsync( List<ID> srIds ) {
        
        // Fetch your data and a field where you want to store the generated short url
        List<Service_Request__c> requests = new List<Service_Request__c>([ SELECT id, assigned_to_text__c, short_url__c FROM service_request__c WHERE id IN :srIds ]);
        
        // Service to actually call out to bitly and get a shortened url
    BitlyService service = new BitlyService();
        
        // Bitly does not support bulk url shortening
        // so you must make each call individually.
        // Do be aware of Bitly's rate limiting if you try
        // to mass create a bunch of records in short succession
        // http://dev.bitly.com/rate_limiting.html
        for ( Service_Request__c ServiceRequestObj : requests ) {
            
            // create Service Request URL to be shortened (with the variables needed by the Service Request Status Flow)
            ServiceRequestObj.short_url__c = service.shorten( 'https://MyServerName.salesforce.com/My_Flow_Name_Here?varSRID=' + ServiceRequestObj.id + '&varOriginalAssignedTo=' + ServiceRequestObj.assigned_to_text__c );
            
        }
        
        // update the records with their short urls
        // use workflow or trigger to fire off the short url field being populated
        // to then send email alerts, etc. including the short url
        if ( requests.size() > 0 ) {
            update requests;
        }
        
    }
    
}






 
Hi All - I am very familiar with Salesforce but newer to APEX. I recently created an APEX Class to change the behavior of a Flow Finish Button. When the finish button is clicked this class sets the URL and sets the referenced variables within the URL.

The class is working, but I'm not sure about how to go about creating the test coverage for the Class shown below. Any assistance would be appreciated!!

VF Page -
<apex:page Controller="OpptyFlowController" TabStyle="Opportunity">
    <br/>
    <flow:interview name="CreateOppty" interview="{!myflow}" finishlocation="{!OID}" />
</apex:page>

Here is the Class -
public class OpptyFlowController {

public Flow.Interview.CreateOppty myFlow { get; set; }

public String getmyID() {
if (myFlow==null) return '';
else return myFlow.OpptyID;
}

public PageReference getOID(){
PageReference p = new PageReference('/apex/opportunityProductEntry?id=' + getmyID() + '&addTo=' + getmyID() + '&retURL=%2F006%2Fe&sfdc.override=1');
p.setRedirect(true);
return p;
}

}
Hi All! I have been an admin for a couple years and I am starting to get into some lightweight development. I have a Visualforce page and need it to automatically update the value of a custom picklist field. Could anyone offer any guidance on creating an Extension Controller? (Not sure it if matters, but this page is accessed by a "Complete Event" button. I was using URL Hacking to update field from button, but couldn't get this method to work when we switched to Visualforce page)

Below is the first line of my Visualforce page. It's my understanding that I would need to reference the extension here?

<apex:page standardcontroller="DGCampaign__c">




I need to change the Status of the record to "Completed".
Here is the line of code from my Visualforce page that references the Status field I need to update:

<apex:inputfield value="{!DGCampaign__c.Status__c}" required="false"/>

It is my understanding that I need to create an Extension (Apex Class) that contains Apex tags to update this field?

Could someone confirm if my very basic understanding is correct? And any guidance on what that class should look like would be extremely appreciated!! : )

Thanks,

Derek
Hello,
I have an Apex Controller and a Visualforce page. My controller does several things, amoung them it gets values of a List; and those values are used to populate a Drop Down Field of Departments names on the Visualforce page. The list only shows departments that are related to a facility id. Below is an exerpt from my controller:

This Works:
List<Department__c> Departments = [select id ,name from Department__c where Facility__c = '00160000010NjFa'] ;


This Doesn't Work:
List<Department__c> Departments = [select id ,name from Department__c where Facility__c = {!myFacilityid} ] ;

The variable myFacilityid is populated in the controller (code to populate the variable not shown here, but I do know it's working because I reference this variable in a different searchquery as \''+myFacilityid+'\').

I also attempted to reference the variable as:
  • \''+myFacilityid+'\'
  • :myFacilityid
  • {!myFacilityid}
None of these attempts work.

How do I reference the variable in the Where clause shown above?
Hello,
  I am the admin for a company that has an instance of SFDC that has a lot of customizations and my experience with apex is minimal, so until now i have been making a lot of declarative changes to complete tasks that are given to me. Most recently, i have been asked to not let anyone back date calls that they are making. I am hoping it is a subtle change to the code that i can make. Also, i will be using a Sandbox enviroment to test the changes. Here are some screen shots to give you an idea of my under standing of what is happening with the code. First is a screen shot of what the log a call VF page looks like to the end users. Second is what i am presuming to the be the code that makes that page. Also, would it be difficult to remove the reminder date/ time and reminder notes fields?
 I am open to all suggestions and words of wisdom that may help me understand why this works the way it does. 

Thanks in advance,

Matt
User-added image
User-added image
Hello All,

I'm sure this is something simple... I have an Apex Controller and Visualforce page that simply allows a user to search for a name of an "Asset" (custom object) and it returns "Service Request" (another custom object) that are related to that Asset. 

I am limiting the search to only return 20 results, but I would like to to return the most recent 20 records. Right now it seems to be returning the first 20 records created instead of the last (most recent) 20 records created.

This is my controller:
public class ServiceRequestSearchController {
public list <Service_Request__c> sr {get;set;}  
   public string searchstring {get;set;}  
   public ServiceRequestSearchController(ApexPages.StandardController controller) {  
   }  
   public void search(){  
     string searchquery='select Philips_Site_Number__r.name,Name,SR_Created_Date__c,Status__c,Subject__c,Priority__c,id from service_request__c where Philips_Site_Number__r.name like \'%'+searchstring+'%\' Limit 20';
     sr= Database.query(searchquery);  
   }  
   public void clear(){  
   sr.clear();  
   } 
 }


This is my visualforce page:
<apex:page standardController="Service_Request__c" showHeader="false" extensions="ServiceRequestSearchController">  
  <apex:form >  
 <apex:inputText value="{!searchstring}" label="Input"/>   
  <apex:commandButton value="Search records" action="{!search}"/>  
  <apex:commandButton value="Clear records" action="{!search}"/>  
   <apex:pageBlock title="Search Result">  
    <apex:pageblockTable value="{!sr}" var="s">  
     <apex:column headerValue="Service Request #" >
        <apex:outputText>{!s.Name}</apex:outputText>
     </apex:column>  
     <apex:column headerValue="SR Status" >  
      	<apex:outputText>{!s.Status__c}</apex:outputText>  
     </apex:column>   
	<apex:column headerValue="Problem Reported" >  
      	<apex:outputText>{!s.Subject__c}</apex:outputText>  
     </apex:column>     
	<apex:column headerValue="Priority" >  
      	<apex:outputText>{!s.Priority__c}</apex:outputText>  
     </apex:column>         
     <apex:column headerValue="Created Date" >  
      	<apex:outputText>{!s.SR_Created_Date__c}</apex:outputText>  
     </apex:column>           
    </apex:pageBlockTable>     
   </apex:pageBlock>   
  </apex:form>  
 </apex:page>


Any assistance you can provide would be greatly appreciated!! Thanks in advance!


 
Hello Everyone!

I was able to create a Bitly Integration using the awesome instructions provided by Doug Ayers shown here: https://douglascayers.wordpress.com/2015/10/21/salesforce-create-short-urls-with-bitly-process-builder-and-apex/

This is working well in the Sandbox, but I am not a new to APEX and attempting to create a Test Class so I can move to Production.

There are two different APEX Classes:
  • BitlyService
  • BitlyShortenURLInvocable
Could anyone give suggestions on how to create test classes? The full code is shown below. I understand that I need to create test data within the class, then use the test data to actually perform test, but I'm not understanding what that would look like in this senario. Any direction is appreciated. Thanks in advance!!

BitlyService Apex Class:
/**
 * Simple service to make http callout to
 * Bitly url shortener service.
 */
public class BitlyService {
    
    // reusable access token for oauth,
    // required when making API requests
    private String accessToken;
    
    public BitlyService() {
        this.accessToken = getAccessToken();
    }
    
    /**
     * Given a long URL will return the shortened version.
     * http://dev.bitly.com/links.html#v3_shorten
     */
    public String shorten( String url ) {
        
        HttpRequest req = new HttpRequest();
        req.setEndpoint(
            'callout:Bitly/v3/shorten' +
            '?access_token=' + this.accessToken +
            '&longUrl=' + EncodingUtil.urlEncode( url, 'UTF-8' ) +
            '&format=txt'
        );
        req.setMethod('GET');
        
        Http http = new Http();
        HttpResponse res = http.send(req);
        return res.getBody();
    }
    
    /**
     * Get the access token to make authenticated oauth calls.
     * The actual username/password credentials are stored in
     * Named Credentials so that the password is stored securely.
     * 
     * This does require an extra http request when instantiating
     * the service which adds to latency. Alternatively, you could
     * store the generated access token in a custom setting and simply
     * reference it from your code, but then anyone who can view
     * custom settings can view the access token and use the API.
     * Trade-offs.
     */
    private String getAccessToken() {
        
        HttpRequest req = new HttpRequest();
        req.setEndpoint('callout:Bitly/oauth/access_token');
        req.setMethod('POST');
        
        Http http = new Http();
        HttpResponse res = http.send(req);
        return res.getBody();
    }
    
}



BitlyShortenURLInvocable APEX Class:
public class BitlyShortenURLInvocable {
    
    @InvocableMethod(
        label = 'shorten'
        description = 'Given service request IDs then generates a bitly short url for them'
    )
    public static List<String> shorten( List<ID> srIds ) {
        
        // You can't invoke http callouts from Process Builder or Flow
        // because the database transaction has not committed yet, you will get error:
        // "System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out"
        // To get around this then we'll actually make the call in a @Future method asynchronously.
        shortenAsync( srIds );
        
    return new List<String>();
    }
    
    @Future( callout = true )
    private static void shortenAsync( List<ID> srIds ) {
        
        // Fetch your data and a field where you want to store the generated short url
        List<Service_Request__c> requests = new List<Service_Request__c>([ SELECT id, assigned_to_text__c, short_url__c FROM service_request__c WHERE id IN :srIds ]);
        
        // Service to actually call out to bitly and get a shortened url
    BitlyService service = new BitlyService();
        
        // Bitly does not support bulk url shortening
        // so you must make each call individually.
        // Do be aware of Bitly's rate limiting if you try
        // to mass create a bunch of records in short succession
        // http://dev.bitly.com/rate_limiting.html
        for ( Service_Request__c ServiceRequestObj : requests ) {
            
            // create Service Request URL to be shortened (with the variables needed by the Service Request Status Flow)
            ServiceRequestObj.short_url__c = service.shorten( 'https://MyServerName.salesforce.com/My_Flow_Name_Here?varSRID=' + ServiceRequestObj.id + '&varOriginalAssignedTo=' + ServiceRequestObj.assigned_to_text__c );
            
        }
        
        // update the records with their short urls
        // use workflow or trigger to fire off the short url field being populated
        // to then send email alerts, etc. including the short url
        if ( requests.size() > 0 ) {
            update requests;
        }
        
    }
    
}






 
Using Process Builder, I have a series of Processes(Flows) that execute in 2 days, 4 days, etc (email campaign). if certain criteria (call it Criteria A) are met.  The problem with this approach (other than not having the ability to create multiple schedules in a single process) is that a process/flow is in a "paused interview" state until the delay time (2 days) and the filter criteria (Criteria A) are met.  While this technically solves my business scenario (don't execute the flow if the user has done X), it results in all of the resulting flows to remain in the "paused interview" state indefinitely.  There is a limit of 30K "paused interviews" at one time, so my question is "how do I progammatically clean-up interviews that I do not need to run any longer?"  I don't see any Apex method for removing these via a scheduled batch or other means.

We are using the Flows to create records that drive transactional emails, otherwise this process is perfect for a time-based Workflow.  Given the lack of functionality to create a record or call a headless flow from time-based workflow, I'm at a loss finding another route for doing this declaratively.

Thanks,

Jason

Hi Everyone,

 

I need to create a dropdown field on Visualforce page which should display the list of Users based on a query.

Then I need to use the chosen  value in my Controller.

 

How to achieve this??

Plz help its urgent 

 

Thanks,

Ankit

We have created a flow that creates an Opportunity and we want the "finishlocation" of the flow, where they end up when they click "Finish", to be the newly created Opportunity. I know that we will have to create a VF page and controller to pass the OpptyID (once created) back to the VF page and set as the finishlocation, but can't figure out how to do it. Any ideas?

Hi All,

 

Sorry to mark it urgent, as i need to implement this soon...

 

I have a custom object with Master detail Relationship, now i want to make this field as lookp field (reason: i may not have the master record each time for the detail record). Please let me know the way of converting the master field to Lookup, or any other Data Type.

 

or else, is there any way to to mark the Master Detail field as non-mandatory on the detail objects page layout

 

Please let me know..

 

Thanks