+ Start a Discussion
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;

Peter BölkePeter Bölke 

i need to get the picklist value for Field Reason of the Case-Objekt. Those vary depending on the record type. I found this on the net, but i am getting an Error 401

    public static List<reasonObject> getReasonRest(Id eId){
        Map<String,String> sessionAttributes = Auth.SessionManagement.getCurrentSession();
        System.debug('Session '+sessionAttributes.get('SessionId'));
        Id rType = [SELECT id, RecordTypeId FROM Case WHERE ID = :eId].RecordTypeId;
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        String host = System.Url.getSalesforceBaseURL().toExternalForm();
        String url = host + '/services/data/v43.0/ui-api/object-info/Case/picklist-values/'+rType+'/Reason';
        //String url = host + '/ui-api/object-info/Case/picklist-values/'+rType+'/Reason';
        request.setHeader('Authorization', 'OAuth '+sessionAttributes.get('SessionId'));
        HttpResponse response;        
        response = http.send(request);
        System.debug('response ' + response);
        Map<String, Object> meta = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
		List<reasonObject> optionsList = new List<reasonObject>();
        //optionsList.add(new SelectOption('--None--', ''));
                for(Object o: (List<Object> )meta.get('values')){
                    Map<String, object > temp = (Map<String, object>)o;        
                    System.debug((String)temp.get('label')+ ' ' + (String)temp.get('value'));
                    reasonObject ro = new reasonObject();
                    //optionsList.add(new SelectOption((String)temp.get('label'), (String)temp.get('value')));
        return optionsList;
System.HttpResponse[Status=Unauthorized, StatusCode=401]
Any suggestions on this?
Is there a better solution for Lightning components?

Best Answer chosen by Peter Bölke
Khan AnasKhan Anas (Salesforce Developers) 
Hi Peter,

I trust you are doing very well. It is a pleasure to be in touch with you again.

The Session Id for Lightning is restricted from most API calls. According to this document (https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/apex_api_calls.htm#apex_api_calls) :

"By security policy, sessions created by Lightning components aren’t enabled for API access. This prevents even your Apex code from making API calls to Salesforce. Using a named credential for specific API calls allows you to carefully and selectively bypass this security restriction.
The restrictions on API-enabled sessions aren’t accidental. Carefully review any code that uses a named credential to ensure you’re not creating a vulnerability."

You need to use a Connected App and Named Credential to enable access to the APIs. Please refer to the below tutorial which might help you further.



I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in future.

Thanks and Regards,
Khan Anas



Inside Contact I'd like to look for all contacts whose first name + ' ' + last name equals a local varialbe, say myVar. I can't figure out how to do the concatenation. I've tried :(FirstName + ' ' + LastName) and that didn't work. This is an inline query. Any ideas please? Thanks!

Best Answer chosen by Admin (Salesforce Developers) 
You can't do any caculation in SOQl as you do in SQL. So you can't put this expression FirstName + ' ' + LastName in a SOQL query string. 

Anyway, if you wanna get the full name, why don't you just use the Name filed which actually is a concat of FirstName and Lastname. 

Andrew McAllisterAndrew McAllister 
I am adding a button that opens a modal window to add a task to a specific "Objective".  There is an add Task button next to every "Objective" that is displayed, but I'm not sure how I can pull the record Id of the specific objective the button sits next to so I can set the WhatId field of the task to that specific objective... Any ideas here? 

Thanks in advance.
<aura:iteration items="{!v.objectives}" var="obj" >

        	<div class="blacklink slds-col slds-size_11-of-12 slds-text-body_regular slds-m-bottom_small slds-box">
                	<a class ="blacklink" href="{!'/lightning/r/Task/'+ obj.Id + '/view'}" target="_blank">	{!obj.Description__c} </a>
            <div id ="obj.Id" class="slds-size_1-of-12 slds-m-top_x-small slds-p-left_large">
                	<lightning:button label="+Task" class="slds-button slds-text-body_regular" onclick="{!c.taskopenmodal}" name="obj.Id"/>
                        <aura:if isTrue="{!obj.Tasks}">
                    	<div class="slds-col slds-size_3-of-5 slds-p-left_xx-large slds-m-bottom_small slds-text-heading_small slds-border_bottom" >
                            Task Subject
                		<div class="slds-col slds-size_1-of-5 slds-m-bottom_small slds-text-heading_small slds-border_bottom">
                		<div class="slds-col slds-size_1-of-5 slds-m-bottom_small slds-text-heading_small slds-border_bottom">
            <aura:iteration items="{!obj.Tasks}" var="t" >
                       	<div class="slds-col slds-size_3-of-5 slds-p-left_xx-large slds-m-bottom_small" >
                            <a href="{!'/lightning/r/Task/'+ t.Id + '/view'}" target="_blank">
                		<div class="slds-col slds-size_1-of-5 slds-m-bottom_small">
                		<div class="slds-col slds-size_1-of-5 slds-m-bottom_small">

Best Answer chosen by Andrew McAllister
Naveen IlaNaveen Ila
We can get the Objective id by using below code. However while populated the name field on the button you haven't use merge field expression.
i.e., {!obj.Id} instead you used obj.Id
Using event.getSource().get("v.name"); 

<lightning:button label="+Task" class="slds-button slds-text-body_regular"onclick="{!c.taskopenmodal}" name="obj.Id"/>  change the highlited to merge field expression.
Out standard Case page layout is being overridden with another visualforce page. In that visualforce page, we are using the apex:detail to display the fields on the page layout.

However, when I add an embedded Visualforce Page to the standard layout, no data is displayed. The embedded page works fine alone or in other standard pages which are not being overridden, but in this page, it doesn't show any data, even simple text.

Here is the Case page override:

<apex:page standardController="Case" action="{!if($Profile.Name != 'Community Partner User',null,urlFor('/apex/case'))}"> 
    <style type="text/css">
        .data2Col, .dataCell { max-width:600px; word-wrap:break-word; }
        .data2Col div, .dataCell { width:700px\9; }
    <apex:includeScript value="{!$Resource.project_cloud__jquery_js}" />
    <script type="text/javascript">
        function esc$(id) {
            return jQuery('#' + id.replace(/(:|\.)/g,'\\\\$1'));
    <project_cloud:tree workableId="{!Case.Id}" projectId="{!Case.project_cloud__Project_Task__r.project_cloud__Project_Phase__r.project_cloud__Project__c}" />

    <apex:pageMessages />

    <apex:form >
        <apex:detail subject="{!Case.Id}" inlineEdit="true" relatedList="true" showChatter="true" />

And here is my very simple Visualforce page:

<apex:page standardController="Case"

        <b>Hello!!! This is the embedded page.</b>


The text doesn't show. Any ideas on why the embedded page doesn't operate under these conditions would be appreciated.

Best Answer chosen by mharikian1.3892229047844834E12
In my visualforce page, I had the <apex:detail> surrounded by <apex:form> tags.

Once I removed the <apex:form> tags, the embedded visualforce page now renders properly.