+ Start a Discussion
Rory McDonnellRory McDonnell 
Hi I have created the following Trigger that creates ten opportunities when an account has more than 99 employees. It is working as expected and the opps are being created, only issue is that they are not being linked to the account record. Any idea why that is the case?
 
trigger CreateTenOpps on Account (before insert, before update) {
    
    List<Opportunity> TenOpps = New List<Opportunity>();
    
    for (Account acc : Trigger.new) {
        if (acc.NumberOfEmployees > 99) {
            for (Integer i = 0; i < 10; i++) {
                Opportunity opp = New Opportunity(CloseDate = date.today(), 
                                                  StageName = 'Prospecting', 
                                                  Name = 'Trigger Opp',
                                                  AccountId = acc.Id);
                TenOpps.add(opp);
            }
            insert TenOpps;
        }
    }

}

 
Best Answer chosen by Rory McDonnell
Danish HodaDanish Hoda
Hi Rory,
Before update will work, but it is recommended to work on After trigger events when you are working on other related/un-related records.
Rory McDonnellRory McDonnell 
Hi I am somewhat of a novice when it comes to apex and can't seem to work out what the problem is with line 7 of my code. I am building a practice trigger that creates 10 identical opportunities whenever an account has more than 99 employees.

I think I have set up the for loop correctly but in the developer console 'Problem' there are a number of messages on line 7
- Expecting ';' but was a '<'
- Expecting ';' but was a ','
- Expecting ';' but was a ')'

Any suggestions?
trigger CreateTenOpps on Account (before insert) {
    
    List<Opportunity> TenOpps = New List<Opportunity>();
    
    for (Account acc : Trigger.new) {
        if (acc.NumberOfEmployees > 100) {
            for (Integer i = 0, i < 10, i++) {
                Opportunity opp = New Opportunity(CloseDate = date.today(), 
                                                  StageName = 'Prospecting', Name = 'Trigger Opp');
                TenOpps.add(opp);
            }
            insert TenOpps;
        }
    }

}

 
Best Answer chosen by Rory McDonnell
Maharajan CMaharajan C
Hi Rory,

In Line no: 7   you have to use the Semi Colon " ; "  don't use the comma in for loop.

trigger CreateTenOpps on Account (before insert) {
    
    List<Opportunity> TenOpps = New List<Opportunity>();
    
    for (Account acc : Trigger.new) {
        if (acc.NumberOfEmployees > 100) {
            for (Integer i = 0; i < 10; i++) {       /// use the Semi colon here .
                Opportunity opp = New Opportunity(CloseDate = date.today(), 
                                                  StageName = 'Prospecting', Name = 'Trigger Opp');
                TenOpps.add(opp);
            }
            insert TenOpps;
        }
    }

}

Thanks,
Maharajan.C  
Sarah PaulsonSarah Paulson 

Hello, I wrote a trigger to check if the url = 'https://sig-cb--Full.cs88.my.salesforce.com' and the profile of the current user is a specific profile (SIG-FSM-Super User) and if so the trigger shows an error message and also an image which I included in the addError function, it looks like this:

trigger ContactCreationForServiceMaxUsers on Contact (Before insert) {
   
       String baseURL = String.valueof(URL.getSalesforceBaseUrl());
      
       system.debug('<<baseURL>>' + baseURL);
       Boolean isBaseURL = baseURL.contains('https://sig-cb--Full.cs88.my.salesforce.com');
       System.debug(' >> String.valueof(URL.getSalesforceBaseUrl()) >>'+baseURL ); 
       User currentUser = [SELECT Id, Profile.Name FROM USER WHERE Id =:UserInfo.getUserId()]; 
      
       Contact c = new Contact(); 
      
       System.debug(' >> isBaseURL >>'+isBaseURL ); 
       System.debug(' >> currentUser.Profile.Name>>'+currentUser.Profile.Name ); 
   
     for(Contact c : Trigger.New){ 
          if(isBaseURL == TRUE  && currentUser.Profile.Name == 'SIG-FSM-Super User'){
           c.addError(' <p style="color:red; font-size: 20px;">Service contact creation is only allowed from “Account” tab using the blue button “Create Contact” after selecting a account”</p><img id="theImage" src="https://sig-cb--full--c.cs88.content.force.com/servlet/servlet.FileDownload?file=0159E0000002tNp" width="850px" height="100px" alt="Description of image here"/> ', false); 
          } 
     } 
}


Can anyone help me with how to build the test class for the trigger? At least theoretical.

1. First I need to create a contact
2. I need to create a user with a profile = 'super-user'
3. somehow i need to check the addError function..

Something like this...

Best Answer chosen by Sarah Paulson
Maharajan CMaharajan C
Hi Sarah,

Please use the below test class:
 
@isTest
public class ContactCreationForServiceMaxUsersTest {
    
    Static testmethod void ServiceMaxUserstest(){
        Profile p = [SELECT Id FROM Profile WHERE Name='SIG-FSM-Super User'];
        User UserObj= new User(Alias = 'Test', Email='SIGFSMSuper@testorg.com',
                               EmailEncodingKey='UTF-8', LastName='SIGFSMSuper', LanguageLocaleKey='en_US',
                               LocaleSidKey='en_US', ProfileId = p.Id,
                               TimeZoneSidKey='America/Los_Angeles', UserName='SIGFSMSuper@testorg.com');
        insert UserObj;
		System.runAs(UserObj) {
        // Add the mandatory fields to create the contact record in below line.
        Contact c = new Contact(LastName ='Test Contact',Email='SIGFSMSuper@testemails.com');
        Database.SaveResult result = Database.insert(c, false);
		}
        
    }
}



Thanks,
Maharajan.C
Rory McDonnellRory McDonnell 
Hi I am learning how to build triggers and am trying to do the following.

When a new lead is created with a specific company name, update two fields on the lead record and also create a new task. 

My understanding is that since it is a new record I would need to use an AFTER INSERT trigger as the task will need the newly created lead ID as a reference in the WhatID. But seeing as I also need to update fields on the lead record it doesn't seem that the After Insert will allow that.

Am I stuck with choosing between a Before Insert so I can update my lead record, and an After Insert if I want to create a task.

I'm pretty sure there is a simple solution but still very new to Apex.
Best Answer chosen by Rory McDonnell
Danish HodaDanish Hoda
hi Rory,
Please refer below code:
trigger LeadTrigger on Lead (after insert,before insert) {
	
	if(Trigger.isInsert){
		List<Task> tasks = new List<Task>();
		for(Lead leadObj : Trigger.New){
			if(trigger.isBefore){
				//set the field values you want
			}
			if(trigger.isAfter){
				//create Task as below
				Task taskObj = new Task(WhoId = leadObj.Id, ..set other task fields..);
				tasks.add(taskObj);
			}
		}
	}
	if(!tasks.isEmpty())	insert tasks;
}

 
Oscar FigueraOscar Figuera 
Hello community!

I know there are like a thousand posts related to this challenge. But none of those seem to have a trustable answer and we can find several discrepances between all posts, questions and answers. This is just me trying to figure out whats actually wrong with this.

The error message: Challenge Not yet complete... here's what's wrong: 
The Fulfillment Creation process does not appear to be working properly. Please check that your task was created with all of the field values set appropriately.

I condensed all the inmediate actions in One Node, since that's what i tought I had to do. I've read in different threads about people having two and people using one.
User-added image

User-added image

Now the record updates

User-added image
User-added image

And the Task, where it's supossed to be failing according to the error message...
User-added image
I just don't know where is the problem, it could be only a field reference that is wrong or the entire process (I hope not).

Thanks for the answers and the help!
Best Answer chosen by Oscar Figuera
NagendraNagendra (Salesforce Developers) 
Hi Figuera,

sorry for this issue you are encountering.

May I suggest you please check with below threads from the forums community with a suggested solution, and compare your work with the same. Hope this helps.

Thanks,
Nagendra
sanjusfdcsanjusfdc 
Hi All,
Help me on this, i want using validation rule "Dealer user cannot save if the selected picklist value in Status field in "Inquiry" record type in Case is "Uploaded".
Best Answer chosen by sanjusfdc
Prakash NawalePrakash Nawale
sanjusfdc,

Use below code in validation rule to prevent creating of Case record based on your requirments.
 
AND(
           $RecordType.DeveloperName='Inquiry',
            $User.Username = 'Dealer username',
            ISPICKVAL( Status , 'Uploaded') 
)

Please like the answer and mark it as best if this helps.
Kahlil DozierKahlil Dozier 
In Objective C, I follow the steps as outlined here and it works fine: https://developer.salesforce.com/docs/atlas.en-us.noversion.mobile_sdk.meta/mobile_sdk/ios_rest_apis_using_methods.htm?search_text=forceios

But when following the same steps translating the code into Swift, I run into an issue with the SFRestRequest initializer, whose signature is below:
 
Public convenience init(method: SFRestMethod, path: String, queryParams: [String : String]?)

As you can see, queryParams takes a Swift Dictionary with a key and value of the String type.  But when you follow the example, it seems you end up with a Dictionary with a key of the String type and value of the Dictionary type; and thus we have a type mismatch.

This doesn't seem to be a problem in Objective C, because upon inspection of the method signature in SFRestRequest.m, queryParams appears to be able to take a generic NSDictionary: 
 
+ (instancetype)requestWithMethod:(SFRestMethod)method path:(NSString *)path queryParams:(NSDictionary *)queryParams

For reference here is the Swift code I'm trying out:
 
//build the queryParams dictionary from a JSON String
let body: String = "{ \"body\" :{\"messageSegments\" :[{ \"type\" : \"Text\",\"text\" : \"My Comment\"}]}}"
        let queryParams = SFJsonUtils.objectFromJSONString(body) as! [String:AnyObject] 
//construct and send the request
        let request = SFRestRequest(method: SFRestMethod.POST, path: "/services/data/v36.0/connect/communities/my_community_ID/chatter/feed-elements/my_element_ID/capabilities/comments/items", queryParams: queryParams as? [String:String])
        SFRestAPI.sharedInstance().send(request, delegate: self)

But unwrapping queryParams fails and resolves to nil.  Trying to forcefully cast queryParams to [String:String] does not work either, and just causes a crash.

How might I get around this?
 
Best Answer chosen by Kahlil Dozier
Kahlil DozierKahlil Dozier
So what I did was to follow the directions outlined in http://stackoverflow.com/questions/24002369/how-to-call-objective-c-code-from-swift to create an Objective-C file that my Swift code could call.  

Below are my Objective-C interface/implementation files:

SFRestRequestSending.h:
 
//
//  SFRestRequestSending.h
//

#import <Foundation/Foundation.h>
#import <SalesforceRestAPI/SalesforceRestAPI.h>
#import <SalesforceSDKCore/SalesforceSDKCore.h>
/*This is an Objective-C wrapper class that exists to allow swift classes to use the requestWithMethod:path:queryParams: method of the SFRestRequest class whenever we have a non-nil value for queryParams.  Currently, this method plays fine accepting generic NSDictionaries in Objective-C, but requires a Dictionary specifically typed [String:String] in Swift.  This might be a bug in the SalesforceRestAPI framework, because we need to pass generic swift dictionaries to this method to form some requests.*/
@interface SFRestRequestSending : NSObject

@property(nonatomic,strong) SFRestRequest* restRequest;
/*
 parameter "method" is an NSInteger which refers to the http request method:
 
 GET = 0
 POST = 1
 PUT = 2
 DELETE = 3
 HEAD = 4
 PATCH = 5 */

//standard SFRestRequest
-(id)initWithMethod:(NSInteger)method path:(NSString*)path queryParams:(NSDictionary*)queryParams;

 SFRestRequestSending.m:
 
//
//  SFRestRequestSending.m
//

#import "SFRestRequestSending.h"
#import "My_Project_Name-Swift.h"

@implementation SFRestRequestSending

-(id)initWithMethod:(NSInteger)method path:(NSString *)path queryParams:(NSDictionary *)queryParams{
    self = [super init];
    if(self){
        self.restRequest = [SFRestRequest requestWithMethod:method path:path queryParams:queryParams];
    }
    return self;
}
@end

Replace "My_Project_Name" with the name of your Xcode project, as specified in the stack overflow directions. 

Then, from swift, I would call this class like:
 
//compose and execute a GET request
let requestWrapper = SFRestRequestSending(withMethod: 0, path: myPath, queryParams: paramDict);

let request = requestWrapper.restRequest;

SFRestAPI.sharedInstance().send(request, delegate: myDelegate);

 
LinThawLinThaw 
Hi,

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.

Regards,
LinThaw
Best Answer chosen by LinThaw
LinThawLinThaw
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.

Regards,
LinThaw
kavya mareedukavya mareedu 
Modify an AppExchange dashboard
Maria Jimenez is looking for reports and dashboards on AppExchange to track her team's transition to Lightning Experience. Install the AppExchange Dashboard Pack for Sales, Marketing and Service package into your Trailhead Playground and make some modifications. 

You’ll need your hands-on org username and password to complete this challenge. If you're using a Trailhead Playground, this article shows you how to find your username and reset your password. If you have trouble installing the package, follow the steps in this article.

In your Trailhead Playground, install the AppExchange Dashboard Pack for Sales, Marketing and Service.
Clone the 1-Account, Contact & Opportunity Data Quality dashboard and name it My Account and Contact Dashboard.
Add a dashboard filter on the Billing City field so that the dashboard only shows info about Accounts in London.
Save and refresh the dashboard.

I am trying to complete this challenge from past 4 hours still am not able to do it. Please help me guys! Guide me!!!!
Best Answer chosen by kavya mareedu
Murali MattaMurali Matta
Hi Kavya,

Please uninstall the Package and install the package again.

1.At the time of Installation please install for "For All Users"
2. Once the Installation is done. goto Reports folder you can see "6 - Data Quality Analysis" and clone the User-added image
3. And Click on "1-Account, Contact &Opportunity Data Quality". Where you can see the screen click on "Clone" button and "Save"  and Save to
"My Personel Dashboard"User-added image
Please use the below screen short.
User-added image

4. After Saving goto "My Personel Dashboards" and see for "My Account and Contact Dashboard" and edit and click on "Add Filter". Please add the following criteria as inthe screen shots. 
User-added image 

5. Once done click on 'ok' and click on 'Save'. 

I hope it helps you.

Thanks,
Murali
Michael MMichael M 
Hello, I have a process builder set up that posts a chatter notification to the Owner of the Lead when a certain custom field gets updated. How can I @mention that user in the body of the chatter post FROM process builder? The reason I need to do so is because I want the user to receive an alert (both a bell on the chatter and an email) when this chatter post gets posted?  FYI the person is always the User-Owner of the Lead record. Your help is greatly appreciated. 
Best Answer chosen by Michael M
AbhishekAbhishek (Salesforce Developers) 
Hi Michael,

You can go through the below blogs which might answer your query,

https://automationchampion.com/tag/mention-related-user-in-a-post-to-chatter-action-process-builder-salesforce/

https://jenwlee.com/2017/12/12/automate-chatter-post-that-mentions-several-users/

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

Thanks.