+ Start a Discussion
Raghu Sharma 6Raghu Sharma 6 
In which scenarios should we put the logic in apex controller vs java script controller

For eg: For making salesforce SOQL/DML statements, we can put the logic apex controller. Similarly, where should be put the logic for REST API calls? When should we use apex controller? Whar are the best practices
Best Answer chosen by Raghu Sharma 6
Rahul KumarRahul Kumar (Salesforce Developers) 
Hi Raghu,

Create a server-side controller in Apex and use the @AuraEnabled annotation to enable access to the controller method.
Only methods that you have explicitly annotated with @AuraEnabled are exposed. Calling server-side actions aren’t counted against your org’s API limits. However, your server-side controller actions are written in Apex, and as such are subject to all the usual Apex limits. A client-side controller handles events within a component. It’s a JavaScript resource that defines the functions for all of the component’s actions.
A client-side controller is a JavaScript object in object-literal notation containing a map of name-value pairs. Each name corresponds to a client-side action. Its value is the function code associated with the action. Client-side controllers are surrounded by parentheses and curly braces. Separate action handlers with commas (as you would with any JavaScript map). hope it will be helpful.

Please mark it as best answer if the information is informative.so that question is removed from an unanswered question and appear as a proper solution.

Rahul Kumar
Best Answer chosen by Nikhil Bujade
If you are using "/apex/vfpage" to open VF page in iframe, it is a change in context and origin as visualforce is loading from lightning.

There are mulitple redirects done before page is loaded if we use relative url, resulting in Performance issue in loading.

Try using absolute URL, please visit below article.

http://ashishsfdc.blogspot.com/2018/09/loading-visualforce-in-iframe.html (http://ashishsfdc.blogspot.com/2018/09/loading-visualforce-in-iframe.html" target="_blank)
On Opportuntities we have the default "Next Steps" field, but it's not very long and we'd like to retain back history of the progress of a deal.  I've created a long text field "Sales Progress".  Here's what I'd like to do using a workflow trigger and field update:  Whenever a new entry is made in Next Steps, copy that entry over to Sales Progress and add it to the bottom (or top) of the existing text.  What would the formula look like?
Best Answer chosen by mcooper1.3926705144774475E12
You would want to create a workflow rule on the Opportunitiy object.

For evaluation criteria, you would want to use 'created, and every time it’s edited'.  

The Rule Criteria would be 


Then for an action, you would create a field update.  The update would be on the Sales_Progress__c field.  You would use a formual to set the new value.  The formula you would want to use would be 

Sales_Progress__c + BR() + BR() + $User.LastName + ', ' + $User.FirstName + ' ' + TEXT(Today()) + ' - ' + NextStep

This appends the the next step field to your custom sales progress field.  It also adds the user and the date so you know who made the change and when, so it should show a decent chronological story of the opportunity.  

Hope that helps

I have a picklist with an onchange event bound to it.
When I select a value in the picklist, I get the following error message :
This page has an error. You might just need to refresh it. Error in $A.getCallback() [b.run is not a function] Failing descriptor: {lightning:select}

Component :
    <aura:attribute name="colors" type="String[]"/>
    <aura:attribute name="selectedColor1" type="String"/>
    <aura:handler name="init" value="{!this}" action="{!c.loadOptions}" />
    <lightning:select aura:id="select1-id" value="{v.selectedColor1}" onchange="{c.onChangeColor}" name="picklist1" label="Select a Color"  >
        <option value="">-- None --</option>
        <aura:iteration items="{!v.colors}" var="color">
            <option value="{!color.value}" text="{!color.label}"></option>
Controller :
    loadOptions: function (component, event, helper) {
        var opts = [
            { value: "R", label: "Red" },
            { value: "G", label: "Green" },
            { value: "B", label: "Blue" }
         component.set("v.colors", opts);
    onChangeColor: function (component, event, helper) {
        //var myColor = event.getSource().get("v.value");
        //var test;

Best Answer chosen by bretondev
Ashif KhanAshif Khan

There is small syntext error issue -- {!v.selectedColor1}​ & {!c.onChangeColor} here​  ' ! ' is missing
<lightning:select aura:id="select1-id" value="{!v.selectedColor1}" onchange="{!c.onChangeColor}" name="picklist1" label="Select a Color"  >
        <option value="">-- None --</option>
        <aura:iteration items="{!v.colors}" var="color">
            <option value="{!color.value}" text="{!color.label}"></option>


Hi.  I am trying to assign a queue as the case owner.. In a Case Before Trigger, I am have the following.  The case owner is getting updated if the abm__c field is populated.. however, it does not get updated with the queue if that field is null.

Account_Team__c at = aMap.get(c.AccountId);
                // Only change the owner if the Account Team has
                // an ABM and the ABM is an active user. Once assigned
                // set the flag Assigned to ABM
            if (string.isNotBlank(at.abm__c)) {
                if (at.abm__r.IsActive) {
                    c.ownerid = at.abm__c;
                    c.Assigned_To_ABM__c = true;                    
              else {
                c.ownerid = abmQueue[0].Id;

Any help woudl be greatly appreciated!!

Best Answer chosen by fredka
_Zach Boyd_Zach Boyd
I have not used the QueueSObject class before, however I see that it has a QueueId field. Try using that and the owner should be assigned properly.


Naveen Kannoju02547126464965992Naveen Kannoju02547126464965992 
cloud you please give me help for this Question

I retrive the data from account(using custom controller) object and display that data in datatable(vf) format this one is good.
but  here column name for example: name,industry,type,rating.
here whenever i click the name or industry ior any other field name I want to display sort order depending on that field.

Best Answer chosen by Naveen Kannoju02547126464965992
Hi Naveen

Try these,

Marry SteinMarry Stein 
Hey guys,

i am not familar with javascript, but i really like how the chart.js libary looks. To get started i want to create some cool Salesforce Dashboards with chart.js. I have already create a visualforce Page to show a simple bar chart. Now, i am looking for a way to get the controller variable to the javascript function : 

This is the javascript Code: 
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["M1", "M2", "M3", "M4", "M5", "M6"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],   
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            borderColor: [
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            borderWidth: 1
    options: {
        scales: {
            yAxes: [{
                ticks: {
How can i change the label and dataset with controller variables ? My idea is to create a simple list and transform the list to string. Does this work ? 

Thanks for help guys. I cant find any help for chart.js and visualforce...



Best Answer chosen by Marry Stein
Alain CabonAlain Cabon

The access fo remote object from the client in javascript was used for button with javascript (not supported in Lightning) and it is also an interesting technique for VFP used for the mobile (android/iOs). 

Best Practices for Using Remote Objects: 
Remote Objects pairs well with JavaScript frameworks such as jQuery and AngularJS, and those can help with the complexity of your application’s user interface. Always consider separating the concerns of your application into multiple layers and keeping them as discrete as possible. This is called “separation of concerns,” and it’s a classic software pattern and best practice.

An Example of Using Remote Objects with jQuery Mobile​

i know jQuery and it is explained here:for the basics in Salesforce: https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_javascript_libraries.htm



I want to access controller getter-setter variable inside javascript. How could I do this.


Thanks in advance.







Best Answer chosen by Admin (Salesforce Developers) 


Try the below code snippet as reference:


----------- vf page----------------

<apex:page controller="accessmergefieldinjavascript" >


var stringvalue='{!s}';

var integervalue='{!nn}';

alert(' stringvalue '+stringvalue+' integervalue '+integervalue);





------------ Apex controller -----------------

public class accessmergefieldinjavascript


public string s{get;set;}

public integer nn{get;set;}

public accessmergefieldinjavascript ()







Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

pooja biswaspooja biswas 
I have university as parent object & college as child object.
There is a master-detail relationship defined on child object i.e college

I have a parent-child soql as follows
List<University__c> univList=[select Name,(select Name from colleges__r) from university__c];

Also I have a child-parent soql as follows
List<college__c> univList=[select Name,university__r.Name from college__c

when I execute the parent-child query I do not get any child related records .
Also when I execute child-parent query I do get the name of the college but the university ID I get but I want the university name also not the ID

please let me know.

Best Answer chosen by pooja biswas
Banwari kevatBanwari kevat
Hi pooja,
   Please try this piece of code in developer console. I think you would get what tou want.
For parent-child soql
for(University__c u: [select Name,(select Name from colleges__r) from university__c])
    for(College__c c:u.Colleges__r)
         System.debug('University Name:'+u.Name+'   College Name:'+c.Name);
This code will give you all universities name and colleges under university

For child-Parent soql
For(College__c c:[select Name,university__r.Name,university__c from college__c])
  system.debug('College Name:'+c.Name+'     University Name:'+c.university__r.Name);
This code will give you all colleges name with respected university.

Please choose best answer if your problem has been resolved.

Banwari K

Dagny FernandesDagny Fernandes 
I have a REST service but i am not able to cover this class. 
Below is my code, need help ASAP.

Thanks You in advance.
global class ServiceInvoiceRedirectController {
        global static void AttachPDFtoRecordREST() {
        	List<Id> accId = new List<Id>();
        	List<String> emailList = new List<String>();
            RestRequest req = RestContext.request;
            id recordId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);

            PageReference pdfPage = new PageReference('/apex/ServiceInvoicePDF?Id='+recordId);
            Blob pdf = pdfPage.getContentAsPdf(); //!Test.isRunningTest() ? pdfPage.getContentAsPdf() : Blob.ValueOf('dummy text');
			//List of accoutn Id's of related project
            for(Account_Project_Junction__c accPrjJunRec: [SELECT Id,Project__c,Account__c From Account_Project_Junction__c WHERE Project__c =: recordId]){
            //List of email id's of the selected account's
            for(Contact conRec: [SELECT Id,AccountID,Email,Is_Primary_Contact__c From Contact where AccountID IN: accId AND Is_Primary_Contact__c = true]){
            	if(conRec.Email != null){
            Project__c prjRec = [Select Id,Name from Project__c where Id =: recordId];
            //Insert Invoice record for related project
	        Invoice__c invoRec = new Invoice__c();
	        invoRec.RecordTypeId = Constants_PicklistVariables.serInvoice; 
	        invoRec.Project__c = recordId;
	        insert invoRec;
	        }catch(Exception e){
	        //Insert Attacment to the invoice        
	        Attachment a = New Attachment();
	        a.body = pdf;
	        a.parentID = invoRec.id;
	        a.ContentType  = 'application/pdf';
	        a.Name = 'SER-INV-'+invoRec.id+'.pdf';
	        insert a;
	        }catch(Exception e){
	        //Create the email attachment
	    	Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
	    	efa.setFileName('SER-INV-'+invoRec.id+'.pdf');//Pleace ad pdf name from contact name project and oppty concatinate 
		    // Create the Singal Email Message
		    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
		    email.setSubject('Service Invoice Notification');
		    String[] CCEmails = emailList;
		    //email.setToAddresses(new String[] { 'developer@extentor.com' });//add Contact email id
		    email.setPlainTextBody( 'Dear:Sir/Madam <br/> Please Find Attachment your financial report Attached with this email.');
		    email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
		    // Sends the email
		    Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

        // call this method from your Batch Apex
        global static void attachPdfToRecord( Id recordId, String sessionId )
        	System.debug('Iam in REST API Call method');
            HttpRequest req = new HttpRequest();
            req.setHeader('Authorization', 'OAuth ' + sessionId);

            Http http = new Http();
            HttpResponse response = http.send(req);    

Test class:
global class Test_ServiceInvoiceRedirectController{
    static testMethod void testDoGet() {
		Account acc= InitialTestData.createAccount('Raj');
        insert acc;
        Contact contact1=InitialTestData.createContact(acc.id,'Sen','raj@gmail.com');
        insert contact1;
        Opportunity_Deal__c oppdeal=InitialTestData.createOpportunityDeal('Opp1',acc.id,contact1.id,false,'Quote');
        insert oppdeal;
        Project__c project1=InitialTestData.createPlotProject('Pro',acc.id,'Submitted',oppdeal.id);
        insert project1;
    RestRequest req = new RestRequest(); 
    RestResponse res = new RestResponse();

    // pass the req and resp objects to the method     
    req.requestURI = URL.getSalesforceBaseUrl().toExternalForm()+'/services/apexrest/AttachPDF/'+project1.Id;  
    req.httpMethod = 'GET';

    ServiceInvoiceRedirectController.attachPdfToRecord results = ServiceInvoiceRedirectController.AttachPDFtoRecordREST(req,res);

    System.assertEquals('true', results.success);
    System.assertEquals(10, results.records.size());
    System.assertEquals('Query executed successfully.', results.message);

Best Answer chosen by Dagny Fernandes
Dagny FernandesDagny Fernandes
Thanks a lot @Roy Luo for your help the above code throwing the null value in the response RestRequest req = RestContext.request; req was null but it coverd the attachPdfToRecord method. this helped a lot to complet the code coverage below is the complete test code 

the importent was the "req" url gives the record id to get that id was importent*

Mock Test Class:(The same code)
public class Test_MockAttachPDFtoRecordHttpResponce implements HttpCalloutMock 

        public HTTPResponse respond(HTTPRequest req) 
                // Create a fake response
                HttpResponse res = new HttpResponse();
                return res;

Test Class
private class Test_ServiceInvoiceRedirectController{
    static Account testAccount;
    static Contact testContact;
    static Opportunity_Deal__c testOpportunity;
    static Project__c testNewProject;
    static User testUser;
    Static void init(){
        testAccount = InitialTestData.createAccount('TestAccount');
        insert testAccount;
        testContact = InitialTestData.createContact(testAccount.Id,'TestName','testContact@eamil.com');
        insert testContact;
        testUser = InitialTestData.createUser('TestLast', 'TestFirst', 'userProfile@testuser.com', 'System Administrator');
        insert testUser;
        testOpportunity = InitialTestData.createOpportunityDeal('TestOpportunity', TestAccount.Id, testContact.Id, False, 'Presentation');
        insert testOpportunity;
        testNewProject = InitialTestData.createNewProject('testProject',TestAccount.Id,'Verified',testOpportunity.Id);
        insert testNewProject;
    static testMethod void attachPdfToRecord()
        //mock up your test data
		Test.setMock(HttpCalloutMock.class, new Test_MockAttachPDFtoRecordHttpResponce()); 
		String sessionId=UserInfo.getSessionId();
        ServiceInvoiceRedirectController.attachPdfToRecord(testNewProject.Id, sessionId); 

    static testMethod void AttachPDFtoRecord_Test()
        RestRequest req = new RestRequest(); 
    	RestResponse res = new RestResponse();
        req.requestURI = '/services/apexrest/AttachPDF/';  
        req.addParameter('recordId', testNewProject.id);
    	req.httpMethod = 'GET';  
        RestContext.request = req;
    	RestContext.response = res;