+ Start a Discussion
Ghulam Murtaza 5Ghulam Murtaza 5 

i am a newbie to salesforce and trying to complete this trailhead challenge and unable to find a way through apex to generate this method for creating new contacts with unique id. as one requirement to pass the challenge is "The 'generateRandomContacts' method must be capable of consistently generating contacts with unique first names."

If somebody successfully completed the task kindly help me.

Best Answer chosen by Ghulam Murtaza 5
Ghulam Murtaza 5Ghulam Murtaza 5
hi pankaj,
i have completed the task somehow. my friend completed it with a simple code i.e. 
public class RandomContactFactory{
   public static List<Contact> generateRandomContacts(integer n,string lastname){
       integer n1= n;
       list<contact> c=[select  FirstName from contact limit : n1];
       return c;

but for me it was giving error of class not created as static or either the method is not returning the first name. so for me it worked as follows:

public class RandomContactFactory{

    public static List<Contact> generateRandomContacts(integer n,string LastName){
    integer n1=n;
    List<contact> c1 = new list<contact>();
    list<contact> c2 =new list<contact>();
     c1 = [select FirstName from Contact Limit : n1];
     integer i=0;
     for(contact cnew : c1){
     contact cnew1 = new contact();
     cnew1.firstname = cnew.firstname + i;
    return c2;

Please help me ,

 I create new formula field ( Data type is Number ) for calculate value from text field but system not allow me to calculate it. Do you have any suggest me ?


Best Answer chosen by Admin (Salesforce Developers) 
Ritesh AswaneyRitesh Aswaney

Use the VALUE function


Converts a text string that represents a number to a number
Timothy SmithTimothy Smith 
I am receiving the error:
Unexpected file found in package directory:
When I try to deploy a class that I have just created.  The file is saved in the /force-app/main/default/classes/Case_Trigger_Alert_Count.

I have also noticed that in the 'Problems' tab, I have the message:
The sourcepath ".../force-app/main/default/classes/Case_Trigger_Alert_Count" is not a valid source file path.  SourcePathInvalid [1,1]

The filename of the file I have just created and attempting to deploy is 'Case_Trigger_Alert_Count"
What am I missing to be able to deploy to my Sandbox?
Best Answer chosen by Timothy Smith

Ingeneral classes ends with .cls extension. Make sure you have that. Also every class should have meta xml file associated with it. 

For example
public with sharing class SampleClass {
// some code

<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">

Make sure you class has all these.

James Kacerguis 5James Kacerguis 5 
I currently have apex class in lightning component that is getting a specific Queue Id to assign as owner of the record the component is launched from.

This is the current  way I'm getting the id, but I'm guessing there is a better way to do this, any ideas?
Group marketingQueue = [SELECT id,Name FROM Group WHERE Type = 'Queue' and DeveloperNAME = 'MarketingProspectLeads'];
         	ID marketingQueueId = marketingQueue.id;
            //l.OwnerId = UserInfo.getUserId();
            l.OwnerId = marketingQueueId;

I just need to make sure this can't break so I'm assuming I should add some error checking or be doing this a different way.  Thanks in advance.  
Best Answer chosen by James Kacerguis 5
Hi James,
If you don't require Name then you can modify your query as follows to reduce number of lines in code and add NULL check before assignment to avoid code break.
ID marketingQueueId = [SELECT id FROM Group WHERE Type = 'Queue' and DeveloperNAME = 'MarketingProspectLeads'].Id;

if(marketingQueueId != NULL) {
    l.OwnerId = marketingQueueId;

Kindly mark as resolved if you find this anser helpful. 
James Kacerguis 5James Kacerguis 5 
Hello All,
I'm extremely new to lightning components and trying to replace some of our custom javascript buttons with lightning compatible options.  One button takes ownership of a lead.  I found a post that does something similar for cases and tried to modify it for my purpose: https://learnownlightning.blogspot.com/2018/01/change-owner-update-record-using.html

It seems to be doing the record update based on apex code, but it launches a quickaction screen with a cancel button that doens't go away.  I've seen it posted that you can use 
It is not working for me.  I'm not sure if I'm not puting that code in the right place but I'm hoping someone can help me figure out a way to click the quick action button, have the lead change ownership, and that's it.

Here is my code so far:
<aura:component implements="force:lightningQuickAction,force:hasRecordId" controller="LightningComponent_MoveToMarketing" access="global" >
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>    
 doInit : function(component, event, helper) {
        var leadId = component.get("v.recordId");
        var action = component.get("c.changeOwnerMethod");
            leadId : leadId
        action.setCallback(this, function(response) {
            if(response.getState() === "SUCCESS") {
                console.log("Lead Owner Changed To Current login User");
             var rec = response.getReturnValue();

Apex Class:
public class LightningComponent_MoveToMarketing {

    public static Lead changeOwnerMethod(Id leadId) {
        if(leadId != null) {
            Lead l = [SELECT OwnerId FROM Lead WHERE Id = :leadId];
         l.OwnerId = UserInfo.getUserId();
//update case Ownerid with loggedin userid.
            update l;
            return l;
        return null;


Any ideas?
Best Answer chosen by James Kacerguis 5

inside the callback function. It should be good then.

Your controller should be like this.
 doInit : function(component, event, helper) {
        var leadId = component.get("v.recordId");
        var action = component.get("c.changeOwnerMethod");
            leadId : leadId
        action.setCallback(this, function(response) {
            if(response.getState() === "SUCCESS") {
                console.log("Lead Owner Changed To Current login User");
             var rec = response.getReturnValue();


Please mark it solved if this is working for you.


I set up a CMS connection in my Community.
I used these settings:
CMS Source: Drupal
Connection type public:
Server URL: https://drupdemoeight8wnpr4ekpl.devcloud.acquia-sites.com

Content list: 
- Name: List
- Path: content/rest?_format=json
- Node Path: nothing

When using the component CMS Connect JSON with the default values I see: "The server returned code HTTP 0"

I can confirm that my Rest service is well configures by testing it with Postman or even directly in the browser:

Any idea of what is wrong or how I could debug that?

Can we test the CMS connection?


Best Answer chosen by LaurentDelcambre
I can answer my own question:
I needed to enable CORS in the Drupal site:

Then add the Drupal site to the Remote Site settings in Salesforce

A good blog post:

I must be missing something..


The date is always 1 day behind when formating like so:


datetime xDate = o.campaign_start_date__c;
String xxDate = xDate.format('yyyy-dd-MM');
system.debug('sdate :' +xxDate);


I set the above field to 8/16/2011


and in debug it shows up as: 2011-15-08


Everytime I change it the debug value is shown as 1 day behind.. Im sure I could to +1, but could someone help me understand why this is happening?


Jacob Davis

Best Answer chosen by Admin (Salesforce Developers) 
Shashikant SharmaShashikant Sharma

This  is campaign_start_date__c  datetime field . And your users time zone must be such that GMT - some hours, so that GMT Offset makes a day less.


Try this


Datetime localTime = o.campaign_start_date__c.Date();
localTime = localTime.addHours(o.campaign_start_date__c.hour());
localTime = localTime.addMinutes(o.campaign_start_date__c.minute());
localTime = localTime.addSeconds(o.campaign_start_date__c.second());

String xxDate = xDate.format('yyyy-dd-MM');
system.debug('sdate :' +xxDate);


Puneet KhoslaPuneet Khosla 
I am getting this error when trying to do the "Lightning Experience Rollout Specialist"

The AccountTab Visualforce page does not include one or both of the following: the apex:slds tag in the page, or the slds-table value in the table.

My code is as follows:
<apex:page standardStylesheets="false" standardController="Account" recordSetVar="accounts" tabStyle="account" applyHtmlTag="false" applyBodyTag="false" showHeader="false">
       <apex:slds />
    <div class="slds-scope">     
        <table class="slds-table">
    			<tr class="slds-text-title_caps">
      				<th scope="col">
        				<div class="slds-truncate" title="{!$ObjectType.Account.Fields.Name.Label}">{!$ObjectType.Account.Fields.Name.Label}</div>
    			<apex:repeat value="{!accounts}" var="a">
                  <td data-label="Account Name">
                    <div class="slds-truncate" ><apex:outputLink value="{!URLFOR($Action.Account.View, a.id)}">{!a.name}</apex:outputLink></div>
     <div class="slds-scope">
        <apex:pageBlock >
            <apex:pageBlockTable value="{!accounts}" var="a" styleClass="slds">
                <apex:column headerValue="{!$ObjectType.Account.Fields.Name.Label}">
                    <apex:outputLink value="{!URLFOR($Action.Account.View, a.id)}">{!a.name}</apex:outputLink>

Best Answer chosen by Puneet Khosla
Puneet KhoslaPuneet Khosla
Looks like I figured out.

styleClass="slds-table" needs to be added to pageBlockTable

We have a class and trigger in place which is now producing the error listed below. It is referencing an Apex Class and an Apex Trigger of where the issue is stemming from. 

Can someone help me figure out how I can correct this? 

Thank you!
Apex script unhandled trigger exception by user/organization: 005A0000005XYZb/00DA0000033432M

triggerUpdAssignedLead: execution of BeforeUpdate

caused by: System.Exception: Too many SOQL queries: 101

Class.LeadTrigger.<init>: line 47, column 1
Trigger.triggerLead: line 3, column 1

Line 47  of the Class.LeadTrigger can be found in this class code below:  
for(User u : [Select Id, UserType, Contact.AccountId, Contact.Account.Member__c, Exclude_from_Zip_Placement__c From User Where isActive = true]){
public without sharing class LeadTrigger {
    //private static boolean alreadyExecuted = false;
    Private Set<String> OpenLeadStatus = new Set<String>{'Awaiting Decision','Initiating Contact','New', 'Quoting', 'Re-Engaged', 'Job Take'};
    Private String QuotingStatus = 'Quoting';
    Private String QuotingCampaignNumber = '34099';
    Private static String MODELER_LEAD = 'Modeler Lead';
    Private static String HOW_LEAD = 'Show Lead';
    Private static String STATUE = 'Statue';
    public static String ClosedStatus = 'Closed By EF';
    public static String ProjectDelayedStatus = 'Project Ending';
    //public static boolean isTest {get; set;}
    //public static boolean isTestUpdateLead {get; set;}
    public static boolean isUpdateLeadStatus {get; set;}
    public static boolean isUpdateHistoryLog {get; set;}
    //New class variable creatd for optimization - 10/2016
    //Prevent SOQL Query governor limit exception
    private Map<String,Id> recTypes = new Map<String,Id>();
    private final string queueInsideSalesId;
    private final string dummyCampaignId = null;
    private Map<Id, User> activeUsers = new Map<Id, User>();
    private Set<Id> excludedZipAssignUsers = new Set<Id>();
    //Creating class constructor to initialize class objects - 11/2017
    //Prevent SOQL Query governor limit exception
    public LeadTrigger(){
        //Retrieving RecordType information
        for(Schema.RecordTypeInfo rt : Lead.SObjectType.getDescribe().getRecordTypeInfos()){
            String rtName = rt.getName();
            if((rtName == MODELER_LEAD)||(rtName == SHOW_LEAD)){ 
                recTypes.put(rtName, rt.getRecordTypeId());
        //Retrieving values for the Lead Assignment - AssignLeads() method
        //Retrieving the default owner (Inside Sales Queue)
        for(QueueSobject queue : [Select QueueId From QueueSobject Where SobjectType = 'Assigned_Lead__c' and Queue.Name = 'Inside Sales']){
            queueInsideSalesId = queue.QueueId;
        //Retrieving Dummy Campaign ID for Assigning New Leads to a Campaign
        for(Campaign c : [Select Id, Campaign_Number__c From Campaign Where Name Like '%Dummy%' Limit 1]){
            dummyCampaignId = c.Id;
        // Retrieving Active Users List for Lead Assignment
        for(User u : [Select Id, UserType, Contact.AccountId, Contact.Account.Member__c, Exclude_from_Zip_Placement__c From User Where isActive = true]){
            //Retrieving Users excluded by Zip Assignment
            if(u.Exclude_from_Zip_Placement__c ==  true){
                activeUsers.put(u.Id, u);

This is the ApexTrigger code named referenced in the apex error code: 
Trigger.triggerLead: line 3, column 1
trigger triggerLead on Lead (after insert, before insert, before update, after update) {

    LeadTrigger lt = new LeadTrigger();
    if (Trigger.isInsert)
        lt.LeadInsertion(Trigger.New, Trigger.isBefore, Trigger.isAfter);
    else if (Trigger.isBefore)
        lt.LeadUpdate(Trigger.New, Trigger.old, Trigger.isBefore);
    if (Trigger.isAfter) {
      lt.ReassignALOnClosedLeads(Trigger.New, Trigger.old, null);
      lt.AddToCampaign(Trigger.New, Trigger.oldMap);
      lt.ProcessQuotingLeads(Trigger.New, Trigger.old);
    } else 
      lt.PopulateAmbassador(Trigger.New, Trigger.old);   
    // 10/22/2015 Ambassador enhancement Tia Xuan 
    if (Trigger.isBefore && Trigger.isUpdate){
      lt.CopyHistoryLog(Trigger.new, Trigger.oldMap);   

Best Answer chosen by HNT_Neo
Deepali KulshresthaDeepali Kulshrestha
Hi JH_Neo,

Greetings to you!

The following error appears when you exceed the Execution Governors Limit (you can run up to a total 100 SOQL queries in a single call or context). 

System.LimitException: Too many SOQL queries: 101 error

-Avoid SOQL queries that are inside FOR loops.

Try this code from line 47 in Class:
List<User> userList= [Select Id, UserType, Contact.AccountId, Contact.Account.Member__c, Exclude_from_Zip_Placement__c From User Where isActive = true];
for(User u : userList){
            //Retrieving Users excluded by Zip Assignment
            if(u.Exclude_from_Zip_Placement__c ==  true){
                activeUsers.put(u.Id, u);


All the SOQL queries in triggers fired from one call or context will be counted against the limit of 100.
Salesforce cannot disable or raise the Governors Limit.

Resolve the "Too many SOQL queries: 101" error
To fix the issue, change your code so that the number of SOQL fired is less than 100.

If you need to change the context, you can use @future annotation which will run the code asynchronously.

Best practices to avoid exceeding the Governors Limit
Since Apex runs on a multi-tenant platform, the Apex runtime engine strictly enforces limits to ensure code doesn't monopolize shared resources.

-Avoid SOQL queries that are inside FOR loops.
-Follow the key coding principals for Apex Code in our Developer's Guide.
-Review our best practices for Trigger and Bulk requests:
-Best practices for Triggers and Bulk requests (Force.com Apex Code Developer's Guide)

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

I got following error on step 3.

Challenge Not yet complete... here's what's wrong: 
Couldn’t find Agency records from the Account object.

Can anyone pass this step?
Thanks in advance.

Best Answer chosen by LinThaw
Hi Jennifer and ankita,

Please refer below, I passed this step 3.

fig 1.
User-added image

fig 2.
User-added image

and create Top 5 Agencies lenses.