• LBK
  • PRO
  • 3158 Points
  • Member since 2015

  • Chatter
    Feed
  • 85
    Best Answers
  • 0
    Likes Received
  • 19
    Likes Given
  • 0
    Questions
  • 598
    Replies
I am Trying to create a report on Object__c. So I am trying to use user custom field(projectName__c) value in custom object field(projectName__c) in filter in Reports.

For that, I got a suggestion to do like below, and filter with Boolean.

Create a formula field in the custom object which is checkbox type and formula will be IF(projectName__c=user.projectName__c,true,false)

And create a report where apply filter forumulaField__c = true.

So, This is working fine. But When I change projectName__c, The all same projectName__c record's will be updated. If I change it to another project again records will be updated. I will have 10 Lakhs records in my application, presently I am using developer account.

Does This updating on 10 lakhs records meets any governor limits?

This help will be very Glad.

Thank you.
Hi,

Have a question, please help.


I am trying to insert a record and relate it to existing record. For example, if we want to insert a contact relating to existing Account, then we would write as follows:

Contact con = new Contact(LastName = 'Rahul');
con.AccountID = //here account ID will go
insert con;

My first question is, why the below code does not work(that is, it relates contact and Account, but does not show the same on UI, Account field is blank on Contact)

Contact con = new Contact(LastName = 'Rahul);
con.Account = //Account Object reference here.
insert con;

My second question is: lets say we have two custom objects Job Application and position, in which position is master object. Then how do we insert Job application object related to existing position. below code does not work for me:


Job_Application__c job = new Job_Application()
job.position__r = //position object reference here.
insert job;

this code does create job applicaton object but does not relate it to position object.

PLEASE HELP


best Reagrds,

Rahul SIngh Rana
hello,

I'm hoping someone can help me out on this issue. 
A while back I created this apex trigger that would update a record from the account and a custom ojbect when 3 variables were present. 

However, I noticed that new records were not being entered but only udpated. 

Can someone tell me how I would modify my code so that if a new record is identified it will create a new record and update the existing record? 
 
trigger CAPdataTiers on CAPdata__c (before insert,before update) {
    for (CAPdata__c CAP : Trigger.new) {
        if(CAP.Volume_Market__c.equalsIgnoreCase('A') && 
           CAP.Region_Program_Requirements__c != null && 
           CAP.Region_Program_Requirements__c.equalsIgnoreCase('Midwest'))
        {    //Midwest Market A
            CAP.TierElitePreferredJobs__c = 36; 
            CAP.TierElitePreferredRV__c = 90000;
            CAP.TierElitePreferredL6MosTA__c = 90;
            CAP.TierElitePreferredL6MosDA__c = 90;
            CAP.TierPreferredJobs__c = 24; 
            CAP.TierPreferredRV__c = 60000;
            CAP.TierPreferredL6MosTA__c = 75;
            CAP.TierRewardsAdvantageJobs__c = 12;
            CAP.TierRewardsAdvantageRV__c = 30000;
            CAP.TierRewardsAdvantageL6MosTA__c = 75;
        }
        else if(CAP.Volume_Market__c.equalsIgnoreCase('B') &&
           CAP.Region_Program_Requirements__c != null && 
           CAP.Region_Program_Requirements__c.equalsIgnoreCase('Midwest'))
        {    //Midwest Market B
            CAP.TierElitePreferredJobs__c = 18; 
            CAP.TierElitePreferredRV__c = 45000;
            CAP.TierElitePreferredL6MosTA__c = 90;
            CAP.TierElitePreferredL6MosDA__c = 90;
            CAP.TierPreferredJobs__c = 12; 
            CAP.TierPreferredRV__c = 30000;
            CAP.TierPreferredL6MosTA__c = 50;
            CAP.TierRewardsAdvantageJobs__c = 6;
            CAP.TierRewardsAdvantageRV__c = 15000;
            CAP.TierRewardsAdvantageL6MosTA__c = 25;
        }
        else if(CAP.Volume_Market__c.equalsIgnoreCase('A') &&
           CAP.Region_Program_Requirements__c != null && 
           CAP.Region_Program_Requirements__c.equalsIgnoreCase('Northeast'))
        {    //Northeast Market A
            CAP.TierElitePreferredJobs__c = 36; 
            CAP.TierElitePreferredRV__c = 90000;
            CAP.TierElitePreferredL6MosTA__c = 75;
            CAP.TierElitePreferredL6MosDA__c = 90;
            CAP.TierPreferredJobs__c = 24; 
            CAP.TierPreferredRV__c = 60000;
            CAP.TierPreferredL6MosTA__c = 50;
            CAP.TierRewardsAdvantageJobs__c = 12;
            CAP.TierRewardsAdvantageRV__c = 30000;
            CAP.TierRewardsAdvantageL6MosTA__c = 50;
        }
        else if(CAP.Volume_Market__c.equalsIgnoreCase('B') &&
           CAP.Region_Program_Requirements__c != null && 
           CAP.Region_Program_Requirements__c.equalsIgnoreCase('Northeast'))
        {    //Northeast Market B
            CAP.TierElitePreferredJobs__c = 18; 
            CAP.TierElitePreferredRV__c = 45000;
            CAP.TierElitePreferredL6MosTA__c = 75;
            CAP.TierElitePreferredL6MosDA__c = 90;
            CAP.TierPreferredJobs__c = 12; 
            CAP.TierPreferredRV__c = 30000;
            CAP.TierPreferredL6MosTA__c = 50;
            CAP.TierRewardsAdvantageJobs__c = 6;
            CAP.TierRewardsAdvantageRV__c = 15000;
            CAP.TierRewardsAdvantageL6MosTA__c = 25;
        }
        else if(CAP.Volume_Market__c.equalsIgnoreCase('A') &&
           CAP.Region_Program_Requirements__c != null && 
           CAP.Region_Program_Requirements__c.equalsIgnoreCase('Pacific Northwest'))
        {   //Pacific Northwest Market A
            CAP.TierElitePreferredJobs__c = 36; 
            CAP.TierElitePreferredRV__c = 90000;
            CAP.TierElitePreferredL6MosTA__c = 75;
            CAP.TierElitePreferredL6MosDA__c = 50;
            CAP.TierPreferredJobs__c = 24; 
            CAP.TierPreferredRV__c = 60000;
            CAP.TierPreferredL6MosTA__c = 50;
            CAP.TierRewardsAdvantageJobs__c = 12;
            CAP.TierRewardsAdvantageRV__c = 30000;
            CAP.TierRewardsAdvantageL6MosTA__c = 50;
        }
        else if(CAP.Volume_Market__c.equalsIgnoreCase('B') &&
           CAP.Region_Program_Requirements__c != null &&
           CAP.Region_Program_Requirements__c.equalsIgnoreCase('Pacific Northwest'))
        {    //Pacific Northwest Market B
            CAP.TierElitePreferredJobs__c = 18; 
            CAP.TierElitePreferredRV__c = 45000;
            CAP.TierElitePreferredL6MosTA__c = 75;
            CAP.TierElitePreferredL6MosDA__c = 50;
            CAP.TierPreferredJobs__c = 12; 
            CAP.TierPreferredRV__c = 30000;
            CAP.TierPreferredL6MosTA__c = 50;
            CAP.TierRewardsAdvantageJobs__c = 6;
            CAP.TierRewardsAdvantageRV__c = 15000;
            CAP.TierRewardsAdvantageL6MosTA__c = 50;
        }
        else if(CAP.Volume_Market__c.equalsIgnoreCase('A') && 
           CAP.Region_Program_Requirements__c != null &&
           CAP.Region_Program_Requirements__c.equalsIgnoreCase('South/West'))
        {   //South/West Market A
            CAP.TierElitePreferredJobs__c = 36; 
            CAP.TierElitePreferredRV__c = 90000;
            CAP.TierElitePreferredL6MosTA__c = 90;
            CAP.TierElitePreferredL6MosDA__c = 50;
            CAP.TierPreferredJobs__c = 24; 
            CAP.TierPreferredRV__c = 60000;
            CAP.TierPreferredL6MosTA__c = 75;
            CAP.TierRewardsAdvantageJobs__c = 12;
            CAP.TierRewardsAdvantageRV__c = 30000;
            CAP.TierRewardsAdvantageL6MosTA__c = 75;
        }
        else if(CAP.Volume_Market__c.equalsIgnoreCase('B') && 
           CAP.Region_Program_Requirements__c != null &&
           CAP.Region_Program_Requirements__c.equalsIgnoreCase('South/West'))
        {    //South/West Market B
            CAP.TierElitePreferredJobs__c = 18; 
            CAP.TierElitePreferredRV__c = 45000;
            CAP.TierElitePreferredL6MosTA__c = 90;
            CAP.TierElitePreferredL6MosDA__c = 50;
            CAP.TierPreferredJobs__c = 12; 
            CAP.TierPreferredRV__c = 30000;
            CAP.TierPreferredL6MosTA__c = 75;
            CAP.TierRewardsAdvantageJobs__c = 6;
            CAP.TierRewardsAdvantageRV__c = 15000;
            CAP.TierRewardsAdvantageL6MosTA__c = 75;
        }
    }
}

 
Hi everyone,

I have two objects: Segment Brief Tracking and Segment Category Mapping. I've created a trigger that is supposed to get the Segment Category Mapping ID that corresponds to the Segment Name from Segment Brief Tracking - mapped to Segment Name field on Segment Category Mapping.

I'm not getting an error but the Segment Category Mapping ID field is not being populated at all.

I've only started dabbling into Apex triggers so it'd be great to have an expert's opinion on how this trigger could be written better/why it's not working.

Thank you!
 
trigger SegmentBriefTracking_AddSegmentID on Segment_Brief_Tracking__c (before insert, before update) {

//Create a Set of all the Segment Names to be Uploaded

Set<String> SegmentNames = new Set<String>();

//Variable declaration

for (Segment_Brief_Tracking__c segbrieftrack : Trigger.new)
if(segbrieftrack.Segment_Name_For_Upload__c!=''){
SegmentNames.add(segbrieftrack.Segment_Name_For_Upload__c);}

//Map Segment Name for Upload to Segment Taxonomy Name

Map<String,Segment_Category_Mapping__c> mastersheet = new Map<String,Segment_Category_Mapping__c>([Select Id, Segment_Name__c FROM Segment_Category_Mapping__c WHERE Segment_Name__c IN :SegmentNames]);

//Add Segment Category Mapping ID to Segment Brief Tracking Record

for (Segment_Brief_Tracking__c segbrieftrack : Trigger.new)
if(segbrieftrack.Segment_Category_Mapping_ID__c!=null && segbrieftrack.Segment_Category_Mapping_ID__c!=''){
segbrieftrack.Segment_Category_Mapping_ID__c=mastersheet.get(segbrieftrack.Segment_Name_For_Upload__c).Id;}
}

 
The code coverage for the Trigger below is only 56%, trying to get it to atleast a 75%
 
Trigger GetInitialWeightValue on Appointments__c(after insert, after update) {
    Set<Id> accountIds = new Set<Id>();

    for (Appointments__c appt : trigger.new) {
        accountIds.add(appt.Patient__c);
    }

    //Elimnate the the accounts that don't have IDs for
    accountIds.remove(null);
    
//SOQL query that returns that initial weight value 
    if (!accountIds.isEmpty()) {
        List<Account> accountsToUpdate = new List<Account>(); 
        for (Account account : [
            Select Id,
                (
                    Select Scheduled_time__c, weight__c
                    From Dr_Chrono_appointments__r
                    WHERE Weight__c != NULL AND Status__c NOT IN ('Canceled', 'Cancelled')
                    Order by Scheduled_time__c ASC
                    Limit 1
                )
            From Account
            Where Id in :accountIds
        ]) {
           
            //Declare a decimal variable to store initial weight value 
            Decimal IW = NULL;
            
            // Get(0) to return the first element in the list value
            if (!account.Dr_Chrono_appointments__r.isEmpty()) {
                IW = account.Dr_Chrono_appointments__r.get(0).weight__c;
            }

            accountsToUpdate.add(new Account(
                Id = account.Id,
                initial_Weight__c = IW
            ));
            
        }   
        
        update accountsToUpdate;
        
        }
      }

Here is the testing class that I used:
 
@isTest
Private class InsertWeightToAppointment {

    @isTest static void InsertAppointment() {
        Account accnts = new Account();
        Appointments__c appt = new Appointments__c();
        Labs__c lb = new labs__c();
        
        appt.weight__c = 200;
        appt.scheduled_time__c = date.today();
        appt.patient__c = '00161000013cLIg';
        appt.status__c = 'Completed';
        
        insert appt;
        
        lb.value__c = 100;
        lb.Specimen_Received__c = date.today();
        lb.patient__c = '00161000013cLIg';
        lb.Observation_Description__c = 'LDL';
        
        insert lb;
               
        
        }
        
    @isTest static void UpdateAppointment() {
        Appointments__c appt = new Appointments__c();
        Labs__c lb = new labs__c();
        appt.id = 'a0A6100000UUBeK';
        appt.weight__c = 100;
        appt.scheduled_time__c = date.today();
        appt.patient__c = '00161000013bPD9';
        
        update appt;   
        
        lb.value__c = 180;
        lb.Specimen_Received__c = date.today()-30;
        lb.patient__c = '00161000013cLIg';
        lb.Observation_Description__c = 'LDL';
        lb.id = 'a0E61000005Pg21';
        
        update lb;
        
        }
     
}
Hello friends
I have a requirement as follows. I am explaining in detail.

I have a URL say https://ap2.salesforce.com?fanID=0032800000gufvJ  in salesforce.
based on this FanID I will get the email of that user.

Now I have a visualforce page with standard controller="fan__c"
<apex:inputText name="email>

In aex controller:
string fanid="Apexpages.currentpage().getparameter('fanID');
               if fanid != NULL
  string emaladdress=[select Email from fan__c where ID=:fanID];

Now value in emailaddress should be stored in <apex:InputText name=Email>

if the email already exists it should be replaced with asterisk as follows.
for example : assume email is  jose@gmail.com and if it exists for that particular ID then the contents of <apex:inputText> should be
j***@g****.com

If email doesnt exist for that  FanID   then contents of <apex:inputText> will contain   mary@yahoo.co.in

I am literaly struggling with this so any will be rewarded with points

thanks
krishna
Error: Compile Error: Variable does not exist: RestDocCallController at line 19 column 13 in ""apex class""
------------------CLASS----------------------

@RestResource(urlMapping='/DocAttachment/v1/*')

global with sharing class RestDocService {
    
    // Post method to decode the file and insert Attachment.
    @HttpPost
    global static String attachdoc(String encodedDoc){
        try {      
            RestRequest req = RestContext.request;
            Id callId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
            Blob pic ;//Blob variable to capture decoded image
            if(encodedDoc != null) {
                pic=EncodingUtil.base64Decode(encodedDoc);//Decode the base64 encoded image
            }
            Attachment attach = new Attachment (ParentId = callId,Body = pic,ContentType = 'text/plain',Name = 'Document Test');
            insert attach;
            return attach.Id;
        }catch(Exception e) {
            RestDocCallController.errorHandler(e);
            return null;
        }
    }



----------------------CONTROLLER---------------------

Error: Compile Error: Invalid type: Logger__c at line 112 column 32 ""Controller""

public class RestDocCallController {
    
    public Blob file{get;set;}
    public String accountId{get;set;}
    public String fileName{get;set;}
    public String result{get;set;}
    
    // Method called from Page
    public PageReference uploadDoc(){
        if(file != null && accountId != null){
            try {
                RestDocCallController restObj = new RestDocCallController();
                String result = restObj.restAuthSetting(accountId,file,fileName);
                if(result != null) {
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
                    return null;
                } else {
                    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));    
                }
            }catch(Exception e) {
                errorHandler(e);
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
                return null;
            }
            return null;
        }
        return null;
    }
    
     // Get Authorized and Post call to service class with JSON Body
    
    public String restAuthSetting(String accId,Blob file_body,String fileName) {
        try {
            String loginUrl = Label.Login_Url;
            String consumerKey = Label.App_Cosumer_Key;
            String consumerSecretKey = Label.Consumer_Secret_Key;
            String userName = Label.Org_UserName;
            String password = Label.Org_Password;
            
            
            Map<String, Object> oauth = oauthLogin(loginUrl,consumerKey,consumerSecretKey,userName,password);
            
            System.debug('oauth'+oauth);
                    
            String accessToken = (String)oauth.get('access_token');
            String instanceUrl = (String)oauth.get('instance_url');
            
            System.debug('instanceUrl'+instanceUrl);
            
            
            HttpRequest req = new HttpRequest();
            
            String bodyEncoded = EncodingUtil.base64Encode(file_body);
            
            req.setMethod('POST');
            
            req.setEndpoint(instanceUrl+'/services/apexrest/DocAttachment/v1/'+accId);
            req.setHeader('Authorization', 'Bearer '+accessToken);
            req.setHeader('Content-Type', 'application/json');
            req.setBody('{"encodedDoc":"'+bodyEncoded+'","fileName":"'+fileName+'"}');
            req.setTimeout(120000);
    
            Http http = new Http();
      
            HTTPResponse res = http.send(req);
    
            System.debug('BODY: '+res.getBody());
            System.debug('STATUS:'+res.getStatus());
            System.debug('STATUS_CODE:'+res.getStatusCode());
            
            return res.getBody();
        } catch(Exception e) {
            errorHandler(e);
            return null;
        }
    }
    
    // Method to get authorized using Connected Apps Client ID and Consumer Id.
    
     private static Map<String, Object> oauthLogin(String loginUri, String clientId,
        String clientSecret, String username, String password) {
        
        try {
            HttpRequest req = new HttpRequest();
     
            req.setMethod('POST');
            req.setEndpoint(loginUri+'/services/oauth2/token');
            req.setBody('grant_type=password' +
                '&client_id=' + clientId +
                '&client_secret=' + clientSecret +
                '&username=' + EncodingUtil.urlEncode(username, 'UTF-8') +
                '&password=' + EncodingUtil.urlEncode(password, 'UTF-8'));
        
            Http http = new Http();
      
            HTTPResponse res = http.send(req);
    
            System.debug('BODY: '+res.getBody());
            System.debug('STATUS:'+res.getStatus());
            System.debug('STATUS_CODE:'+res.getStatusCode());
            
            return (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
        }catch(Exception e) {
            errorHandler(e);
            return null;
        }
    }
    
     //Method used to log errors
    public static void errorHandler(Exception e) {
        
        Logger__c logger = new Logger__c();
        logger.Error_Line_Number__c = String.valueOf(e.getLineNumber());
        logger.Error_Body__c = e.getStackTraceString();
        logger.Error_Cause__c = e.getMessage();
        try {
            insert logger;
        }catch(Exception exp){
            System.debug(exp);
        }  
    }
}
How would I create a gross margin % trigger? Sample code would be great!
This is class
-------------------------------------------------------------------------
public class leaddup {

    public List<lead>ac{get;set;}
    public leaddup(){
    ac =[SELECT name,email FROM lead ];
    }
    public void getbyname(){
       ac=[SELECT name,count(Id) FROM lead GROUP BY name HAVING count(Id)>1];
    }
     public void getbyemail(){
       ac=[SELECT email,count(Id) FROM lead GROUP BY email HAVING count(Id)>1];
    }
}
--------------------------------------------------
This is vf
---------------------------------------------------------------------
<apex:page controller="leaddup">
    <apex:form >
        <apex:pageblock title="Duplicate lead">
            <apex:pageBlockButtons >
                <apex:commandButton value="based on name" action="{!getbyname}"/>
                <apex:commandButton value="based on email" action="{!getbyemail}"/>
            </apex:pageBlockButtons>
                    <apex:PageBlockTable value="{!ac}" var="a">
                        <apex:Column value="{!a.Name}"/>
                        <apex:Column value="{!a.email}"/> 
                    </apex:PageBlockTable>
               
        </apex:pageblock>
    </apex:form>
</apex:page>
I have a page layout named "User_ContactLayout" for Contact object.  I want to open this as a tab on my service console on click of a button  on the visual force page.
Hi Everyone,

I need a way determine if the accountNumber field contains -1. I got it work when -1 is the only value in the account number field. The formula needs to identify identify wether -1 is present the string (i.e. 11706-1). Not sure what else I need to do here.
 
IF(  CONTAINS("-1", Site) , BillingCity , 
IF(   NOT( CONTAINS("-1", Site) ), ShippingCity , 
IF(  CONTAINS("", Site)  , ShippingCity , BillingCity) ) )

 
Hello,


User-added image

I am creating a list button like above, 

Below is the thing i put in button
/001/e
&retURL=%2F001%2Fo
&cancelURL={!Opportunity.Id}
&ent=Account
In standard creation wizard for creation of Account:
​
The user has many record types to choose:

so the first URL appearing for record selection is like below:

https://axyz.cs82.my.salesforce.com/setup/ui/recordtypeselect.jsp
?ent=Account
&retURL=%2F001%2Fo
&save_new_url=%2F001%2Fe%3FretURL%3D%252F001%252Fo

Once the first record is selected, the URL is like below:

https://xyz.cs82.my.salesforce.com/
001/e
?retURL=%2F001%2Fo
&RecordType=012D0000000kZUw
&ent=Account

I want to have the same behavior for record selection:

Am i missing something in my button ?
  • April 19, 2017
  • Like
  • 0
I have a Picklist field on Case called Type with values 'Teacher Related, Policy Feedback, Curriculum Feedback' I have another field called Teacher_Name__c.  I need some help to write a validation rule so that if the user select the either 'Policy Feedback' or 'Curriculum Feedback' The teacher_name__c field should be made non editable and when the user choose 'Teacher Related' the Teacher_Name__c should be allowed to choose the teacher name.
  • April 18, 2017
  • Like
  • 0
I have the fields "Base_Price__c", Discount_Percentage__c, Discount_Amount__c.  I need to calculate the discounted price either by $ or percentage.  I need some help to write a formula to have either one discount or no discount, please help
  • April 18, 2017
  • Like
  • 0
Hi folks,

I put a custom button on Salesforce cases that both Accepts a case and checks whether it the case is owned by a User or Queue, and gives an error when one user tries to take the case from another User, and not from a Queue.

The trouble is this button only works if one user opens the case after another has accepted it.  But if both users open an unaccepted case, the button will unfortunately allow the case to first be taken by the first person and then the second, without alerting.

The code:
{!REQUIRESCRIPT("/soap/ajax/13.0/connection.js")}



if('{!Case.OwnerId}'.substring(0,3)=='005'){
alert("This case is owned by " +'{!Case.Case_Owner_s__c}'+" and is not in a Queue.");
} else 

{

var caseObj = new sforce.SObject("Case");
caseObj.Id = '{!Case.Id}';
caseObj.OwnerId = '{!$User.Id}';
caseObj.One_Stop_Counter__c = "{!TEXT($User.Assigned_Counter__c)}";
caseObj.Display_Screen_Suffix__c = "see " + '{!User.FirstName}'+" at Counter  "+'{!TEXT($User.Assigned_Counter__c)}';
var result = sforce.connection.update([caseObj]);

if (result[0].success=='false'){
alert(result[0].errors.message);
} else {
window.parent.location.href="/{!Case.Id}";
}
}

My original solution to this was to have the code in the Accept button refresh the page before running its User owner check, but this does not seem to be working either.

I was adding location.reload(true); before the User check.

Can anyone tell me why the refresh solution isn't working, or if there is another way to either do the refresh, or to execute my intentions?
I cannot figure out what I am doing wrong here.  This was working before.  

MY VF Page
<apex:page Controller="TestP" showHeader="false">

<apex:pageBlock><apex:pageBlockSection>
    <apex:form>
   Email given: {!cemail} 
   Email Returned: {!IdentifyUser.email} 
   Name: {!IdentifyUser.name}
    </apex:form>
    </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

My Controller
 
public class TestP {
    Public string cemail {get;set;} 
    Public Contact IdentifyUser {get;set;}
    Public Contact x {get;set;}
    
    // IDENTIFY USER BASED ON EMAIL ADDRESS
    Public Contact getIdentifyUser(){       
     cemail='kevin@caberu.be';   
       Contact x = [SELECT Id, firstname, email, name             
              FROM Contact 
              WHERE email = :cemail 
                              LIMIT 1]; 
        Return x;

    }
}

The VF page does not show any of the variables.

Any help is appreciated.  Where is the bug?
Hi,

I need help on the following issue 

I am having a trigger on account object 

When, we trying to upload bulk records  via dataloader or ETL , system is facing 'CPU usage limition'' issue.
For one Account record creation, the trigger is running four times instead of one time.

How to avoid the issue, Kindly help me pls
MY TRIGGER :

trigger AccountTrigger on Account (after insert, before update, after update, after delete) {  
    
    /* Assign & create Account team members based on user department*/
    if(Trigger_Status__c.getValues('AccountTeam').Active__c && Trigger.isUpdate  && Trigger.isBefore ){
        /* Before insert process */
        AccountTriggerHelper.updateAccountTeam(Trigger.newMap, Trigger.oldMap);
    } 
    
    /* Trigger to invoke the AccountIneligibilty Logs Tracking*/
    if(Trigger_Status__c.getValues('AccountEligibilityLogTrigger').Active__c && Trigger.isAfter && Trigger.isUpdate){
        AccountTriggerHelper.createAccountEligiblityLogs(Trigger.newMap, Trigger.oldMap);
    }
    
    /* Trigger to invoke the DiscountCode Calculations on Products*/
    if(Trigger_Status__c.getValues('AccountAirlineLeveltrigger').Active__c && Trigger.isAfter && Trigger.isUpdate) {
        AccountTriggerHelper.calculateDiscountCode(Trigger.newMap,Trigger.oldMap);
    }
    
    /* Trigger to invoke the DeleteAccount Tracking of Records*/
    if(Trigger_Status__c.getValues('AccountDeleteTrigger').Active__c && Trigger.isAfter && Trigger.isDelete) {
        AccountTriggerHelper.createDelAccountLogTracker(Trigger.oldMap); 
    }        
}
MY CLASS:

public class AccountTriggerHelper {
    
    /*--------------------------------------------------------------------------------------      
  Method Name:        updateAccountTeam
  Description:        Method to Assign & create Account team members based on user department
  Parameter:          Account New Map & Old Map 
  --------------------------------------------------------------------------------------*/    
    public static void updateAccountTeam(Map<Id,Account> newMapAccount, Map<Id,Account> oldMapAccount){
      try{
        AccountTeamHandler accHandler = new AccountTeamHandler();
        List<Account> lstNewAccount = newMapAccount.values();
            accHandler.setRevenueManualUpdate(lstNewAccount, oldMapAccount);
            accHandler.createAccountTeamMembers(lstNewAccount, oldMapAccount);
      }
      catch(Exception ex){
        String recType = CustomSettingsUtilities.getConfigDataMap('Log Exception Logs Rec Type');    
            CreateLogs.LogWrapper logWrap = new CreateLogs.LogWrapper('Account Team - Account Trigger', 'AccountTriggerHelper', 
                                                                      'updateAccountTeam', UserInfo.getUserName(), '', 
                                                                      '', false, recType);
            
            Log__c objLogs = CreateLogs.createLogRec(logWrap, '');
            CreateLogs.createApplicationLog(objLogs, ex);
      }
    }

    /*--------------------------------------------------------------------------------------      
  Method Name:        createAccountEligiblityLogs
  Description:        Method to Create AccountIneligibilty Logs and Update
  Parameter:          Account New Map & Old Map 
  --------------------------------------------------------------------------------------*/    
    public static void createAccountEligiblityLogs(Map<Id,Account> newMapAccount, Map<Id,Account> oldMapAccount){
      try{
        AccountEligibilityLogHandler.createAccountEligiblityLogs(newMapAccount, oldMapAccount);
      }
      catch(Exception ex){
        String recType = CustomSettingsUtilities.getConfigDataMap('Log Exception Logs Rec Type');    
            CreateLogs.LogWrapper logWrap = new CreateLogs.LogWrapper('SME - Account Trigger', 'AccountTriggerHelper', 
                                                                      'createAccountEligiblityLogs', UserInfo.getUserName(), '', 
                                                                      '', false, recType);
            
            Log__c objLogs = CreateLogs.createLogRec(logWrap, '');
            CreateLogs.createApplicationLog(objLogs, ex);
      }
    }

    /*--------------------------------------------------------------------------------------      
  Method Name:        calculateDiscountCode
  Description:        Method to DiscountCode Calculations on Products
  Parameter:          Account New Map & Old Map 
  --------------------------------------------------------------------------------------*/    
    public static void calculateDiscountCode(Map<Id,Account> newMapAccount, Map<Id,Account> oldMapAccount){
    try{
            AccountAirlineLevelHandler.updateDiscountCodeOnProducts(newMapAccount, oldMapAccount);
      }
      catch(Exception ex){
        String recType = CustomSettingsUtilities.getConfigDataMap('Log Exception Logs Rec Type');    
            CreateLogs.LogWrapper logWrap = new CreateLogs.LogWrapper('SME - Account Trigger', 'AccountTriggerHelper', 
                                                                      'calculateDiscountCode', UserInfo.getUserName(), '', 
                                                                      '', false, recType);
            
            Log__c objLogs = CreateLogs.createLogRec(logWrap, '');
            CreateLogs.createApplicationLog(objLogs, ex);
      }
    }

    /*--------------------------------------------------------------------------------------      
  Method Name:        createDelAccountLogTracker
  Description:        Method to Create Delete Tracker Logs records when any Account is Deleted
  Parameter:          Account Old Map 
  --------------------------------------------------------------------------------------*/    
    public static void createDelAccountLogTracker(Map<Id,Account> oldMapAccount){
        try{
            String recTypeName = CustomSettingsUtilities.getConfigDataMap('Del Log SME Account Rec Type');
            List<CreateLogs.DeleteLogWrapper> lstDelLogWrapper = new List<CreateLogs.DeleteLogWrapper>();
            for(Account acc: oldMapAccount.values()){
                String directvalue = CustomSettingsUtilities.getConfigDataMap('AccListner Type Direct Stream');
                if(acc.Listner_Type__c == directvalue){
                    CreateLogs.DeleteLogWrapper delLogWrapper = new CreateLogs.DeleteLogWrapper();
                    delLogWrapper.recType = recTypeName;
                    delLogWrapper.recName =  acc.Name;
                    delLogWrapper.abnNumber = acc.ABN_Tax_Reference__c;
                    delLogWrapper.sobjectId = acc.Id;
                    delLogWrapper.sobjectName = 'Account';
                    lstDelLogWrapper.add(delLogWrapper);
                }
            }
            List<Delete_Tracker_Log__c> lstDelTrackerLog = CreateLogs.createDeleteLog(lstDelLogWrapper);
            insert lstDelTrackerLog;
        }catch(Exception ex){
            String recType = CustomSettingsUtilities.getConfigDataMap('Log Exception Logs Rec Type');    
            CreateLogs.LogWrapper logWrap = new CreateLogs.LogWrapper('Direct Stream - Account Trigger', 'AccountTriggerHelper', 
                                                                      'createDelAccountLogTracker', UserInfo.getUserName(), '', 
                                                                      '', false, recType);
            
            Log__c objLogs = CreateLogs.createLogRec(logWrap, '');
            CreateLogs.createApplicationLog(objLogs, ex);
        }
    }

}
Kindly help me pls

Thanks in Advance

 
Could someone explain how to process a list within a list in APEX code?

String List Example:

List<String>
{AccountCustomerNumbers=[700011326, 507024842, 12345678], AgentId=AI60856},
{AccountCustomerNumbers=[700011326, 507024842, 12345678], AgentId=AI54960},
{AccountCustomerNumbers=[700011326, 507024842, 12345678], AgentId=AI57656}

There would be three calls within a loop to a service that is expecting the parameters of AgentId and CustomerIds[].


Example:

AgentId = 'AI60856'
CustomerIds[] = '700011326', '507024842', '12345678'

AgentId = 'AI54960'
CustomerIds[] = '700011326', '507024842', '12345678'

AgentId = 'AI57656'
CustomerIds[] = '700011326', '507024842', '12345678'
i want to relate Oppurtunity and Training session objects and the field No of Training Days in Training session record should be auto populated on No of training days field on oppurtunity standard object
Hi,


There is a text Field which stores value in the format: Last name, First name

I need to extract only first name from this field to be used in One of the email templates in marketing cloud

 
Hope someone would have gone through atleast a similar exercise. i'm trying to migrate around 80mil records from sfdc through informatica. for the initial load we don't want to go big bang approach. so we need to split the sfdc records into batches so we can load them daily. my question is how to split the sfdc data? one of the suggestions is to use 15 digit salesforce id but again the question is how to split as it's not a sequential number. appreciate any ideas.
Hi, 

   Need experts suggestion on this new requirement. I have a requirement in Account and Contact hierarchies 
  
   Example : 

   Account A  = 10 Contacts  = No Parent
   Account B  = 5 Contacts  = Account A is Parent 
   Account C  = 20 Contacts = Account B is Parent 
   Account D = 3 Contacts = Account B is Parent 
   Acconut E = 2 Contacts = Account C is Parent 

Now my requirement here is if Account B -- Contact is checked I need a result of Account B,C and D list of contacts Please suggest me how to achive this hierachy in code

Similarly If Account C -- contact is checked/searched I need a result of Account C and E list of contacts 

Please let me know if my example is not clear I can explain in clear again need salesforce expters to suggest me on this requirement.  

Thanks
Sudhir 
hi,
I have a favourite button which fetches the items which has been ordered more than twice.
This is my controller

    Public List<Menu__c> favmenu {get;set;}
     favmenu = [select id, name,Category__c,Description__c,Image__c,ImageURL__c,Dish_Name__c,Price__c,
                 Special_Dish__c,Status__c,SubCategory__c,veg_non_veg__c,remarks__c from Menu__c where id IN : menuIdList]; 
           
           if(favmenu.size()>0)
               nofavourites = 'Choose from your favourites';
           else
                nofavourites='No favourites yet';

When i m testing for favmenu.size()>0 ..... it is working fine....but for the else part, when the soql query is not fetching any item, it is showing the error
Attempt to de-reference a null object 
An unexpected error has occurred. Your development organization has been notified.
  • September 21, 2017
  • Like
  • 1
Dears,

I want to realize a function similar with "vlookup" with Apex and I tried coding like following but not correct.

Background:
I have 2 standard object: opportunities and quotes (lookup relationship, opportunities is father). In opportunities I have a picklist field named "City".

And I create a customized filed called "Destination information". For each value in the picklist "city", I have a record in "Destination information", named with the same picklist value.

Now I created a lookup function between Quotes and  "Destination information". I want to get the ID of that City in "Destination information" to Quotes.

For example: In opportunity there is 1 record with the "City" field value "Paris", and the record named "Paris" in "Destination information" has a ID 0062800000P6Dg6. I want to get that ID and give it to the lookup field "Destination_information" in the Quote records related to that opportunity.

Here following my code (not correct)
trigger GetDestinationID on Quotes (before insert, before update) {
for (Quotes quotes : Trigger.new) {
    String desid = Quotes.Destination_information__c;
    List<Destination_information__c> Destination_information = [SELECT Id FROM Destination_information WHERE Quotes__r.Opportunity.City__c = :desid];
    if(Destination_information != null)
             Quotes.Destination_information__c = Destination_information[0].Id;
    }
}
Thanks in advance!
 
We have a custom object with a Formula field referncing the Amount field in the Opportunity object. In apex, we use dynamic SOQL to generate a query that includes this field. When the code executes in Winter 18 (Partial Sandbox), we are receiving this error when the query executes: System.UnexpectedException: common.exception.SfdcSqlException: ORA-00936: missing expression. 

Exact same code is working fine in Production (Summer 17). We tested in a Developer Sandbox running Winter 18 and it is working fine too. Compared the metadata between the two sandboxes and seems to be the same. Anyone else seeing problems with dynamic SOQL queries in Winter 18? 
I'm receiving an error on Line: 1, Column 1 
System.StringException: Unexpected end of expression.

System.schedule('IMSync_At00Minutes', '0 0***?',new IncidentManagerSync());
System.schedule('IMSync_At15Minutes', '0 15***?',new IncidentManagerSync());
System.schedule('IMSync_At30Minutes', '0 30***?',new IncidentManagerSync());
System.schedule('IMSync_At45Minutes', '0 45***?',new IncidentManagerSync());

Can someone tell me what I'm doing wrong? I'm trying to execute a process every 15 minutes.  Did I get the syntax wrong somewhere?
Hello,

I am working on the Process Automation Specialist Superbadge and have completed the first part of the challenge (Automate Leads). I have created the Validation Rule, Lead Queues, and Lead Assignment Rules, yet I keep receiveing various reference Error ID's without explanation. I am using a fresh chellenge Org as well.

Thanks!

Dave 
I am Trying to create a report on Object__c. So I am trying to use user custom field(projectName__c) value in custom object field(projectName__c) in filter in Reports.

For that, I got a suggestion to do like below, and filter with Boolean.

Create a formula field in the custom object which is checkbox type and formula will be IF(projectName__c=user.projectName__c,true,false)

And create a report where apply filter forumulaField__c = true.

So, This is working fine. But When I change projectName__c, The all same projectName__c record's will be updated. If I change it to another project again records will be updated. I will have 10 Lakhs records in my application, presently I am using developer account.

Does This updating on 10 lakhs records meets any governor limits?

This help will be very Glad.

Thank you.
Im sure this is super basic for some of you so hoping I can save some hours in my day by asking the larger community. 

The question I am trying to answer is: How many Contacts have made a Donation with the Opportunity Name = "Foundation Donation" in 2017?

The nuance is:
  • We dont use Accounts
  • We dont use Contact Roles for Opportunities
  • We use a custom lookup field on the Opportunity Object called 'Donor_Contact'
  • I dont need to return dollar amount (although would be helpful)
  • I dont need to return any Contact meta data, strictly 'number of donors'. 
A lot of the solutions I have found are looking up the Contact via the Account which we dont use and/or go through the Contact Role which we dont use. I have not found a solution that utilizes a custom field lookup on the Opportunity Object to get to the Contact. I am looking for some tips on structuring the query. Everything I have tried has returned 'malformed' errors. 

Any help would be appreciated. Thank you!
 
Apex Class:
public with sharing class SkipMilestone{
    public List<Program_Member_Stage_MVN__c>Pms{get;set;}
    public List<ProgramWrapper>PmsWrapper{get;set;}
    public Program_Member_MVN__c Pm;
    public SkipMilestone(ApexPages.StandardController controller) {    
    Pm = (Program_Member_MVN__c)controller.getRecord();
        List<Program_Member_Stage_MVN__c>Pms =[select id,Name,Program_Stage_MVN__c,Status_MVN__c,Program_Stage_Name_MVN__c from Program_Member_Stage_MVN__c where Program_Member_MVN__c=:Pm.id and Status_MVN__c='Not Started'];
            if(Pms != null && Pms .size() > 0){
               displayStages(Pms);
    system.debug('Pms:'+Pms);
    }
    }
    
    public void displayStages(List<Program_Member_Stage_MVN__c>Pms)
    {
   PmsWrapper=new  List<ProgramWrapper>();
     for(Program_Member_Stage_MVN__c PmObj : Pms){
       PmsWrapper.add(new ProgramWrapper(PmObj));
    }
    }
    public void complete(){
    PmsWrapper=new  List<ProgramWrapper>();
        for(ProgramWrapper ow : PmsWrapper){
        if(ow.isChecked){
              ow.PmStatus='Started';
             // PmsWrapper.add(new ProgramWrapper(ow));
            }  
          //  update PmsWrapper;
        }
        }
       
     public class ProgramWrapper{ 
     public string PmId{get;set;}
      public String PmName{get;set;}
        public String Pmstage{get;set;}
        public Boolean isChecked {get;set;}
        public String PmStatus{get;set;}
        
        
         public ProgramWrapper(Program_Member_Stage_MVN__c PmObj){
         this.PmId=PmObj.id;
          this.PmName= PmObj.Name;
            this.Pmstage= PmObj.Program_Stage_Name_MVN__c;
            this.isChecked = false;
            this.PmStatus= PmObj.Status_MVN__c ;
    }
    }
    }

Visual force Page:
<apex:page standardcontroller="Program_Member_MVN__c" extensions="SkipMilestone" >
  
    <apex:form >
        <apex:pageBlock >
            <apex:pageblocktable value="{!PmsWrapper}" var="Pm">
                <apex:column ><apex:inputCheckbox value="{!Pm.isChecked}" /></apex:column>
                <apex:column headervalue="Name" value="{!Pm.PmName}"/>
                <apex:column headervalue="Stage Name" value="{!Pm.Pmstage}"/>
                <apex:column headervalue="Status" value="{!Pm.PmStatus}"/>
                <apex:column headerValue="Action">
                    <apex:commandButton value="Complete" onclick="complete" />  
                </apex:column>
            </apex:pageblocktable>
        </apex:pageBlock>
    </apex:form>
</apex:page>


The functionality i want is when i click the button which is displayed at the end of records it should update the status field of that particular record to completed.
How should i write the logic in: 
public void complete(){
    PmsWrapper=new  List<ProgramWrapper>();
        for(ProgramWrapper ow : PmsWrapper){
        if(ow.isChecked){
              ow.PmStatus='Started';
             // PmsWrapper.add(new ProgramWrapper(ow));
            }  
          //  update PmsWrapper;
        }
        }
To update the status field of that record to "completed"?
Visual force page will look like:
User-added image
Hi,

Have a question, please help.


I am trying to insert a record and relate it to existing record. For example, if we want to insert a contact relating to existing Account, then we would write as follows:

Contact con = new Contact(LastName = 'Rahul');
con.AccountID = //here account ID will go
insert con;

My first question is, why the below code does not work(that is, it relates contact and Account, but does not show the same on UI, Account field is blank on Contact)

Contact con = new Contact(LastName = 'Rahul);
con.Account = //Account Object reference here.
insert con;

My second question is: lets say we have two custom objects Job Application and position, in which position is master object. Then how do we insert Job application object related to existing position. below code does not work for me:


Job_Application__c job = new Job_Application()
job.position__r = //position object reference here.
insert job;

this code does create job applicaton object but does not relate it to position object.

PLEASE HELP


best Reagrds,

Rahul SIngh Rana
I have successfully created the wave dev account multiple times, but the check button on the trailhead still does not recognize the newly created account.  
Hi, I need to update the field "location" (picklist) on the master object based on the value in the field "location" (picklist) on a child object
Basically, here is what I want:
 if field "location" on child object contains a value and the status (picklist) of the child object= active, then I want to update the location field (picklist) on the master object if this field is blank.

I guess I need to use a process builder to do this as worklow will not work but I am stuck:
1. when saying ISPICKVAL (Status, "Active") in my conditions
2. when defining the condition "location" field is blank on the field to update.
both pbls related to picklist field
Can somebody help me with this? Many thanks, claire
 i have a trigger that updates fields on an opportunity when it is created and anytime it is updated anytime after. It adds phone number fields and a few other fields that i can't map over. I need it to also update the opportunity name depending on if the account has a middle name or not. So i am dealing with if and else statements. I had a process builder done and it worked fine for a little bit but now it is not working at all. I will attach what it looks like as well as the trigger that i have so far. SO basically what i need to added to my trigger that i cant seem to figure out how to do is the opportunity name update.
For example-- If the account First Name: Bob --Middle Name: Null -Last Name: Smith  I would want Opportunity name to be updated to Bob Smith 
But if it was --First Name: Bob  - Middle Name: Mary -Last Name: Smith  I would want Opportunity name to be updated to Bob & Mary Smith 

this is the trigger that i have created that updates the opportunity fields 

trigger insertOpportunity on Opportunity(before insert,before update) {

if(trigger.isinsert)
{
for(Opportunity ac : Trigger.new){
try{

List<account> acc=[select id,Water_Source__c,Phone,PersonHomePhone,PersonMobilePhone,Water_Filters__c,PersonMailingStreet,PersonMailingCity,PersonMailingState,PersonMailingPostalCode,Water_Conditions__c,Type_of_Home__c from Account where id=: trigger.new[0].accountid];
trigger.new[0].Water_Source__c=acc[0].Water_Source__c;
trigger.new[0].Home_Phone__c=acc[0].PersonHomePhone;
trigger.new[0].Mobile_Phone__c=acc[0].PersonMobilePhone;
trigger.new[0].Water_Filters__c=acc[0].Water_Filters__c;
trigger.new[0].Street__c=acc[0].PersonMailingStreet;
trigger.new[0].City__c=acc[0].PersonMailingCity;
trigger.new[0].State__c=acc[0].PersonMailingState;
trigger.new[0].Zip_Code__c=acc[0].PersonMailingPostalCode;
trigger.new[0].Water_Condtitions__c=acc[0].Water_Conditions__c;
trigger.new[0].Type_of_Home__c=acc[0].Type_of_Home__c;
trigger.new[0].Phone__c=acc[0].Phone;
}
catch(Exception e ){
}
}
}

}



This is the formula that i had for the process builder that worked but now no longer does and this is what i need the opportunity name to look like 

IF(NOT(ISBLANK([Account].Spouse_Name__c)),
  [Account].FirstName & " " & "&" & " " & [Account].Spouse_Name__c & " " & [Account].LastName,
[Account].FirstName & " " &  [Account].MiddleName & " " &  [Account].LastName
 )

Groundswell Cloud Solutions is seeking superstar Salesforce DevelopersTechnical Architects to join us to work on some large-scale SFDC implementations! This is an excellent opportunity to join a fast-expanding Salesforce consulting firm, and grow with friendly, highly accomplished Salesforce professionals. You'll get to push the boundaries of Wave AnalyticsCommunities, work across SalesService Clouds and now even Einstein!

We offer competitive salary, generous annual bonus, 15 days vacation+ 2 weeks office closure over X’mas/New Year, Extended Health, sponsored SF certifications and endless supply of snacks and drinks.

Interested?
Please visit: www.gscloudsolutions.com/careers 

Thanks and we look forward to hearing from you!

Groundswell Team Intro!
 

I found a bug in the Tooling API, but cannot report it directly to Salesforce.

We are using the Tooling API to assign new picklist values to record types. This is a typical request that we send:

URL: https://SANDBOX.cs80.salesforce.com/services/data/v39.0/tooling/sobjects/RecordType/012250000008wmq
Payload:
{
  "Metadata": {
    "active": true,
    "compactLayoutAssignment": "Master_Product_Compact_Layout",
    "description": "Master Product, managed in MDM.",
    "label": "Master Product",
    "picklistValues": [
      {
        "picklist": "Packaging__c",
        "values": [
          {
            "default": false,
            "valueName": "twinpack, 1 ltr. + 1 ltr."
          }
        ]
      }
    ]
  },
  "FullName": "Product2.Master_Product"
}
Error Message:
{
    "statusCode": 400,
    "headers": {
        "Pragma": "no-cache",
        "Cache-Control": "no-cache",
        "Date": "Wed, 01 Mar 2017 14:27:59 GMT",
        "Server": "Microsoft-IIS/8.0",
        "X-AspNet-Version": "4.0.30319",
        "X-Powered-By": "ASP.NET",
        "Content-Length": "151",
        "Content-Type": "text/plain; charset=utf-8",
        "Expires": "-1"
    },
    "body": "[{\"message\":\"Picklist value: twinpack%2C 1 ltr%2E   1 ltr%2E in picklist: Packaging__c not found\",\"errorCode\":\"FIELD_INTEGRITY_EXCEPTION\",\"fields\":[]}]"
}

This error only occurs for picklist values that have a "+" character in their name. The Tooling API seems to URL decode the request where "+" characters are replaced with a space, as you can see in the error message. Additional URL encoding of the valueName won't help. This seems to be an error of the RecordType Tooling API, as inserting new picklist values with a "+" character does work fine. 

 
Mistake on this page (or it could be clearer)
https://trailhead.salesforce.com/modules/data_modeling/units/schema_builder

'Salesforce populates Field Name using the field label. This name can contain only underscores and alphanumeric characters, and must be unique in your org. '

Surely it should be unique in the object.
Hi,
I have custom lookup field in a account object 
lookup to the user

My question is i have to prepopulate the field with the user name that means owner of the account

please help me to sort out this

Thanks & Regards
Pratyusha.K



Hi all, 

I'm learning triggers in salesforce and want some advice on understanding how to write a trigger for below scenario. what is the approach?
There are two objects Object1_c(Parent) and Object__c(child) having look-up relationship.

Summary:
Object__c has record types namely  "A" and "B".
Object__c has a field (currency) --> Myamount__c
Object__c has 2 picklislts --> Picklist_a__c and Pciklist_b__c
object1__c has a field(curreny_ --> amount__c

Scenario:

when amount__c(on Object1__c) is blank or null, and if record type is either A||B and Picklst_a__c and picklist__b is selected then Myamount__c should be required show be the error.

Thanks in advance.
 
Below is the trigger 
 
trigger TaskBeforeDelete on Task (before delete) {

      Map<Id,Profile> profileMap=new Map<Id,Profile>([SELECT Id,Name FROM Profile WHERE Name  IN ('Standard User')]);
       
    System.debug('profileMap==>'+profileMap);
    
    profile p=profileMap.get(UserInfo.getprofileID());
     try {
        
        for (Task task : Trigger.old)  {    
        
        	  if(task.Activity_LFD_Type__c.equalsIgnoreCase('Test') && task.WhatId.getSObjectType() == account.sObjectType && task.WhatId != null && (p==null) )           
            
            {    
                if(!Test.isRunningTest()){
                
                task.addError('You are not permitted to delete this task');
                
                }
     
            }
        
        }
        
    } Catch(Exception e){
        
            
       throw new RuntimeException('****TaskBeforeDelete:'+':' +e.getMessage());
    }
        
     }

Below is the test class 
 
@istest

    public class TaskBeforeDelete_Test{
    
    public static testMethod void BeforeDelete(){ 
    
           Profile pId = [SELECT Id FROM Profile WHERE Name = 'Test Profile'];
        
         User testUser = new User(Email='test@email.com',Phone='555-555-5555',
                                 FirstName='Test',LastName='User', ProfileId=pId.Id,UserName=uniqueName + '@test' + orgId + '.com',
                                 Alias='tesUse',TimeZoneSidKey='America/New_York',
                                 LocaleSIdKey='en_US',EmailEncodingKey='UTF-8',
                                 LanguageLocaleKey='en_US'); 
                                 
        
        system.runAs(testUser){
        
        account acc= new account();
        acc.name='test';
        acc.Site='testsite';
        insert acc;
        
        
       task task=new task();
       task.Activity_LFD_Type__c='Test';
       task.whatid=acc.id;
       
       insert task;
       
       delete task;
       
       }
        
    
    }


}

For the above trigger the code coverage is below 75 % and i'm not able to cover the catch block.

Can any one suggest on this please.
trigger updateProjectTeammember on opportunityTeamMember(after insert, after update, after delete){
        if(trigger.isInsert || trigger.isUpdate){
        
        Map<String,String> OppOtmfieldMap=new Map<String,String>();
               OppOtmfieldMap.put('Sr. Client Insights Manager','CEM_Assigned__c');
               OppOtmfieldMap.put('Client Insights Manager','CEM_2nd__c');
               OppOtmfieldMap.put('Data Manager','Ops_Owner__c');
               OppOtmfieldMap.put('Lead Consultant','Consultant_assigned__c');
               OppOtmfieldMap.put('Support Consultant','Consultant_2nd__c');
               OppOtmfieldMap.put('Analysis Support','Analysis_Support__c');
               OppOtmfieldMap.put('BD/Development Partner','BD_Development_Partner__c');
        
        Map<String,String> projOtmfieldMap=new Map<String,String>();
               projOtmfieldMap.put('Sr. Client Insights Manager','Sr_Client_Insights_Manager__c');
               projOtmfieldMap.put('Client Insights Manager','Client_Insights_Manager__c');
               projOtmfieldMap.put('Data Manager','Ops_Manager__c');
               projOtmfieldMap.put('Lead Consultant','Lead_Consultant__c');
               projOtmfieldMap.put('Support Consultant','Support_Consultant__c');
               projOtmfieldMap.put('Analysis Support','Analysis_Support__c');
               projOtmfieldMap.put('BD/Development Partner','BD_Development_Partner__c');
        
            list<id> oppoIdList = new list<id>();
            map<id, id> oppoOtmMap = new map<id, id>();
            list<id> proMemList = new list<id>();
            map<id, id> oppIdProIdMap = new map<id, id>();
            list<id> proId = new list<id>();
            Map<Id,Opportunity> oppIdMap = new Map<Id,Opportunity>();
            Map<id, id> oppIdAccIdMap = new Map<id, id> ();
            Set<id> accId=new Set<Id>();
            
        for(OpportunityTeamMember otm : trigger.new){
                        OppoIdList.add(otm.OpportunityId);
                        oppoOtmMap.put(otm.Id, otm.OpportunityId);
            }
        
        map<id, list<Project__c>> oppIdProjectListMap = new map<id, list<Project__c>>();
        list<Opportunity> oppoList = [select Id, accountId, Project__c, (Select Id, Name from Project__r) From opportunity Where Id In: oppoIdList];
        system.debug('--oppoIdList--' +oppoIdList);
        for(Opportunity op : oppoList){
            proId.add(op.id);
            oppIdMap.put(op.id,op);
            accId.add(op.accountId);
            oppIdAccIdMap.put(op.id, op.accountId);
           // oppIdProIdMap.put(op.id, op.Project__c);
            oppIdProjectListMap.put(op.id, op.Project__r);
            }
                
        list<Project_Team__c> ptmListForInsert = new list<Project_Team__c>();
        system.debug('--proId--' +proId);
        system.debug('--accId--' +accId);
        system.debug('--oppIdProIdMap--' +oppIdProIdMap);
        system.debug('--oppIdAccIdMap--' +oppIdAccIdMap); 
        
        list<Project_Team__c> ptmList = [Select id, Account__c, Project__c, Member_Role__c, Team_Member__c From Project_Team__c Where Id In: proId];
        map<id, list<Project_Team__c>> proPtmMap = new map<id, list<Project_Team__c>>();
        
        for(project_Team__c ptm : ptmList){
        
            list<project_Team__c> tempList = proPtmMap.get(ptm.Project__c);
            
            if(templist!= null && templist.Size()>0){
                tempList.add(ptm);
                }else{
                        tempList = new list<project_Team__c>();
                        tempList.add(ptm);
                }
                proPtmMap.put(ptm.Project__c, tempList);
            }
        
        for(OpportunityTeamMember otm : trigger.new){
        
            Boolean flag = false;
           
            List<project__c> listOfProj = oppIdProjectListMap.get(otm.OpportunityId);
            
            for(Project__c pro : listOfProj){
            List<project_team__c> listOfPrjTm = proPtmMap.get(pro.id);
            
            
            if(listOfPrjTm!= null){
                for(Project_Team__c ptm : listOfPrjTm){
                    if(otm.userId == ptm.Team_Member__c){
                        flag =true;
                        }
                    }
                }
                if(flag ==true){
                }else{
                    Project_Team__c ptm1 = new Project_Team__c();
                    ptm1.Team_Member__c= otm.userId;
                    ptm1.Member_Role__c = otm.TeamMemberRole;
                    ptm1.Account__c = oppIdAccIdMap.get(otm.OpportunityId);
                    ptm1.Project__c = proPtmMap.get(otm.OpportunityId);
                    ptmListForInsert.add(ptm1);
                    system.debug('--ptm1--' +ptm1);
                    }
            }}
        if(ptmListForInsert.size()>0){

        insert ptmListForInsert;
            }
            
  }
}
Wave Apps Basics - Creating Wave Apps
I'm trying to refresh data for Wave Analytics trail using Trailhead Data Manager
I'm getting STORAGE_LIMIT_EXCEEDED
I have 5 MB limit and Trailhead Data Manager eats up 6MB
I tired to delete all tasks and re-run but it creates all those tasks again and uses all available space.
Is somehow my dev org is too small or Trailhead Data Manager isn't working correctly?
How can I fix it?








 
  • February 13, 2017
  • Like
  • 1
Hi all,

I would need that if a user select a piclist field value, another text field can´t be blank.

Here is my code. Any help, please?

AND (
ISPICKVAL( Status  , "Unqualified"),
 NOT (ISBLANK( ReasonRejectedByCommercialPlanning__c ))

 )
  • February 10, 2017
  • Like
  • 1

I am using two tables. Invoice_Header(Parent) and Invoice_Line(Child) tables. Relationship is Invoice_Line__r(Being seen in Invoice_Line table in Schema Builder).

Fields we are going to Use: 

Invoice_Header:Invoice_no, Amount_minus_tax(we want sum of it), Salesrep__c

Invoice_Line: Invoice_no, prduct_group_id

Query Question: I want sum of all invoices (Amount_minus_tax) where salesrep is equal to Steven, product_group_Id = 'MERCH' 

 

I tried this Query, but it is not working:

select sum(amount_minus_tax__c) from CommercientSF10__EPICOREP21_InvoiceHeader__c where CommercientSF10__Salesrep__c = 'a0d61000004Jcvj' and CommercientSF10__EPICOREP21_Invoice_Lines__r.CommercientSF10__product_group_id__c = 'MERCH'

I can excecute query with left join but this will be having more rows than we need so I want to use Right join as shown in above Query.

Working Query with Left Join:

select CommercientSF10__invoice_no__c, (select CommercientSF10__invoice_no__c from CommercientSF10__EPICOREP21_Invoice_Lines__r where CommercientSF10__product_group_id__c = 'MERCH' ) from CommercientSF10__EPICOREP21_InvoiceHeader__c where CommercientSF10__Salesrep__c = 'a0d61000004Jcvj'

 

 

I've got a strange error. I grabbed the controller code from this blog post, but when I try to save it to my dev org, I get an error: unexpected token: '='. I can't seem to figure out why. Any help would be appreciated!

Here's the controller throwing the error:
Public class ThumnailController {

  public String imageUrl {get; set;}

  ContentVersion[] cvs = [select id from contentversion where contentdocumentid= '0691a0000015c3v' and isLatest=true];

  imageUrl ='/sfc/servlet.shepherd/version/renditionDownload?rendition=THUMB720BY480&versionId=' + cvs[0].id;

}

The error is being thrown at this line:
imageUrl ='/sfc/servlet.shepherd/version/renditionDownload?rendition=THUMB720BY480&versionId=' + cvs[0].id;


 
I am looking for help to run a Join Query to find all out Accounts in our Database without Contacts AND Opportuntiy.  I can run the query indepetly, but I would like to join the queries. 

The Query I am runing to find Accounts without Contacts: Select Id, Name From Account Where Id NOT IN (SELECT AccountId FROM Contacts)
Query to find Accounts without Opportunties: Select Id, Name From Account Where Id NOT IN (SELECT AccountId FROM Opportunity)
This rule works however, if the user chooses other value in the Stage name and chooses a required value for Product Support, this value doesn´t save. Any idea??. Thanks. Note: both field are picklist

IF(

 ISPICKVAL( StageName , "5 - Qualification"),

 ISPICKVAL( Product_Support__c, "None"),true)
  • February 10, 2017
  • Like
  • 1
Hi,
i am stuck in this below error can anyone suggest?I already imported contact and account successfully through import wizard.stuck for hobby,contact hobby and opportunity.When i am trying to import hobby data with the(list of contacts to import) CSV file.in mapping section it shows only hobby field.

can anyone guide me on this?

User-added image
Since reading Advanced Apex Programming I've been a propenent of the "one trigger to rule them all" framework.  I then carried that philosophy over to process builder using a single upsert process for each object (Lead Upsert process, Account Upsert process, etc.).  The primary reason was to better control execution context of when flows will run within that object.  Winter 17' release now allows for the building of process builder hierarchies which seems like it eliminates the need to bunch everything up into a single process.

What do you think?  What does your process builder framework look like?
This error can be caused in one of two ways:
  1. ​You've been away for a while and you're now logged out of your DE. This can simply be resolved by logging in again and restoring the connection.
  2. No matter how many times you log out and log in again, having the security setting "Lock sessions to the IP address from which they originated" enabled will prevent you from connecting your Org to Trailhead. For some reason, when trailhead checks challenges, it doesn't use the same IP address throughout the transaction, causing the error because the connector was logged out. As much as I'd like to claim this as my own discovery, @Matt Latto was the one to come up with the solution and posted it on another question, Not able to verify steps of Trailhead project.
Although this isn't officially a question, to my knowledge this information is not anywhere else on the forum, and if it is, it couldn't hurt to post it again.

Thanks for viewing,
Parker

When someone takes the time/effort to repspond to your question, you should take the time/effort to either mark the question as "Solved", or post a Follow-Up with addtional information.  

 

That way people with a similar question can find the Solution without having to re-post the same question again and again. And the people who reply to your post know that the issue has been resolved and they can stop working on it.