+ Start a Discussion
Harjeet Singh 28Harjeet Singh 28 
Hi All,

I have developed an apex class whcih basically assign users to queue dynamically.I have a VF page which will launch from a custom VF tab.This VF page shows few users and with the checkbox.When checkbox against the username is marked and hit Save button then seleected users will go to the queue defined in class.
Below is my clas:
public class TodayTelesalesDetails {

public Date Today { 
    get { 
        return Date.today(); 
public List<wrapAgent> wrapAgentList{get; set;}
public List<User> selectedAgents{get;set;}

public TodayTelesalesDetails (){
    if(wrapAgentList == null) {
        wrapAgentList = new List<wrapAgent>();

        for(User teleSalesAgent: [select Id, Name, Email from User where Name IN('Steve Waugh','Yuvraj Singh')]) {
            // As each agent is processed we create a new wrap object and add it to the wrapAgentList
            wrapAgentList.add(new wrapAgent(teleSalesAgent));

public PageReference doFullSave(){

    set<id> userSetId = new set<id>();
    list<GroupMember> gmm = new list<GroupMember>();
    List<GroupMember> toBeDeleted= [SELECT Id, GroupId, UserOrGroupId FROM GroupMember where GroupId = '00G9D000000toPYUAY'];
    delete toBeDeleted;
    List<User> userlist=[select Id, Name from User where Name IN('Steve Waugh','Yuvraj Singh')];
    for(User u : userlist)
         for(wrapAgent wrapAccountObj : wrapAgentList) {
            if(wrapAccountObj.selected == true) {

    for(User us : [select id from User where id =: userSetId])
        for(Group gg : [select id,name from Group where type = 'Queue' and Name = 'TeleSales Queue'])
            GroupMember gm = new GroupMember();
            gm.groupId = gg.id;
            gm.UserOrGroupId = us.Id;
    insert gmm;
    PageReference pageRef = new PageReference('/');
            return pageRef;
 public PageReference doCancel(){
         PageReference pageRef = new PageReference('/');
            return pageRef;

 public class wrapAgent{
    public User teleAgent {get; set;}//Please put the custom metadata names
    public Boolean selected {get; set;}

    //This is the contructor method. When we create a new object we pass a telesales metadata member that is set to the acc property. We also set the selected value to false
    public wrapAgent(User teleSalesAgent) {
        teleAgent = teleSalesAgent;
        selected = false;

and below is my test class:
public class Test_TodayTeleSalesDetails {

    public static testMethod void validateusersinqueue() {
    Group testGroup = new Group(Name='test group', Type='Queue');
	insert testGroup;

	System.runAs(new User(Id=UserInfo.getUserId()))
    QueuesObject testQueue = new QueueSObject(QueueID = testGroup.id, SObjectType = 'Lead');
    insert testQueue;
     TodayTelesalesDetails telesalesDetails=new TodayTelesalesDetails();

I am not able to cover below lines of code:
for(User us : [select id from User where id =: userSetId])
        for(Group gg : [select id,name from Group where type = 'Queue' and Name = 'TeleSales Queue'])
            GroupMember gm = new GroupMember();
            gm.groupId = gg.id;
            gm.UserOrGroupId = us.Id;
Below is the screenshot for the same:
Lines of Code is not covering
My current code coverage stands at 73%

Many I request to help me on same to get a code coverage above 75%

Many thanks in advance

Thanks & Regards,
Best Answer chosen by Harjeet Singh 28
Ajay K DubediAjay K Dubedi
Hi Harjeet,

If you want to keep "selected" of wrapAgent as false and want to increase your code coverage then you can use Test.isRunningtest() in your code. You can update your code as below:
for(User u : userlist)
            for(wrapAgent wrapAccountObj : wrapAgentList) {
                    if(wrapAccountObj.selected == true) {

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
Marvin Castro 8Marvin Castro 8 
Hello.  I'm new to salesforce.  How do I create a trigger that will update the lead status to working when an activity is created (event, task, call)?  I saw this code while doing research, and it works for logging a call, but does not update the status if I schedule an event.  Any help will be appreciated.

trigger changeLeadStatus on Task (before insert, before update) {
    String desiredNewLeadStatus = 'Working';

    List<Id> leadIds=new List<Id>();
    for(Task t:trigger.new){
            if(String.valueOf(t.whoId).startsWith('00Q')==TRUE){//check if the task is associated with a lead
            }//if 2
        }//if 1
    List<Lead> leadsToUpdate=[SELECT Id, Status FROM Lead WHERE Id IN :leadIds AND IsConverted=FALSE];
    For (Lead l:leadsToUpdate){
        update leadsToUpdate;
    }catch(DMLException e){
        system.debug('Leads were not all properly updated.  Error: '+e);
Best Answer chosen by Marvin Castro 8
UC InnovationUC Innovation
Hello Marvin,

You need to create the same trigger on the Event Object. Events and Tasks are both activities, but they are separate objects (They are special in that way). You already have the code, just copy it for Events and you should be good!

Hope this helps!
Brock NortonBrock Norton 
I keep getting the following error when trying to check my challenge on "Routing Records with Approvals" on Admin Trail - Intermediate.

Challenge not yet complete... here's what's wrong: 
The process did not set the correct Type value on submitting for approval

User-added image

I'm not sure why it isn't approving.  Please help!

User-added image
User-added image
User-added image
User-added image

Best Answer chosen by Brock Norton
Himanshu ParasharHimanshu Parashar
Hi Brock,

Here is mine version of that Approval process which worked perfectly.

User-added image

You will notice that in Approval steps I don't have any rejection step which is marked as red bold in your Approval process. remove that criteria and it should work.



I am a beginner to Salesforce development.


By default, from the Partner related list on the Opportunity, you can create OpportunityPartner junction objects between an Opportunity and a Partner Account. We want to modify this page. Unfortunately this object is not very easy to customize.


We have come up with a solution that works for us though.

I am going to create a Visualforce page with standardController 'Opportunity' and with an extension class.

The Visualforce page should be built up to look similar to the current Partner Edit page. 


So we are going to have five rows of partners where you can choose if its primary or not, the AccountToId and the Role. You don't have to fill in information on all rows.


I am not at all done with this yet and many things are not working as I would like them too (the radio buttons for instance). But currently I am stuck with the problem that the getters for the partner variables work but the setters does not. In other words I know that the getPartner methods have been run since I have seen this in the debug logs. The setters are never run though and this becomes obvious and also a problem when I try to insert one of the defined partners in the save method . I get an error that the field 'AccountToId' is a required field and should have a value:



Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [AccountToId]: [AccountToId]



Furthermore as you can see I have chosen to use the Partner object since I am not allowed to create OpportunityPartner objects. But when a Partner object gets created an OpportunityPartner object also does so that shouldn't be a problem.


VisualForce page:


<apex:page title="Partners: {!Opportunity.Name}" standardController="Opportunity" extensions="PartnerEditExt" showheader="true" sidebar="true" id="thePage"> <apex:sectionHeader title="Partners" subtitle="{!Opportunity.Name}" id="partnerEditSectionId" help="javascript:openPopupFocusEscapePounds(%27/help/doc/user_ed.jsp?loc=help&target=partners_edit.htm&section=Partners&showSplash=true%27, %27Help%27, 700, 600, %27width=700,height=600,resizable=yes,toolbar=yes,status=no,scrollbars=yes,menubar=yes,directories=no,location=no,dependant=no%27, false, false);"></apex:sectionHeader> <apex:pageMessages /> <apex:form id="theForm"> <apex:pageBlock title="Partners Edit"> <apex:pageBlockSection columns="3"> <!-- Headings --> <apex:outputText value="Primary" style="font-weight:bold" /> <apex:outputText value="Partner" style="font-weight:bold" /> <apex:outputText value="Role" style="font-weight:bold" /> <apex:pageBlockSectionItem > <apex:inputField value="{!Partner0.isPrimary}" id="fromPartnerPrimary0"/> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:outputText value="No Partner" id="noPartnerAccount"/> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem /> <!-- Partner 1 row --> <apex:pageBlockSectionItem > <apex:inputField value="{!Partner1.isPrimary}" id="fromPartnerPrimary1" /> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:inputField value="{!Partner1.AccountToId}" id="fromPartner1" /> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:inputField value="{!Partner1.Role}" id="fromPartnerRole1" /> </apex:pageBlockSectionItem> <!-- Partner 2 row --> <apex:pageBlockSectionItem > <apex:inputField value="{!Partner2.isPrimary}" id="fromPartnerPrimary2"/> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:inputField value="{!Partner2.AccountToId}" id="fromPartner2"/> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:inputField value="{!Partner2.Role}" id="fromPartnerRole2"/> </apex:pageBlockSectionItem> <!-- Partner 3 row --> <apex:pageBlockSectionItem > <apex:inputField value="{!Partner3.isPrimary}" id="fromPartnerPrimary3"/> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:inputField value="{!Partner3.AccountToId}" id="fromPartner3"/> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:inputField value="{!Partner3.Role}" id="fromPartnerRole3"/> </apex:pageBlockSectionItem> </apex:pageBlockSection> <apex:pageBlockButtons location="bottom"> <apex:commandButton action="{!save}" value="Save" immediate="true" /> <apex:commandButton action="{!Cancel}" value="Cancel" /> </apex:pageBlockButtons> </apex:pageBlock> </apex:form> </apex:page>


The Apex extension class:


public with sharing class PartnerEditExt { final Opportunity opp; Partner partner0 = null; Partner partner1 = null; Partner partner2 = null; Partner partner3 = null; ID oppId; ID accId; ID noPartnerAccId = [select id from Account where Name = 'no partner'].Id; /* Constructor */ public PartnerEditExt(ApexPages.StandardController controller) { opp = (Opportunity)controller.getRecord(); oppId = controller.getRecord().Id; accId = [select AccountId from Opportunity where Id = :oppId].AccountId; partner0 = new Partner(OpportunityId=oppId); partner1 = new Partner(OpportunityId=oppId); partner2 = new Partner(OpportunityId=oppId); partner3 = new Partner(OpportunityId=oppId); } /* Save action Insert the specified partners */ public void save() { // Currently no intelligent logic here // I just want to test that partner1 can be inserted insert partner1; } /* Cancel action Redirect user back to opportunity */ public PageReference cancel() { String curr = '/'+ApexPages.currentPage().getParameters().get('id'); PageReference pageref = new Pagereference(curr); return pageref; } /* Getters and Setters for the partner variables */ public Partner getPartner0() { return partner0; } public void setPartner0(Partner p) { partner0 = p; } public Partner getPartner1() { return partner1; } public void setPartner1(Partner p) { partner1 = p; } public Partner getPartner2() { return partner2; } public void setPartner2(Partner p) { partner2 = p; } public Partner getPartner3() { return partner3; } public void setPartner3(Partner p) { partner3 = p; } }


 Some of you might wonder why we didn't choose to use a custom object instead. We though of this but made the assumption that this work would take less time and also be less risky.


What have I done wrong?

I think I might miss some basic understanding here. A solution to my problem with a good explanation would be very welcome!



Thanks / Niklas



Best Answer chosen by Admin (Salesforce Developers) 

Your button has the immediate attribute set to 'true' - this not only skips validation (well document) but also doesn't update any user inputs from the page (not so well documented).


Remove this attribute (which will give you the default value of 'false') and your setters will be invoked. 

Glenn Dailey 1Glenn Dailey 1 
The 'AccountProcessor' class did not achieve 100% code coverage via your test methods. Make sure that you chose 'Run All' tests in the Developer Console at least once before attempting to verify this challenge. I did the run all with no luck. I did notice that this is the new section that was just added and I ran into issues in the first unit too.

Create an Apex class with a method using the @future annotation that accepts a List of Account IDs and updates a custom field on the Account object with the number of contacts associated to the Account. Write unit tests that achieve 100% code coverage for the class.
Create a field on the Account object called 'Number_of_Contacts__c' of type Number. This field will hold the total number of Contacts for the Account.
Create an Apex class called 'AccountProcessor' that contains a 'countContacts' method that accepts a List of Account IDs. This method must use the @future annotation.
For each Account ID passed to the method, count the number of Contact records associated to it and update the 'Number_of_Contacts__c' field with this value.
Create an Apex test class called 'AccountProcessorTest'.
The unit tests must cover all lines of code included in the AccountProcessor class, resulting in 100% code coverage.
Run your test class at least once (via 'Run All' tests the Developer Console) before attempting to verify this challenge.

public class AccountProcessor
  public static void countContacts(Set<id> setId)
      List<Account> lstAccount = [select id,Number_of_Contacts__c , (select id from contacts ) from account where id in :setId ];
      for( Account acc : lstAccount )
          List<Contact> lstCont = acc.contacts ;
          acc.Number_of_Contacts__c = lstCont.size();
      update lstAccount;

public class AccountProcessorTest {
    public static testmethod void TestAccountProcessorTest(){
        Account a = new Account();
        a.Name = 'Test Account';
        Insert a;

        Contact cont = New Contact();
        cont.FirstName ='Bob';
        cont.LastName ='Masters';
        cont.AccountId = a.Id;
        Insert cont;
        set<Id> setAccId = new Set<ID>();
        Account ACC = [select Number_of_Contacts__c from Account where id = :a.id LIMIT 1];
        System.assertEquals ( Integer.valueOf(ACC.Number_of_Contacts__c) ,1);
Best Answer chosen by Glenn Dailey 1
Amit Chaudhary 8Amit Chaudhary 8
I am glad that works. PLease mark best answer and close this thread so that if some one has same issue that post can help other
Hi - when doing the challenge "Bulk Apex Trigger" in Trailhead I get the error message :"Executing against the trigger does not work as expected."

I have checked the name of the class, task name as mentioned in the challenge description.

I have copied the code below :

trigger ClosedOpportunityTrigger on Opportunity (before insert, before update) {
  List<Task> taskList = new List<Task>();

    //If an opportunity is inserted or updated with a stage of 'Closed Won'
    // add a task created with the subject 'Follow Up Test Task'.
    for (Opportunity opp : [SELECT Id,Name FROM Opportunity
                     WHERE Id IN :Trigger.new AND StageName = 'Closed Won']) {
       //add a task with subject 'Follow Up Test Task'.
       taskList.add(new Task(Subject='Follow Up Test Task', WhatId = opp.id ));                
    if (taskList.size() > 0) {
        insert taskList;

Thank you

Best Answer chosen by Pierre-Alain
Ravikant kediaRavikant kedia
First of all you dont need to query the records. In triggers you get those records in by Trigger.new. and if you choose your way which is wrong ( because of an extra sql query ) you need to add "Id IN Trigger.newmap.keyset()" instead of "Id IN :Trigger.new" because "Trigger.new" will return a list of Opportunity records for which it is fiered while "Trigger.newmap.keyset()" will return a set if ID.

Please select this as a best answer.
Alex Wong 4Alex Wong 4 
I am creating a form in Visualforce. Since my form is a bit long, it is hard for users to remember the error message at the top and revise it. On top of the error message, I want to create a validation when users typing in their information.
For example, there are 2 field, users name and email. Users cannot leave the name field blank, if so, I want to show a message of "This field is required to fill in" beside the field. And for email field, I want to have another message to remind users to insert a valid email.
Is there anyway in visualforce to do so? Thanks for your help.
Best Answer chosen by Alex Wong 4
Aniket Malvankar 10Aniket Malvankar 10
Hello Alex,

You can add something like this:
1. Check the Empty
<apex:page id="page">
    function show()
        var name=document.getElementById('page:f1:p1:ip1').value;
        if(name== "" || name==null)
            document.getElementById("page:f1:p1:op2").innerHTML = "Please enter your name"; 
    <apex:form id="f1">
        <apex:pageblock id="p1">
            <apex:outputlabel value="Enter u r name" id="op1" />
            <apex:inputtext id="ip1" />
            <apex:commandbutton value="submit" onclick="return show();" reRender="op2"/>
            <apex:outputlabel id="op2" />

---> Besides salesforce has the on field validation, so u can have that option.

2. create formula syntax 
Regression : '([a-zA-Z0-9_\\-\\.]+)@(((\\[a-z]{1,3}\\.[a-z]{1,3}\\.[a-z]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3}))'


Ajay Kumar 583Ajay Kumar 583 
Can anyone explain Difference between Process Builder and Flows with example ? 
Thanks in Advance. 
Best Answer chosen by Ajay Kumar 583
Deepali KulshresthaDeepali Kulshrestha
Hi Ajay,

Process Builder:

Process Builder is a point-and-click tool that lets you easily automate if/then business processes and see a graphical representation of your process as you build.
Every process consists of a trigger, at least one criteria node, and at least one action. You can configure immediate actions or schedule actions to be executed at a specific time.
I suggest you, to complete the trailhead of process builder it has a better example to make you clear about it.


Flow is a powerful business automation tool that can manipulate data in Salesforce in a variety of ways. Such an application can be created right from the org’s setup with just drag-drop/point-click. The ease of creating flows makes it the number one go-to tool when it comes to complex business requirements

The trailhead for process builder:


Useful link for Flow with an example:


I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha.
Ryan Adams 173Ryan Adams 173 
Please help me resolve this challenge:


The Challenge is as follows:

Generate an Apex class using WSDL2Apex and write a test class.
Generate an Apex class using WSDL2Apex for a SOAP web service, write unit tests that achieve 100% code coverage for the class using a mock response, and run your Apex tests.

Use WSDL2Apex to generate a class called 'ParkService' in public scope using this WSDL file. After you click the 'Parse WSDL' button don't forget to change the name of the Apex Class Name from 'parksServices' to 'ParkService'.
Create a class called 'ParkLocator' that has a 'country' method that uses the 'ParkService' class and returns an array of available park names for a particular country passed to the web service. Possible country names that can be passed to the web service include Germany, India, Japan and United States.
Create a test class named ParkLocatorTest that uses a mock class called ParkServiceMock to mock the callout response.
The unit tests must cover all lines of code included in the ParkLocator class, resulting in 100% code coverage.
Run your test class at least once (via 'Run All' tests the Developer Console) before attempting to verify this challenge.

The error I receive when checking the challencge is:

Challenge Not yet complete... here's what's wrong:
Executing the 'country' method on 'ParkLocator' failed. Make sure the method exists with the name 'country', is public and static, accepts a String and returns an array of Strings from the web service.

Here is the code I am using:
public class ParkLocator {
    public static String[] country(String ctry) {
        ParkService.ParksImplPort prk = 
            new ParkService.ParksImplPort();
        return prk.byCountry(ctry);

global class ParkServiceMock implements WebServiceMock {
   global void doInvoke(
           Object stub,
           Object request,
           Map<String, Object> response,
           String endpoint,
           String soapAction,
           String requestName,
           String responseNS,
           String responseName,
           String responseType) {
        // start - specify the response you want to send
        ParkService.byCountryResponse response_x = 
            new ParkService.byCountryResponse();
        List<String> myStrings = new List<String> {'Park1','Park2','Park3'};
        response_x.return_x = myStrings;
        // end
        response.put('response_x', response_x); 

private class ParkLocatorTest  {
    @isTest static void testCallout() {              
        // This causes a fake response to be generated
        Test.setMock(WebServiceMock.class, new ParkServiceMock());
        // Call the method that invokes a callout
        List<String> result = new List<String>();
        List<String> expectedvalue = new List<String>{'Park1','Park2','Park3'};
        result = ParkLocator.country('India');
        // Verify that a fake result is returned
        System.assertEquals(expectedvalue, result); 

Any help which can be provided is greatly appreciated.  If you could advise me at raadams173@gmail.com if you reply with a solution, I can log in to check it.


Best Answer chosen by Ryan Adams 173
Amit Singh 1Amit Singh 1
Hello Ryan,

Use below code for ParkLocator class.
public class ParkLocator {
    public static String[] country(String country){
        ParkService.ParksImplPort parks = new ParkService.ParksImplPort();
        String[] parksname = parks.byCountry(country);
        return parksname;
If this not resolves the problem then use a new Developer Org for completing the Challenge.

Let me know if this helps :)

Benjamin VisonBenjamin Vison 
I am trying to setup the OAuth process to get the access_token, specifically in PHP using this example (http://developer.force.com/cookbook/recipe/interact-with-the-forcecom-rest-api-from-php). However, I don't know how to avoid the "Allow Access" page that shows up, I would like to be autimatically allowed so the application can continue and get the access_token... It would be a pain to have to manually allow access on every system I am planning on implementing this integration.. What am I missing?
Best Answer chosen by Benjamin Vison
Girish P
I dont know much about PHP, i am posting generic CURL statement that will be hlepful to understand.
  • Use Username and passwords to login to saleforce and get the access token, which when appended with REST calls to salesforce will give data back.For this someone has to create an App inside Salesforce whic will provide client secret and ID
curl https://<instance>.salesforce.com/services/oauth2/token -d "grant_type=password" -d "client_id=myclientid" -d "client_secret=myclientsecret" -d "mylogin@salesforce.com" -d "password=mypassword123456"

This will return JSON format data which will contain acceess_token to be used for further calls. and than use REST URL as follows

curl https://instance_name.salesforce.com/services/data/v38.0/ -H "Authorization: Bearer "THIS_IS_THE_ACCESS_TOKEN_RECEIVED_EARLIER>"
note - https://instance_name.salesforce.com/services/data/v38.0/  is the REST endpoint, i you have REST endpoints for salesforce you can replaces it as needed.