• Pavan Kumar Kaja
  • SMARTIE
  • 540 Points
  • Member since 2014
  • PwC


  • Chatter
    Feed
  • 19
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 79
    Replies
I want Test Class For this Trigger for me it is covering 38 % i thinkk iam wron any one please help me .This is urgenyt issue.can anyone spend time on this
Here is my Trigger:
trigger UpdateNormalLeadwithWebLead on Lead (after insert){
    set<String> setEmails = new set<String>();
    List<Lead> updateExistingLead =New List<Lead>();
    List<Lead> deleteNewDupLead =New List<Lead>();
    map<String,Lead> mLeadsExisting = new map<String,Lead>();
    map<String,Lead> Leadmap = new map<String,Lead>();
   
    for(Lead LeadObj : trigger.new){
   
        if(LeadObj.Email != null){
            setEmails.add(LeadObj.Email);
            Leadmap.put(LeadObj.Email,LeadObj);
        }
       
    }
    System.debug('@@@Leadmap@@@'+Leadmap);
    if(setEmails.size() > 0 ){
        for(Lead LeadObj : [SELECT id,Email,LastName,Company,phone,isConverted FROM Lead where Email in : setEmails AND isConverted =False AND RecordType.Name='Registration']){
            mLeadsExisting.put(LeadObj.Email,LeadObj);
        }
    }
    System.debug('@@@mLeadsExisting@@@'+mLeadsExisting);
    for(Lead LObj: [SELECT id,Email,LastName,FirstName,Company,phone  FROM Lead WHERE Id NOT IN:Trigger.new]){
        if(LObj.Email != null && Leadmap.ContainsKey(LObj.Email )){
            //LObj.MobilePhone= Leadmap.get(LObj.Email).MobilePhone;
            LObj.Phone = Leadmap.get(LObj.Email).Phone;
            LObj.LastName = Leadmap.get(LObj.Email).LastName;
            LObj.FirstName = Leadmap.get(LObj.Email).FirstName;
            LObj.Company= Leadmap.get(LObj.Email).Individual_Company__c;
            LObj.City= Leadmap.get(LObj.Email).City;
            LObj.Street= Leadmap.get(LObj.Email).Street;
            LObj.State= Leadmap.get(LObj.Email).State;
            LObj.Registered_Online__c=Leadmap.get(LObj.Email).Registered_Online__c;
            LObj.Title=Leadmap.get(LObj.Email).Title;
            LObj.Lead_Trigger__c=false;
            updateExistingLead.add(LObj);
        } 
    }
    System.debug('@@@updateExistingLead@@@'+updateExistingLead);
    if(!updateExistingLead.isEmpty()){
        try{
            Update updateExistingLead;
            System.debug('@@@updateExistingLead1@@@'+updateExistingLead);
        }
        catch(Exception e){
            System.debug('@@@Insert Failed Due to@@@'+e);
        }
        for(Lead LeadObj : [SELECT id,Email,LastName,FirstName,Company,phone FROM Lead WHERE Id IN:Trigger.new]){
            if(mLeadsExisting.containsKey(LeadObj.Email)){
                deleteNewDupLead.add(LeadObj);    
            }
        }
        if(!deleteNewDupLead.isEmpty()){
            delete deleteNewDupLead;
        }
    }
}
we hv two objects(standard) one is account (parent) and second is contact(child)

i want to populate the name field of account with the lastname field of contact .




here is what i could code .
; but this is not working 



trigger trigsetLastName on Contact (after insert,after update)
{
   Map<id,account> parentacc = new Map<id,account>();
    List<id> listids = new List<id>();
   
   
    for( contact childobj :Trigger.new)
    {
            listids.add(childobj.account);   // error in this line
    }
   
    parentacc= new map<id,account> ([select id,Name ,(select id,LastName from contacts) from account where id in: listids]);
   
    for ( contact c :trigger.new)
    {
        account myacc = parentacc.get(c.account);
        myacc.Name=c.LastName;
    }
    Update parentacc.values();
    }
Hello everybody!
Here my example:

public class DemoController {

public List<User> mRecords { get; set; }
private Integer mRecordsCount { get; set; }

public ADemoController() {
  mRecordsCount = 1;
  mRecords = [SELECT Id, FirstName FROM User LIMIT :mRecordsCount];
}

public void loadOneMoreRecord() {
  mRecords.clear();
  mRecordsCount++;
  mRecords = [SELECT Id, FirstName FROM User LIMIT :mRecordsCount];
}

}


<apex:page controller="DemoController" >

<apex:pageMessages />

<apex:form id="TheForm">
  <apex:pageBlock id="TheBlok">
   <apex:commandButton value="Load one more record" action="{!loadOneMoreRecord}" reRender="TheTable" />
   <apex:pageBlockTable value="{!mRecords}" var="record" id="TheTable">
    <apex:column headerValue="Records">
     <apex:outputLink value="/{!record.Id}"><apex:outputText value="{!record.FirstName}" /></apex:outputLink>
    </apex:column>
   </apex:pageBlockTable>
  </apex:pageBlock>
</apex:form>
 
</apex:page>

After first page loading the link is work fine, but after loading more records in table, links became dead (works only through rmc).
The question is how can I prevent this?

Sorry for my english.
Dear all,

I can't work out if I've misunderstood the documentation or if there's an issue with the code itself, but I'm trying to build a utility class that can handle DML exceptions and send me an email listing the issues. I pass in the exception and the class/method that caused it:
public static void exceptionhandler(DmlException e, string className){
	string messages='\r\r';
		
	for(integer i = 0 ; i < e.getNumDml(); i++){
		
		messages = messages+'\r\r'+i+1+') '+e.getDmlType(i)+'\r'+'Record Id - '+e.getDmlId(i)+'\rFields Affected - ';
			
		string fieldsAffectedDML = '';
		for(string s : e.getDmlFieldNames(i)){
			fieldsAffectedDML = fieldsAffectedDML+s+', ';
		}
			
		messages = messages+fieldsAffectedDML+'\rError Message - '+e.getDmlMessage(i)+'\r\r';
	}
		
	Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
	message.setSubject('DML Error in class/method - '+className);
	message.setPlainTextBody('There has been a DML Exception that may have caused some unexpected behaviours'+messages);
	message.setToAddresses(new String[] {'arouse@thunderhead.com'});
	Messaging.sendEmail(new Messaging.Email[] {message});
		
	}
Here are the issues I'm facing:
  • The getDMLId() function always returns null
  • The getDMLFieldNames() function always returns null
Does anybody have any ideas?

i dont know where should i give rendered attribute to hide fields.. could u help for this?
VF page:
<apex:page controller="SuccessController1" showheader="false">
<apex:form id="file1">
<apex:pageMessages id="msg"/>
<apex:pageBlock title="CandidateInformation" mode="edit">
<apex:pageBlockSection title="Information" columns="2">
<apex:inputField value="{!cand.FirstName__c}"/>

<apex:inputField value="{!cand.LastName__c}" />


<apex:inputField value="{!cand.SSN__c}" />


<apex:inputField value="{!cand.city__c}" />


<apex:inputField value="{!cand.Phone__c}"  />
<apex:inputField value="{!cand.Email__c}"  />


<apex:commandButton action="{!save}" value="save"/>
<apex:outputPanel id="file1" rendered="{!hidefn}">
</apex:outputPanel>
</apex:pageBlockSection>
</apex:pageBlock>

</apex:form>
</apex:page>

controller:

public with sharing class SuccessController1 {
public boolean hidefn { get; set; }
    public SuccessController1() {

hidefn=false;
    }
Candidate__c cand = new Candidate__c();
Public Candidate__c getCand()
  {
 
   return Cand;
   }
  public SuccessController1(ApexPages.StandardController controller)
    {

      }
      public PageReference save()
      {
      insert cand;
      PageReference p = apexPages.currentPage();
      ApexPages.Message msg=new ApexPages.Message(ApexPages.Severity.CONFIRM,'Record Created Successfully.Thank you!');
      ApexPages.addMessage(msg);
      return p;
      }
    }

But I don't know where we have to use that "rendered "attribute in vf page...after  clicking save button i want to show  success message with blank page...
If i use that rendered attribute in input field.....that field will be hided before giving input...Anyone can help for this..
I am trying to create an extension for my Key_Account_Overview__c object pulling specifically filtered lists from my Kam_Plan_Actions__c object which is a master detail child of Key_Account_Overview__c.

my extension class (KAMKAPextension) seems to have no errors and neither does my VF page (KAMbasic) but when I render the VF page I get:

Visualforce Error
Help for this Page

System.TypeException: Invalid conversion from runtime type SOBJECT:Key_Account_Overview__c to SOBJECT:Kam_Plan_Actions__c
Class.KAMKAPextension.<init>: line 14, column 1

I am pretty sure I have made an illegal assignment in line 14 but can't figure it out, I am trying to teach myself APEX currently so it may be a complete newbie mistake but I just don't know enough yet to spot my mistake.

this.KAP = (Key_Account_Overview__c)KAPController.getRecord();

any help would be much appreciated, the code for my class and page are below, please ignore the place holder Items I am focusing on the lists first and the rest were injected for proposal demo purposes for my COO.

Extension class:
public class KAMKAPextension 
{
  private final Kam_Plan_Actions__c KAP;
    List<Kam_Plan_Actions__c> overdue;
    List<Kam_Plan_Actions__c> next30days;
    List<Kam_Plan_Actions__c> from30to60days;
    List<Kam_Plan_Actions__c> from60to90days;
    List<Kam_Plan_Actions__c> longterm;
    List<Kam_Plan_actions__c> Completed;
    List<Kam_Plan_actions__c> Postponed;
    
  public KAMKAPextension(ApexPages.StandardController
								KAPController) {
								this.KAP = (Key_Account_Overview__c)KAPController.getRecord();
								}
  Public list<Kam_Plan_Actions__c>
        getoverdue() {
            If (overdue == null) 
            {
                overdue = [
                    SELECT Id, Name, Status__c, Due_Date__c 
                    FROM Kam_Plan_Actions__c 
                    WHERE due_date__c < TODAY AND Status__c !='Complete' AND Status__c !='Cancelled'];
            }
            return overdue;
        }
    Public list<Kam_Plan_Actions__c>
        getnext30days() {
            If (next30days == null) 
            {
                next30days = [
                    SELECT Id, Name, Status__c, Due_Date__c 
                    FROM Kam_Plan_Actions__c 
                    WHERE due_date__c >= TODAY AND due_date__c = NEXT_N_DAYS:29 AND Status__c !='Complete' AND Status__c !='Cancelled'];
            }
            return next30days;
        }
    Public list<Kam_Plan_Actions__c>
        getfrom30to60days() {
            If (from30to60days == null) 
            {
                from30to60days = [
                    SELECT Id, Name, Status__c, Due_Date__c 
                    FROM Kam_Plan_Actions__c 
                    WHERE due_date__c !=NEXT_N_DAYS:29  AND due_date__c = NEXT_N_DAYS:59 AND Status__c !='Complete' AND Status__c !='Cancelled'];
            }
            return from30to60days;
        }
    Public list<Kam_Plan_Actions__c>
        getfrom60to90days() {
            If (from60to90days == null) 
            {
                from60to90days = [
                    SELECT Id, Name, Status__c, Due_Date__c 
                    FROM Kam_Plan_Actions__c 
                    WHERE due_date__c !=NEXT_N_DAYS:59  AND due_date__c = NEXT_N_DAYS:89 AND Status__c !='Complete' AND Status__c !='Cancelled'];
            }
            return from60to90days;
        }
    Public list<Kam_Plan_Actions__c>
        getlongterm() {
            If (longterm == null) 
            {
                longterm = [
                    SELECT Id, Name, Status__c, Due_Date__c 
                    FROM Kam_Plan_Actions__c 
                    WHERE due_date__c > TODAY AND due_date__c != TODAY AND due_date__c !=NEXT_N_DAYS:89 AND Status__c !='Complete' AND Status__c !='Cancelled'];
            }
            return longterm;
        }
  
}

VF Page:
<apex:page showHeader="true" docType="html-5.0" StandardController="Key_Account_Overview__c" extensions="KAMKAPextension">  
<!-- Style Override -->
     <style>
        .activeTab {background-color: blue; color:white; font-style:italic; font-weight:bold;
        background-image:none}
        .inactiveTab { background-color: lightblue; color:black;font-style:normal; font-weight:normal;
        background-image:none}
    </style>

<!---Tab Panel: -->
        <apex:tabPanel switchType="client" selectedTab="tabdetails"
        id="AccountTabPanel" tabClass="activeTab"
        inactiveTabClass="inactiveTab">
<!-- Individual Tabs -->
            <apex:tab label="Executive Summary" name="ExSum" id="tabExec">
<chatter:follow entityId="{!Key_Account_Overview__c.id}"/>
                <chatter:followers entityId="{!Key_Account_Overview__c.id}"/>
                <apex:pageBlock title="Executive Summary">
                    <Apex:outputField label="Executive Overview" value="{!Key_Account_Overview__c.Executive_Summary__c}"/>
                </apex:pageBlock>
                <apex:pageBlock title="Financial variance">
                  <br>Financial Variance percentages goe here:</br>
                  <br>1. Estimate v Target</br>
                  <br>2. Actual v Target</br>
                  <br>3. Actual v Estimate <Apex:outputField label="Actual v Estimate" value="{!Key_Account_Overview__c.Financials_Variance__c}"/></br>
                </apex:pageBlock>
            </apex:tab>
            <apex:tab label="Chatter">
                <chatter:feed entityId="{!Key_Account_Overview__c.id}"/>
            </apex:tab>
            <apex:tab label="Company Profile" name="CompanyProfile" id="tabComPro">
                <apex:pageBlock title="Company information">
                    <Apex:outputField value="{!Key_Account_Overview__c.Company_Information__c}"/>
                </apex:pageBlock>
                <apex:pageBlock title="Financials">
                  <br>"Target Financials:    "<apex:outputfield label="Target Financials" value="{!Key_Account_Overview__c.Target_Financials__c}"/> </br>
                  <br>"financials last Year:    "<apex:outputfield label="financials last Year" value="{!Key_Account_Overview__c.Financials_last_year__c}"/></br>
                  <br>"financials this Year:    "<apex:outputfield label="financials this Year" value="{!Key_Account_Overview__c.Financials_this_year__c}"/></br>
                </apex:pageBlock>
               <apex:pageBlock title="Port Call Data">
                   <br><apex:outputfield label="Port calls this year" value="{!Key_Account_Overview__c.Port_Calls_this_year_to_date__c}"/> </br>
                   <br><apex:outputfield label="Port calls last year" value="{!Key_Account_Overview__c.Port_Calls_last_year__c}"/> </br>
                   <br><apex:outputfield label="Port Call Variance" value="{!Key_Account_Overview__c.Port_Calls_variance__c}"/> </br>
               </apex:pageBlock>
            </apex:tab>
            <apex:tab label="Key Progress Indicators" name="KPI"
            id="tabKPI">
            <apex:relatedList subject="{!Key_Account_Overview__c}" list="Account_Analyses__r" />
            <apex:relatedList subject="{!Key_Account_Overview__c}" list="QCR_Grids__r" />
            <apex:relatedList subject="{!Key_Account_Overview__c}" list="Objective_Progress_Trackers__r" />
            </apex:tab>
            <apex:tab label="Customer Objectives" name="CustomerObjectives"
            id="tabCusObj">
            <apex:pageBlock title="Customer Objectives">
            <br><b>Primary Objectives</b><apex:outputfield value="{!Key_Account_Overview__c.Primary_Customer_objectives__c}"/> </br>
<br><b>Secondary Objectives </b><apex:outputfield value="{!Key_Account_Overview__c.Secondary_Customer_objectives__c}"/> </br>
</apex:pageBlock>
            </apex:tab>
            <apex:tab label="KAM Objectives"
            name="KAMObjectives" id="tabKAMObj">
            <apex:pageBlock >
<br><b>Kam Objectives </b><apex:outputfield label="Primary cust. objectives" value="{!Key_Account_Overview__c.KAM_Objectives__c}"/> </br>

</apex:pageBlock>
            </apex:tab>
<!-- KAM Plan tab Accordian style -->
            <Apex:tab label="KAM Plan" Name="KAMPlan" id="KAMP">
            <apex:form >
            <apex:pageblock title="KAM Plan">
            <br>KAM Mission overview goes here....</br>
            </apex:pageblock>
            <apex:pageblock >  
        <c:Accordion >
            <c:AccordionSection title="Overdue" >
            	<apex:pageBlockTable value="{!overdue}"  var="kact">
                    <apex:column Headervalue="Kam Action" value="{!kact.name}"/>
                </apex:pageBlockTable>
            </c:AccordionSection>
            <c:AccordionSection title="Next 30 days">
            </c:AccordionSection>
            <c:AccordionSection title="Next 60 days">
            </c:AccordionSection>
            <c:AccordionSection title="Next 90 days">
            </c:AccordionSection>
            <c:AccordionSection title="Long Term View">
            </c:AccordionSection>
    </c:Accordion>
    </apex:pageblock>
            </apex:form>
            </apex:tab>
        </apex:tabPanel>

 </apex:page>

Hi,

I have checkbox field on the contact object and i have to show the  count of the contacts on which this checkbox field have been checked on the account object..I am getting the followign error.I am not sure where I am going Wrong.Can somebody please help?

The error is:-Method does not exist or incorrect signature: [String].Size() at line 32 column 39


trigger BillingContactsCount on Contact (after Insert,after update) {
list<id> accountids=new list<id>();
for(contact c:trigger.new)
    {
        if(c.billingcontacts__c==true)
            {
         
           
            Accountids.add(c.accountid);
            System.debug('The account type checks are as follows'+Accountids.get(0));
           

            }
      
                 
    }

    list<contact> cc=[Select id,billingcontacts__c,Accountid from contact where accountid in:Accountids and billingcontacts__c=true];
    Map<ID,String>m=new map<ID,String>();
  
    for(Contact d:cc)
    {
   
     m.put(d.accountid,d.id);
    
   
    }
    for(Id ids:Accountids)
    {
   
    Account acc=new account(id=ids);
    acc.ContactCount__c=m.get(acc.id).Size();
   
    }
  }
Hi...being new to triggers and APEX, I'm in need of some help on an error I received...

I currently have a trigger that automatically updates a Lead Status and Lead Custon Field (Stage_C) based on the completion of an Activity. Below is my code for the tigger...which, works perfect:

trigger changeLeadStatustask2 on Task (before insert, before update) {
    List<Lead> LeadToUpdate = new List<Lead>();
        for (Task tsk: Trigger.new){
            if(tsk.Status=='Completed' && tsk.Subject=='Call to Qualify (Successful)'){
                Lead ld = new Lead(Id=tsk.whoid);
                   ld.Status = 'Qualified';             
                     ld.Stage__c = 'Qualified - Convert to QP';
                LeadToUpdate.add(ld);           
            }
           
        }       
        update LeadToUpdate;
    }

However...when I attempt to convert this Lead into an Account, I get the below error/exception:

Error: System.DmlException: Update failed. First exception on row 0 with id 00TR000000EdoDYMAZ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, changeLeadStatustask2: execution of BeforeUpdate caused by: System.TypeException: Invalid id value for this SObject type: 003R000000ojtF5IAI Trigger.changeLeadStatustask2: line 5, column 1: [] (System Code)

Any help would be most appreciated!!! Thank you!!!

What I am trying to do is look at the asset related list under the account object.  I want to sum up the Price field (MRR) for each asset that shows a status of "Active / Live".  If it sums up to <$1000 I want it to set a field called "Customer Type" to Bronze <1000, and if the sum of the assets with that Active / Live status is greater than $1000 but less than $2000, I want the Customer Type field to set to Silver....and so on.  I am really new to coding and am not sure how to proceed.  I was able to get the following code to count the number of assets and populate a custom field I made with that number.  I figured I could some how make this sum instead of count and then use if statements to update the Customer Type field based on the sum of that field.  Please advise what the best way of accomplishing this? 

trigger trgr_Customer_Tier_AutoUpdate on Account (before update) {

    Map <Id,integer> assetCount = new Map<Id,integer>();
   
    for(Account a:[SELECT Id,(select Id from Assets) from Account where Id IN:Trigger.New]){
   
        integer count = 0;
        for(Asset asset:a.Assets){
            count++;
        }
        assetCount.put(a.Id, count);
    }
   
    for(Account account:Trigger.New){
       
        account.Asset_Count__c=assetCount.get(account.Id);
        }
    }
Hello,

I'm trying to pare down the debug logs by reducing the log level in the "filter" part of the user I'm monitoring. Each time I "save" the filter changes, I go back and check and they've reset. This became apparent after multiple deployment runs and still seeing the log entries I'd excluded.

Any idea?

thanks,
david.
The below trigger is throwing "System.NullPointer Exception.Attempt to de-reference a null object",  when there are no products associated with opportunity! When we add Opp to a custom object(detail side) , this trigger will fetch all the Products on this Opp to a field on this custom object,if there are no products sholud leave this field empty but on saving it is throwing the above error.Kindly help out with a solution for this. Thanks....

trigger productnames on cobj__c(before insert,before update) {
List<Id> oppIds = new List<Id>();
for(cobj__c co : Trigger.new)          //cobj__c is custom object
{
oppIds.add(co.Opportunity__c);    //Opportunity__C is the Opportunity master field on this object.
}
Map<Id,List<String>> oppIdToProdNameMap = new Map<Id,List<String>>();
for(OpportunityLineItem p2: [Select Id, Product2.Name,OpportunityId from OpportunityLineItem where OpportunityId in :oppIds])
{
   
     if(oppIdToProdNameMap.containsKey(p2.OpportunityId ))
      {
        List<String> l1 = oppIdToProdNameMap.get(p2.OpportunityId);
        l1.add(p2.Product2.Name);
        oppIdToProdNameMap.put(p2.OpportunityId,l1);
      }
     else
      {
        List<String> l1 = new List<String>();
        l1.add(p2.Product2.Name);
        oppIdToProdNameMap.put(p2.OpportunityId,l1);
      }
}
for(cobj__c co : Trigger.new)
{
 
    String s = '';
    boolean first = true;
    for(String p : oppIdToProdNameMap.get(co.Opportunity__c))
    {
    
        if(!first)
            s+=',';
        first = false;
        s += p;
      
    }
    co.Product_Names__c = s;  //field to populate
}
}
  • June 12, 2014
  • Like
  • 0
Hi all,

I have a probleme to retrieve WhatId argument in my trigger.
When the triggers is fired on the event and Related To field is different from Opportunity,
I get the following error message on my Event when Related To is an Account :
(It works only When Event is Realted To Opportunity)

"Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger Trigger_Event_Send_Email caused an unexpected exception, contact your administrator: Trigger_Event_Send_Email: execution of BeforeUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.Trigger_Event_Send_Email: line 41, column 1"


If the Event is Related To an Account, the trigger is always looking for Related To Opportunity
The aim is to keep the WhatId value in a string ( Account, Opportunity, leads...) and print the value in the body of the email,
Could you help me correct my trigger please?
trigger Trigger_Event_Send_Email on Event (before update) {
    Set<Id> ownerIds = new Set<Id>();
    Set<Id> initiatorIds = new Set<Id>();
    Set<Id> OpptyIds = New Set<Id>();
    Set<Id> AccIds = New Set<Id>();

   
    for(Event evt: Trigger.New)
    //Assigned TO
        ownerIds.add(evt.OwnerId);
    Map<Id, User> userMap = new Map<Id,User>([select Name, Email from User where Id in :ownerIds]);
  
    For(Event evt: Trigger.New)
    //Created By
        initiatorIds.add(evt.CreatedById);
    Map<Id, User> userMap2 = new Map<Id,User>([select Name, Email from User where Id in :initiatorIds]);
  
    For(Event evt : Trigger.New)
  //WhatId = Action
        OpptyIds.add(evt.WhatId);
    Map<id, Opportunity> OpptyMap = new Map<Id,Opportunity>([select Name from Opportunity where Id in :OpptyIds]);
    
    For(Event evt : Trigger.New)
  //WhatId = Account
        AccIds.add(evt.WhatId);
    Map<id, Account> AccMap = new Map<Id,Account>([select Name from Account where Id in :AccIds]);
    
    

    for(Event evt : Trigger.New)  {
        User User = userMap2.get(evt.CreatedById);
        User Assignee = userMap.get(evt.ownerId); 
        Opportunity RelatedTo = OpptyMap.get(evt.WhatId);       
        Account RelatedTo2 = AccMap.get(evt.WhatId);       
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {Assignee.Email};
        mail.setToAddresses(toAddresses);    // Set the TO addresses
        mail.setSubject('A visit Report owned by you is due soon');    // Set the subject

      String Whatid ; 
       if (RelatedTo.Name == '')
       whatid = RelatedTo2.Name;
       
       if (RelatedTo2.Name == '')
       whatid = RelatedTo.Name;

        String template = 'Hello {0}, \nThe following Visit Report is due soon:\n';
        
        String duedate = '';       
        template+= '\n';
        template+= 'Due Date - {1}\n';
        template+= 'Type - {2}\n';     
        template+= 'Subject - {3}\n';
        template+= 'Assign To - {4}\n';
        template+= 'Related To - {5}\n';   
        template+= '\n';
        template+='Click on the following link to access the Visit Report:\n';
        template+= '{6}\n';
        
        //String duedate = '';
    If(System.now() == evt.Send_Email_Alert__c )   
         evt.SendEmailAlert__c = True;
        if (evt.EndDateTime ==null)
            duedate = '';
        Else
           duedate = evt.EndDateTime.format();
                  
               List<String> args = new List<String>();

        args.add(Assignee.Name);
        args.add(duedate);
        args.add(evt.type);
        args.add(evt.subject);
        args.add(Assignee.Name);
        args.add(whatid);
        args.add('https://'+System.URL.getSalesforceBaseURL().getHost()+'/'+evt.Id);
        
        // Here's the String.format() call.
        String formattedHtml = String.format(template, args);
       
        mail.setPlainTextBody(formattedHtml);
        Messaging.SendEmail(new Messaging.SingleEmailMessage[] {mail});
     
            
            }
    }
Many thanks!
Hi All,

I am trying to create a VF page to upload users's chatter profile picture. I know about the OOB way but we have a requirement to upload it using Visual force pages. 

Following is the code that I have developed. But I am recieving the following error. Please help me to troubleshoot this or if there is any workaround. I am okay to use any other fuction, but once the user uploads an image that has to be set as her profile. Even if that is cropped automatically and saved that is fine, or if we can even crop it that also will be great. 

I recieve following error: ConnectApi.ConnectApiException: Illegal value for parameter: 'fileId': 015L0000000ENip
Error is in expression '{!upload}' in component <apex:commandButton> in page profilephotoupload

An unexpected error has occurred. Your solution provider has been notified. (ConnectApi)

Following is the code. 

VF Page:

<apex:page controller="FileUploadController">
  <apex:sectionHeader title="Visualforce Example" subtitle="File Upload Example"/>

  <apex:form enctype="multipart/form-data">
    <apex:pageMessages />
    <apex:pageBlock title="Upload a File">

      <apex:pageBlockButtons >
        <apex:commandButton action="{!upload}" value="Save"/>
      </apex:pageBlockButtons>

      <apex:pageBlockSection showHeader="false" columns="2" id="block1">

        <apex:pageBlockSectionItem >
          <apex:outputLabel value="File Name" for="fileName"/>
          <apex:inputText value="{!document.name}" id="fileName"/>
        </apex:pageBlockSectionItem>

        <apex:pageBlockSectionItem >
          <apex:outputLabel value="File" for="file"/>
          <apex:inputFile value="{!document.body}" filename="{!document.name}" id="file"/>
        </apex:pageBlockSectionItem>

        <apex:pageBlockSectionItem >
          <apex:outputLabel value="Description" for="description"/>
          <apex:inputTextarea value="{!document.description}" id="description"/>
        </apex:pageBlockSectionItem>

        <apex:pageBlockSectionItem >
          <apex:outputLabel value="Keywords" for="keywords"/>
          <apex:inputText value="{!document.keywords}" id="keywords"/>
        </apex:pageBlockSectionItem>

      </apex:pageBlockSection>

    </apex:pageBlock>
  </apex:form>
</apex:page>

Controller:

public without sharing class FileUploadController {

  public Document document {
    get {
      if (document == null)
        document = new Document();
      return document;
    }
    set;
  }

  public PageReference upload() {
    Id ImageId;
    document.AuthorId = UserInfo.getUserId();
    document.FolderId = UserInfo.getUserId(); // put it in running user's folder

    try {
      document.type = 'jpg'; 
      document.IsPublic = true;
      insert document;
      ImageId = document.id;
      //ConnectApi.ChatterUsers newPhoto = new ConnectApi.ChatterUsers();
         
   
   
    } catch (DMLException e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading file'));
      return null;
    } finally {
      document.body = null; // clears the viewstate
      document = new Document();
    }

    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'File uploaded successfully : '+ImageId ));
    String communityId = null;
    String userId= UserInfo.getUserId();
    ID fileId = ImageId;

    // Set photo
    ConnectApi.Photo photo = ConnectApi.ChatterUsers.setPhoto(communityId, userId, fileId, null);
    return null;
  }

}

Thanks a lot,
Nidhi M
Hi,

I have two custom buttons: one in the list view and one in the detail page for a custom object. The onClick Javascript code for the list button was able to get all the record Ids. But the code for the detail page button was not able to get any id at all. Both buttons call the same Apex class. I followed the code sample from http://developer.force.com/cookbook/recipe/creating-a-button-with-apex.
onClick Javascript Code for the Custom List Button on the Listview:
{!REQUIRESCRIPT("/soap/ajax/14.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/14.0/apex.js")}

var recordIdArray = {!GETRECORDIDS($ObjectType.Term_Sheet__c)};
console.log('the record Ids are' + recordIdArray);

if (recordIdArray.length) {
    alert("Calculating...");
    var retStr = sforce.apex.execute("LScurrMonthInterest",     "calculateInterestToDate",{ts_idList: recordIdArray});
    alert(result[0] + " Done!"); //response

} else if (recordIdArray.length == 0) {
    alert("Please select the Term Sheet to which" +
         " you would like to calculate current month interest as of today.");
}

~~~~~~~~~~~~
onClick Javascript Code for the Custom Detail Page Button on the Detail Page:
{!REQUIRESCRIPT("/soap/ajax/14.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/14.0/apex.js")}

var recordIdArray = {{!Term_Sheet__c.Id}};
console.log('the record Ids are' + recordIdArray);

if (recordIdArray.length) {
    alert("Calculating...");
    var retStr = sforce.apex.execute("LScurrMonthInterest",     "calculateInterestToDate",{ts_idList: recordIdArray});
    alert(result[0] + " Done!"); //response

} else if (recordIdArray.length == 0) {
    alert("Please select the Term Sheet to which" +
         " you would like to calculate current month interest as of today.");
}

~~~~~~~~~~~~~
Apex Class:
global class LScurrMonthInterest{

  WebService static void calculateInterestToDate(List<Id> ts_idList) {
   .......
  }
}


I created a validation rule for the standard probability stage in opportunities. What I need the rule to do is limit the users to entering percentages only divisible by 10 with three exceptions. 1) They can never use 50% for any stage. 2) The minimum is 10% unless the stage is 'closed lost' which has a probability of 0%. 3) The maximum is 90% unless the stage is 'closed won' which has a probability of 100%. I can get the error message to come up only when 100% is entered on a stage other then closed won. The system still allows 0% and 50%. Here is my rule:

OR(
AND(
!ISPICKVAL(StageName,"Closed Won"),
Probability<>0.50,
MOD(Probability*100,10)<>0)
,
AND(
!ISPICKVAL(StageName,"Closed Won"),
Probability=1)
)

Can someone help me and show me what I'm doing wrong?
Thanks
Hi

I wanna pass the value of a Campaign ID from a VF Page controller to an Apex Batch Class.

Here is my VF Controller's function:

public with sharing class SendCECertificate {
     public Campaign CAMP { get; set; }
     public Campaign CAMPID { get; set; }
    
     // Class Constructor
      public SendCECertificate(ApexPages.StandardController controller){
         CAMP =  (Campaign)controller.getRecord();              CAID = (Id)CAMP.Id; 
         CAMPID = (Id)CAMP.Id;     // this works fine
      }

      // This function is called from a commandLink  on a VF page
      public void sendEmail(){      
        // Invoke Batchclass from here....
        Database.executeBatch(new SendEmailBatchable(null), 10);
        // Keeping size to 10 to be under emailing governor limits... but how do we pass the CAMPID here? Can this function be overloaded?
    }


And then in the Apex Batch class, I wanna fetch the CAMPID

Here is the batchable class....

global class SendEmailBatchable implements Database.Batchable<SObject>, Database.Stateful {
private String query;
    private Id jobId;   
   
    global SendEmailBatchable(String query) {       
        this.query = query;
        if (this.query == null) {           
          this.query = 'SELECT Attended_CE_Training__c, CE_Credit_Certificate_Sent__c, CE_Credit_Certificate_Sent_Date__c, CampaignId, Id,ContactId, Event_Campaign_Comments__c, Primary_Language__c, RecordTypeId, RecordType.Name, Status, Contact.FirstName, Contact.Email FROM CampaignMember where CampaignId=\'701c0000000CHHz\' ' ;    // NOTE: I wanna replace this hardcoded ID with CAMPID which has to be sent from the VF controller
        }
    }
   
     global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext bc, List<SObject> batch) {    
      sendMail((List<CampaignMember>) batch );
      // Logic to fire email in batches of 10 as follows.....
     
    }
   
     public static void sendMail(List<CampaignMember> batch){
     
     }
    
     global void finish(Database.BatchableContext bc) {
         // Send a a confirmation email to the User who invoked the email blast
         ////// Database.executeBatch(new EAppBatchable(null), 2000);
    }
   
}

Any suggestions, what is the best way to do this?

Thanks
VK
  • May 30, 2014
  • Like
  • 0
Help with validation if one picklist is populated another one needs to be null.  Basically the user can only choose a value from Picklist 1 OR Picklist 2. Not both.
I tired the following validation rule but it's not working.

(ISPICKVAL(WidgetA__c '')) =
(ISPICKVAL(WidgetB__c, ''))
Hi All,

I'm really struggling to get my head around apex test clases. I've build a very basic save controller to help with a function on a small but of VisualForce page. It simply redirects back to the apex page when you save the record.
I just don't know how to build the test class for it. Here's my code:

public with sharing class DemoExtension
{
   ApexPages.StandardController stdCtrl;
   // extension constructor
   public DemoExtension(ApexPages.StandardController std)
   {
      stdCtrl=std;
   }

   public PageReference save()
   {
      stdCtrl.save();
      PageReference pr=Page.Demo_Q_and_A;
      pr.setRedirect(false);
      return pr;
   }
}
How do I build a class to test the save function?

Thanks
i want to insert,update two custom fields in an object. i wrote trigger

trigger availableLeavesTrigger on Leave_Request__c (after insert,after UPDATE) {
List<id> lrs=new List<id>();
List<Leave_request__c> lea=new List<Leave_request__c>();
for(Leave_Request__c leave:Trigger.New)
{
  lrs.add(leave.id);
}
List<Leave_request__c> lc=[select id,name,available_casual_leaves__c,available_sick_leaves__c,days_off__c,type_of_leave__C from leave_request__c where id =:lrs ];
for(Leave_Request__c leave:lc)
{
    if(leave.type_of_leave__C=='casual leave')
    {
        leave.available_casual_leaves__c=leave.available_casual_leaves__c-leave.days_off__c;   
        lea.add(leave);  
    }
    else if(leave.type_of_leave__c=='sick leave')
    {
        leave.available_sick_leaves__c=leave.available_sick_leaves__c-leave.days_off__c;
        lea.add(leave);
    }
}
update lea;
}

I just cant able to insert or update the values into the fields. could anyone help me out
We're seeking a Project Lead who will work-from-home as a part-time employee, managing and implementing 1 project (zero travel required). This position requires managing the entire project life cycle from kickoff to go-live. You must have salesforce expertise, the ability to develop the requirements gathering.

RESPONSIBILITIES
• Manage complex development projects on-time, on-budget, and to-spec.
• Identify detailed business requirements to lead Salesforce.com implementation within the scope of prioritized initiatives.
• Proactively audit Salesforce.com and improve configuration settings and keep current with the latest capabilities of each release.

REQUIREMENTS
• 5+ years of Salesforce platform experience (Sales Cloud, Service Cloud, General Configuration, etc...)
• Take complex client and vendor concepts and articulate them to audiences of varying perception levels.
• Excellent written, verbal presentation and organizational skills, ability to interface with all levels and business units.
• Must work independently in complex fast paced environment to ensure quality and timeliness of system information.

PREFERRED SKILLS
• Salesforce.com Certifications (Admin, Consultant, Developer).
• 3+ years of Servicemax platform experience
• Current or past Project Management Certification (PMP or equivalent).
• Experience work with or managing an offshore team

INTERESTED?
• Send your resume to jobs(at)end-2-end-performance.com
As a certified Salesforce consulting partner, PDO, and ISV, ForceBrain.com builds cloud & mobile apps. We've been a salesforce partner for over 6 years and you'll be joining a super fun team of true rockstars. We're seeking a Project Lead who will work-from-home as a full-time employee, managing 3 to 5 projects (zero travel required). This position requires managing the entire project life cycle from kickoff to go-live. You must have general salesforce expertise, the ability to lead the requirements gathering, and manage a few offshore developers.

RESPONSIBILITIES
• Manage complex development projects on-time, on-budget, and to-spec.
• Oversee developers to make sure requirements are being met and timeline is adhered to
• Identify detailed business requirements to support Salesforce.com implementation within the scope of prioritized initiatives.
• Develop comprehensive training materials and other change management collateral as appropriate for each initiative, deliver training to super users and end users as appropriate.
• Proactively audit Salesforce.com and improve configuration settings and keep current with the latest capabilities of each release.

REQUIREMENTS
• You are comfortable with speaking with clients - This position will require customer facing.
• 3+ years of Salesforce platform experience (Sales Cloud, Service Cloud, General Configuration, etc...)
• Take complex client and vendor concepts and articulate them to audiences of varying perception levels.
• Ability to lead enterprise engagements, facilitate meetings, and lead customer support projects.
• Excellent written, verbal presentation and organizational skills, ability to interface with all levels and business units.
• Must work independently in complex fast paced environment to ensure quality and timeliness of system information.

PREFERRED SKILLS
• Salesforce.com Certifications (Admin, Consultant, Developer).
• Current or past Project Management Certification (PMP or equivalent).
• Experience work with or managing an offshore team

INTERESTED?
• Send your resume to jobs(at)forcebrain.com
• Answer the questions on this form: http://goo.gl/forms/QtaEm7aeQJ

GENERAL STATS
• Full Time Employee
• Location: Remote, Work & Live Anywhere
• Salary with bonus and generous benefit package
• Applicant must be willing to work 8am PST - 5pm PST shift

ABOUT FORCEBRAIN.COM
• Established in 2008, ForceBrain.com manages an all-star team of Salesforce Consultants, Force.com Developers, and Technical Architects to design, develop, deploy, and support cloud & mobile solutions .
• We offer a competitive salary and benefits package, opportunity for continuous education & salesforce certifications, flexible working hours, tools for working remotely, casual dress at the office, quarterly company outings, and subsidized beverage and snack center.
• In 2010, ForceBrain.com became certified as a B-Corporation, recognizing the transparency in which we run our organization and our accountability in giving back.
I want Test Class For this Trigger for me it is covering 38 % i thinkk iam wron any one please help me .This is urgenyt issue.can anyone spend time on this
Here is my Trigger:
trigger UpdateNormalLeadwithWebLead on Lead (after insert){
    set<String> setEmails = new set<String>();
    List<Lead> updateExistingLead =New List<Lead>();
    List<Lead> deleteNewDupLead =New List<Lead>();
    map<String,Lead> mLeadsExisting = new map<String,Lead>();
    map<String,Lead> Leadmap = new map<String,Lead>();
   
    for(Lead LeadObj : trigger.new){
   
        if(LeadObj.Email != null){
            setEmails.add(LeadObj.Email);
            Leadmap.put(LeadObj.Email,LeadObj);
        }
       
    }
    System.debug('@@@Leadmap@@@'+Leadmap);
    if(setEmails.size() > 0 ){
        for(Lead LeadObj : [SELECT id,Email,LastName,Company,phone,isConverted FROM Lead where Email in : setEmails AND isConverted =False AND RecordType.Name='Registration']){
            mLeadsExisting.put(LeadObj.Email,LeadObj);
        }
    }
    System.debug('@@@mLeadsExisting@@@'+mLeadsExisting);
    for(Lead LObj: [SELECT id,Email,LastName,FirstName,Company,phone  FROM Lead WHERE Id NOT IN:Trigger.new]){
        if(LObj.Email != null && Leadmap.ContainsKey(LObj.Email )){
            //LObj.MobilePhone= Leadmap.get(LObj.Email).MobilePhone;
            LObj.Phone = Leadmap.get(LObj.Email).Phone;
            LObj.LastName = Leadmap.get(LObj.Email).LastName;
            LObj.FirstName = Leadmap.get(LObj.Email).FirstName;
            LObj.Company= Leadmap.get(LObj.Email).Individual_Company__c;
            LObj.City= Leadmap.get(LObj.Email).City;
            LObj.Street= Leadmap.get(LObj.Email).Street;
            LObj.State= Leadmap.get(LObj.Email).State;
            LObj.Registered_Online__c=Leadmap.get(LObj.Email).Registered_Online__c;
            LObj.Title=Leadmap.get(LObj.Email).Title;
            LObj.Lead_Trigger__c=false;
            updateExistingLead.add(LObj);
        } 
    }
    System.debug('@@@updateExistingLead@@@'+updateExistingLead);
    if(!updateExistingLead.isEmpty()){
        try{
            Update updateExistingLead;
            System.debug('@@@updateExistingLead1@@@'+updateExistingLead);
        }
        catch(Exception e){
            System.debug('@@@Insert Failed Due to@@@'+e);
        }
        for(Lead LeadObj : [SELECT id,Email,LastName,FirstName,Company,phone FROM Lead WHERE Id IN:Trigger.new]){
            if(mLeadsExisting.containsKey(LeadObj.Email)){
                deleteNewDupLead.add(LeadObj);    
            }
        }
        if(!deleteNewDupLead.isEmpty()){
            delete deleteNewDupLead;
        }
    }
}
we hv two objects(standard) one is account (parent) and second is contact(child)

i want to populate the name field of account with the lastname field of contact .




here is what i could code .
; but this is not working 



trigger trigsetLastName on Contact (after insert,after update)
{
   Map<id,account> parentacc = new Map<id,account>();
    List<id> listids = new List<id>();
   
   
    for( contact childobj :Trigger.new)
    {
            listids.add(childobj.account);   // error in this line
    }
   
    parentacc= new map<id,account> ([select id,Name ,(select id,LastName from contacts) from account where id in: listids]);
   
    for ( contact c :trigger.new)
    {
        account myacc = parentacc.get(c.account);
        myacc.Name=c.LastName;
    }
    Update parentacc.values();
    }
Hi, my previous question had different errors when trying to setup this same result as a Formula field, now I'm doing it through Workflow Rules / Field Updates and experiencing different error messages.  It all seems to boil down that I can't check to see if a Text field is null(blank) using the "ISBLANK" logical unit.  I don't know why that would be an issue, as the ISBLANK function is supposed to work with Text fields as per the online help guide.  

Right now my formula looks like this:  

IF(ISBLANK(Response__c ), "Responded", "Original")

And my error looks like this:

Error: Formula result is data type (Text), incompatible with expected data type (true or false).

Rather odd, I don't get it.  
I am perplexed. I am recieving an error message on a related list when referencing formula fields on a custom object.  The error doesn't exist in the custom object so I know the formulas are working properly. For some reason the related list is having an issue. Here are a couple of screen shots. Any one have any ideas or ever into a similar situation? 

Image of custom object:

User-added image
And the errors on the related list on opportunity:

User-added image

Any help would be greatly appreciated! Thanks.
Hello,

I have a trigger that fires when a campaign is created and changes the default Member Status of Responded on the campaign to Registered, and also adds another status of Attended.  The trigger works well, but my test class is not covering line 19-26.  Does anyone know how I can get the test to cover these lines?

Trigger:
trigger CampaignMemberStatus on Campaign (after insert) {

if(checkRecursiveAI.runOnceAI())
{
   
    List<Campaign> newCamps = [select Id from Campaign where Id IN :trigger.new AND ParentID = Null];
    List<CampaignMemberStatus> cms = new List<CampaignMemberStatus>();
    Set<Id> camps = new Set<Id>();
    List<CampaignMemberStatus> cms2Delete = new List<CampaignMemberStatus>();
    List<CampaignMemberStatus> cms2Insert = new List<CampaignMemberStatus>();
   
    for(Campaign camp : newCamps){
      
            camps.add(camp.Id);
    }  
   
   
   for (CampaignMemberStatus cm: [Select Id, Label, CampaignID  FROM CampaignMemberStatus WHERE CampaignID IN :camps]){
      if(cm.Label == 'Responded' ){
            CampaignMemberStatus cms1 = new CampaignMemberStatus(CampaignId=cm.CampaignID, Label='Registered', HasResponded=false, IsDefault = False, SortOrder=4);          
            System.debug(cms1);
            cms2Delete.add(cm);
            cms2Insert.add(cms1);
           
            CampaignMemberStatus cms3 = new CampaignMemberStatus(CampaignId = cm.CampaignId, HasResponded=true, Label = 'Attended', SortOrder = 5);
            cms2Insert.add(cms3);

      }

    }
    //perform insert before delete because system requires at least one CMS for a Campaign
    insert cms2Insert;
    delete cms2Delete;

}

}

Test Class:

@isTest private class CampaignMembStatus{

    @isTest private static void test_Memb_Status() {
    
        Campaign camp=new Campaign(Name='Test Campaign',IsActive=True);
        insert camp;

    Test.StartTest();
    Test.StopTest();
        
    }
}


  • July 16, 2014
  • Like
  • 0
Dear all,

When you click on an "Analytics:reportChart" component on a VF, it will take you to the filtered report, which is great. However, this is actually a problem if the VG page is inline on a record. I'd like to be able to modify the onclick behaviour, so that it takes the parent window to the filtered report. I'm coming across these issues:
  1. Adding an "actionsupport" component seems to make no difference to the behaviour, or break the report
  2. Trying to surround the component with an outputPanel and adding an onClick attribute to that component breaks the report
  3. I'm unsure how to pass in the variables, so the report that gets run will have the right filters applied
The error I'm getting is: "Error while running $A.run() : Cannot read property 'descriptor' of undefined"

Is what I'm trying to do even possible?

Hey all, 

I have the following rule that works well:

AND(
NOT ISBLANK(MailingState),
LEN(MailingState )<>2
)


However, I need to exclude two record types called 'student' and 'professional' - how can I do that here without breaking the rule?

Thanks!
Hello everybody!
Here my example:

public class DemoController {

public List<User> mRecords { get; set; }
private Integer mRecordsCount { get; set; }

public ADemoController() {
  mRecordsCount = 1;
  mRecords = [SELECT Id, FirstName FROM User LIMIT :mRecordsCount];
}

public void loadOneMoreRecord() {
  mRecords.clear();
  mRecordsCount++;
  mRecords = [SELECT Id, FirstName FROM User LIMIT :mRecordsCount];
}

}


<apex:page controller="DemoController" >

<apex:pageMessages />

<apex:form id="TheForm">
  <apex:pageBlock id="TheBlok">
   <apex:commandButton value="Load one more record" action="{!loadOneMoreRecord}" reRender="TheTable" />
   <apex:pageBlockTable value="{!mRecords}" var="record" id="TheTable">
    <apex:column headerValue="Records">
     <apex:outputLink value="/{!record.Id}"><apex:outputText value="{!record.FirstName}" /></apex:outputLink>
    </apex:column>
   </apex:pageBlockTable>
  </apex:pageBlock>
</apex:form>
 
</apex:page>

After first page loading the link is work fine, but after loading more records in table, links became dead (works only through rmc).
The question is how can I prevent this?

Sorry for my english.
Dear all,

I can't work out if I've misunderstood the documentation or if there's an issue with the code itself, but I'm trying to build a utility class that can handle DML exceptions and send me an email listing the issues. I pass in the exception and the class/method that caused it:
public static void exceptionhandler(DmlException e, string className){
	string messages='\r\r';
		
	for(integer i = 0 ; i < e.getNumDml(); i++){
		
		messages = messages+'\r\r'+i+1+') '+e.getDmlType(i)+'\r'+'Record Id - '+e.getDmlId(i)+'\rFields Affected - ';
			
		string fieldsAffectedDML = '';
		for(string s : e.getDmlFieldNames(i)){
			fieldsAffectedDML = fieldsAffectedDML+s+', ';
		}
			
		messages = messages+fieldsAffectedDML+'\rError Message - '+e.getDmlMessage(i)+'\r\r';
	}
		
	Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
	message.setSubject('DML Error in class/method - '+className);
	message.setPlainTextBody('There has been a DML Exception that may have caused some unexpected behaviours'+messages);
	message.setToAddresses(new String[] {'arouse@thunderhead.com'});
	Messaging.sendEmail(new Messaging.Email[] {message});
		
	}
Here are the issues I'm facing:
  • The getDMLId() function always returns null
  • The getDMLFieldNames() function always returns null
Does anybody have any ideas?

I have edited a trigger and test class to apply to my needs. I just need the custom object on conversion to update the custom object on an opportunity where previously it updated contact, account, and the opportunity. I recieve this error when testing
Failure Message: "System.Exception: SFSSDupeCatcher:Too many SOQL queries: 101", Failure Stack Trace: "(SFSSDupeCatcher)"
Is this an error with DupeCatcher or with the Trigger/test class.

Trigger:
trigger UpdateCustomeObject_Trigger on Lead (before update) {
//This trigger will associate a Custom Object record with the contact and opportunity associated to the
//lead after it has been converted.
//The Custom Object is associated to an opportunity only if an opportunity record exist on the Lead.
    for (Integer i = 0; i < Trigger.new.size(); i++){
        if (Trigger.new[i].IsConverted == true && Trigger.old[i].isConverted == false){
            Set<Id> leadIds = new Set<Id>();
            for (Lead lead : Trigger.new)
                leadIds.add(lead.Id);
           
            Map<Id, Reached_Out__c> entries = new Map<Id, Reached_Out__c>([select test__c, Lead__c from Reached_Out__c where lead__c in :leadIds]);       
            if(!Trigger.new.isEmpty()) {
                for (Lead lead : Trigger.new)  {
                    for (Reached_Out__c CustomObject : entries.values()) {
                        if (CustomObject.Lead__c == lead.Id) {
                            CustomObject.test__c = lead.ConvertedOpportunityId;
                            update CustomObject;
                        }
                    }
                }
            }
        }
    }

}

Test Class:
@isTest
//This is a test case for a situation where a lead will be converted.  The developer must explicitly call the convert lead
//method to simulate the user action.

private class TestTriggerCustomObjectUpdate {
        static testMethod void TestReferralUpdate() {
        // Insert the Lead
        List<Lead> leads = new List<Lead>();
        Lead leadt = new Lead (FirstName ='fname', LastName ='test', Company ='myCompany',  Website = 'TestWebsite.com', Origin_Date__C = Date.newInstance(2014,12,31), Origin__c = 'Other', Status = 'Exception', Exception_Notes__c='asdf');
        insert leadt;
        // Insert the custom object Record
        Reached_Out__C customobject = new Reached_Out__C (Lead__c = leadt.Id);
        insert customobject;       
       
        //Convert the Lead
        Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(leadt.Id);
        LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        Database.LeadConvertResult lcr = Database.convertLead(lc);   
       
        //Requery for the referral record to see if it is updated
        Reached_Out__C ref_upd = [select Test__c from Reached_Out__C where Lead__c = :leadt.Id];
       
        //Check that the test passed
        System.assertEquals(ref_upd.Test__c,[Select ConvertedOpportunityId From Lead Where Id = :customobject.Lead__c].ConvertedOpportunityId);      
   
        //Test if no opty is created
        string NoOpty = 'Y';       
        if (NoOpty =='Y'){
            Lead leadto = new Lead (FirstName ='fnameo', LastName ='testo', Company ='myCompanyo');
            insert leadto;
            // Insert the custom object record
            Reached_Out__C customobjecto = new Reached_Out__C (Lead__c = leadto.Id);
            insert customobjecto;
           
            Database.LeadConvert lco = new database.LeadConvert();
            lco.setLeadId(leadto.Id);
            lco.isDoNotCreateOpportunity();
            lco.setDoNotCreateOpportunity(true);
            LeadStatus convertStatuso = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1];
            lco.setConvertedStatus(convertStatuso.MasterLabel);
            Database.LeadConvertResult lcro = Database.convertLead(lco);
       
            Reached_Out__C ref_updo = [select Test__c from Reached_Out__C where Lead__c = :leadto.Id];
           
            //Check that the test passed
            System.assert(ref_updo.Test__c == null);
        }  
    }

    static testMethod void testBulkUpdate() {
        List<Lead> leads = new List<Lead>();      
        for (Integer i=0;i<5;i++) {
            Lead l = new Lead (FirstName ='bulk', LastName ='Test', Company ='myCompanyo');
            insert l;
            // Insert the Custom Record
            Reached_Out__C r = new Reached_Out__C (Lead__c = l.Id);
            insert r;
           
            //Convert the Lead
            Database.LeadConvert lcb = new database.LeadConvert();
            lcb.setLeadId(l.Id);
            LeadStatus convertStatusb = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1];
            lcb.setConvertedStatus(convertStatusb.MasterLabel);
            Database.LeadConvertResult lcrb = Database.convertLead(lcb);
           
            Reached_Out__C bulkup = [select  Test__c from Reached_Out__C where Lead__c =:l.Id];
           
            //Check that the test has passed
            System.assertEquals(bulkup.Test__c,[Select ConvertedOpportunityId From Lead Where Id = :r.Lead__c].ConvertedOpportunityId);
            }  
        }
}
Hi All,

I have written down a trigger(Trigger which sents out an email alert when the different fields are updated from the backend without editing the record) which is working fine in sandbox .But when I have deployed it to Production Its not working at the first go. But second time when AI go and update the record manually only then my code runs.

Also for referenece there is one other code which is running after update but that is running successfully.

Code of My Trigger-
trigger send_notification on Lead (after update) {
system.debug('send notification trigger active');
  Lead Ld = trigger.new[0];
  system.debug('mailid'+Ld.Mail_To_Vista_First__c);
  Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

  //mail.setTargetObjectId('Ld.OwnerID');
    system.debug('ownerID'+Ld.OwnerID);
  mail.setSenderDisplayName('do-not-reply@snapdeal.com');
  mail.setUseSignature(false);
  mail.setBccSender(false);
  mail.setSaveAsActivity(false);

if (Trigger.isUpdate) {
  system.debug('condition value'+Ld.Stage__c);
    if(Ld.Stage__c == 'Pre On-boarding' && Ld.Seller_Code_Generated__c == true && Ld.Pincode_Mapping_Completed__c == False &&( Ld.Mail_To_Vista_First__c !=null || Ld.Mail_To_Vista_First__c !='') ){
       
      // create email content
         system.debug('Lead Name : '+Ld.Name);
        String subject = 'Hi Partner';
        mail.setSubject(subject);
       
     //Message with line break tag
        mail.setHtmlBody('<html><body>Your  '+ Ld.Seller_Code__c+' an unique id with Snapdeal.com has been emailed to you.Please refer this code for any communication with us.<br>Best Regards<br>Snapdeal Team');   
     


     // add recipients
      String toAddresses =  Ld.Mail_To_Vista_First__c;
      system.debug('mail value +++'+ toAddresses);
      if( string.isNotBlank(toAddresses))
    {
  system.debug('value of toaddress'+string.isNotBlank(toAddresses));
     //Set your too addresses here based on task criteria
     String[] addresses = new String[] {toAddresses};
        mail.setToAddresses(addresses);
     
      }
      system.debug('mail value'+mail);
     if(toAddresses != null)
     {
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
   
        system.debug('sendemail'+r);  
     }
      }  
   }
}

Awaiting for your reply.
i dont know where should i give rendered attribute to hide fields.. could u help for this?
VF page:
<apex:page controller="SuccessController1" showheader="false">
<apex:form id="file1">
<apex:pageMessages id="msg"/>
<apex:pageBlock title="CandidateInformation" mode="edit">
<apex:pageBlockSection title="Information" columns="2">
<apex:inputField value="{!cand.FirstName__c}"/>

<apex:inputField value="{!cand.LastName__c}" />


<apex:inputField value="{!cand.SSN__c}" />


<apex:inputField value="{!cand.city__c}" />


<apex:inputField value="{!cand.Phone__c}"  />
<apex:inputField value="{!cand.Email__c}"  />


<apex:commandButton action="{!save}" value="save"/>
<apex:outputPanel id="file1" rendered="{!hidefn}">
</apex:outputPanel>
</apex:pageBlockSection>
</apex:pageBlock>

</apex:form>
</apex:page>

controller:

public with sharing class SuccessController1 {
public boolean hidefn { get; set; }
    public SuccessController1() {

hidefn=false;
    }
Candidate__c cand = new Candidate__c();
Public Candidate__c getCand()
  {
 
   return Cand;
   }
  public SuccessController1(ApexPages.StandardController controller)
    {

      }
      public PageReference save()
      {
      insert cand;
      PageReference p = apexPages.currentPage();
      ApexPages.Message msg=new ApexPages.Message(ApexPages.Severity.CONFIRM,'Record Created Successfully.Thank you!');
      ApexPages.addMessage(msg);
      return p;
      }
    }

But I don't know where we have to use that "rendered "attribute in vf page...after  clicking save button i want to show  success message with blank page...
If i use that rendered attribute in input field.....that field will be hided before giving input...Anyone can help for this..
I am trying to create an extension for my Key_Account_Overview__c object pulling specifically filtered lists from my Kam_Plan_Actions__c object which is a master detail child of Key_Account_Overview__c.

my extension class (KAMKAPextension) seems to have no errors and neither does my VF page (KAMbasic) but when I render the VF page I get:

Visualforce Error
Help for this Page

System.TypeException: Invalid conversion from runtime type SOBJECT:Key_Account_Overview__c to SOBJECT:Kam_Plan_Actions__c
Class.KAMKAPextension.<init>: line 14, column 1

I am pretty sure I have made an illegal assignment in line 14 but can't figure it out, I am trying to teach myself APEX currently so it may be a complete newbie mistake but I just don't know enough yet to spot my mistake.

this.KAP = (Key_Account_Overview__c)KAPController.getRecord();

any help would be much appreciated, the code for my class and page are below, please ignore the place holder Items I am focusing on the lists first and the rest were injected for proposal demo purposes for my COO.

Extension class:
public class KAMKAPextension 
{
  private final Kam_Plan_Actions__c KAP;
    List<Kam_Plan_Actions__c> overdue;
    List<Kam_Plan_Actions__c> next30days;
    List<Kam_Plan_Actions__c> from30to60days;
    List<Kam_Plan_Actions__c> from60to90days;
    List<Kam_Plan_Actions__c> longterm;
    List<Kam_Plan_actions__c> Completed;
    List<Kam_Plan_actions__c> Postponed;
    
  public KAMKAPextension(ApexPages.StandardController
								KAPController) {
								this.KAP = (Key_Account_Overview__c)KAPController.getRecord();
								}
  Public list<Kam_Plan_Actions__c>
        getoverdue() {
            If (overdue == null) 
            {
                overdue = [
                    SELECT Id, Name, Status__c, Due_Date__c 
                    FROM Kam_Plan_Actions__c 
                    WHERE due_date__c < TODAY AND Status__c !='Complete' AND Status__c !='Cancelled'];
            }
            return overdue;
        }
    Public list<Kam_Plan_Actions__c>
        getnext30days() {
            If (next30days == null) 
            {
                next30days = [
                    SELECT Id, Name, Status__c, Due_Date__c 
                    FROM Kam_Plan_Actions__c 
                    WHERE due_date__c >= TODAY AND due_date__c = NEXT_N_DAYS:29 AND Status__c !='Complete' AND Status__c !='Cancelled'];
            }
            return next30days;
        }
    Public list<Kam_Plan_Actions__c>
        getfrom30to60days() {
            If (from30to60days == null) 
            {
                from30to60days = [
                    SELECT Id, Name, Status__c, Due_Date__c 
                    FROM Kam_Plan_Actions__c 
                    WHERE due_date__c !=NEXT_N_DAYS:29  AND due_date__c = NEXT_N_DAYS:59 AND Status__c !='Complete' AND Status__c !='Cancelled'];
            }
            return from30to60days;
        }
    Public list<Kam_Plan_Actions__c>
        getfrom60to90days() {
            If (from60to90days == null) 
            {
                from60to90days = [
                    SELECT Id, Name, Status__c, Due_Date__c 
                    FROM Kam_Plan_Actions__c 
                    WHERE due_date__c !=NEXT_N_DAYS:59  AND due_date__c = NEXT_N_DAYS:89 AND Status__c !='Complete' AND Status__c !='Cancelled'];
            }
            return from60to90days;
        }
    Public list<Kam_Plan_Actions__c>
        getlongterm() {
            If (longterm == null) 
            {
                longterm = [
                    SELECT Id, Name, Status__c, Due_Date__c 
                    FROM Kam_Plan_Actions__c 
                    WHERE due_date__c > TODAY AND due_date__c != TODAY AND due_date__c !=NEXT_N_DAYS:89 AND Status__c !='Complete' AND Status__c !='Cancelled'];
            }
            return longterm;
        }
  
}

VF Page:
<apex:page showHeader="true" docType="html-5.0" StandardController="Key_Account_Overview__c" extensions="KAMKAPextension">  
<!-- Style Override -->
     <style>
        .activeTab {background-color: blue; color:white; font-style:italic; font-weight:bold;
        background-image:none}
        .inactiveTab { background-color: lightblue; color:black;font-style:normal; font-weight:normal;
        background-image:none}
    </style>

<!---Tab Panel: -->
        <apex:tabPanel switchType="client" selectedTab="tabdetails"
        id="AccountTabPanel" tabClass="activeTab"
        inactiveTabClass="inactiveTab">
<!-- Individual Tabs -->
            <apex:tab label="Executive Summary" name="ExSum" id="tabExec">
<chatter:follow entityId="{!Key_Account_Overview__c.id}"/>
                <chatter:followers entityId="{!Key_Account_Overview__c.id}"/>
                <apex:pageBlock title="Executive Summary">
                    <Apex:outputField label="Executive Overview" value="{!Key_Account_Overview__c.Executive_Summary__c}"/>
                </apex:pageBlock>
                <apex:pageBlock title="Financial variance">
                  <br>Financial Variance percentages goe here:</br>
                  <br>1. Estimate v Target</br>
                  <br>2. Actual v Target</br>
                  <br>3. Actual v Estimate <Apex:outputField label="Actual v Estimate" value="{!Key_Account_Overview__c.Financials_Variance__c}"/></br>
                </apex:pageBlock>
            </apex:tab>
            <apex:tab label="Chatter">
                <chatter:feed entityId="{!Key_Account_Overview__c.id}"/>
            </apex:tab>
            <apex:tab label="Company Profile" name="CompanyProfile" id="tabComPro">
                <apex:pageBlock title="Company information">
                    <Apex:outputField value="{!Key_Account_Overview__c.Company_Information__c}"/>
                </apex:pageBlock>
                <apex:pageBlock title="Financials">
                  <br>"Target Financials:    "<apex:outputfield label="Target Financials" value="{!Key_Account_Overview__c.Target_Financials__c}"/> </br>
                  <br>"financials last Year:    "<apex:outputfield label="financials last Year" value="{!Key_Account_Overview__c.Financials_last_year__c}"/></br>
                  <br>"financials this Year:    "<apex:outputfield label="financials this Year" value="{!Key_Account_Overview__c.Financials_this_year__c}"/></br>
                </apex:pageBlock>
               <apex:pageBlock title="Port Call Data">
                   <br><apex:outputfield label="Port calls this year" value="{!Key_Account_Overview__c.Port_Calls_this_year_to_date__c}"/> </br>
                   <br><apex:outputfield label="Port calls last year" value="{!Key_Account_Overview__c.Port_Calls_last_year__c}"/> </br>
                   <br><apex:outputfield label="Port Call Variance" value="{!Key_Account_Overview__c.Port_Calls_variance__c}"/> </br>
               </apex:pageBlock>
            </apex:tab>
            <apex:tab label="Key Progress Indicators" name="KPI"
            id="tabKPI">
            <apex:relatedList subject="{!Key_Account_Overview__c}" list="Account_Analyses__r" />
            <apex:relatedList subject="{!Key_Account_Overview__c}" list="QCR_Grids__r" />
            <apex:relatedList subject="{!Key_Account_Overview__c}" list="Objective_Progress_Trackers__r" />
            </apex:tab>
            <apex:tab label="Customer Objectives" name="CustomerObjectives"
            id="tabCusObj">
            <apex:pageBlock title="Customer Objectives">
            <br><b>Primary Objectives</b><apex:outputfield value="{!Key_Account_Overview__c.Primary_Customer_objectives__c}"/> </br>
<br><b>Secondary Objectives </b><apex:outputfield value="{!Key_Account_Overview__c.Secondary_Customer_objectives__c}"/> </br>
</apex:pageBlock>
            </apex:tab>
            <apex:tab label="KAM Objectives"
            name="KAMObjectives" id="tabKAMObj">
            <apex:pageBlock >
<br><b>Kam Objectives </b><apex:outputfield label="Primary cust. objectives" value="{!Key_Account_Overview__c.KAM_Objectives__c}"/> </br>

</apex:pageBlock>
            </apex:tab>
<!-- KAM Plan tab Accordian style -->
            <Apex:tab label="KAM Plan" Name="KAMPlan" id="KAMP">
            <apex:form >
            <apex:pageblock title="KAM Plan">
            <br>KAM Mission overview goes here....</br>
            </apex:pageblock>
            <apex:pageblock >  
        <c:Accordion >
            <c:AccordionSection title="Overdue" >
            	<apex:pageBlockTable value="{!overdue}"  var="kact">
                    <apex:column Headervalue="Kam Action" value="{!kact.name}"/>
                </apex:pageBlockTable>
            </c:AccordionSection>
            <c:AccordionSection title="Next 30 days">
            </c:AccordionSection>
            <c:AccordionSection title="Next 60 days">
            </c:AccordionSection>
            <c:AccordionSection title="Next 90 days">
            </c:AccordionSection>
            <c:AccordionSection title="Long Term View">
            </c:AccordionSection>
    </c:Accordion>
    </apex:pageblock>
            </apex:form>
            </apex:tab>
        </apex:tabPanel>

 </apex:page>

Assignment Rule for New Leads for Existing Accounts. How?

Hello,

I would like to write either a lead assignment rule, workflow rule or Apex Trigger to accomplish this.

We would like our lead assignment, trigger and/or workflow rules to check if the lead's COMPANY already exists as an ACCOUNT, and therefore assign the new lead to the proper ACCOUNT OWNER.

Is there a formula that anyone can provide me to make this happen?

It would be great if the formula would look for CONTAINS "ACCOUNT NAME" rather than a direct match, for cases where a new lead submits their company name in a format slightly different than our existing ACCOUNT NAME.

Thank you greatly for your help.
I would like to not allow attachments if a field, like  "Order Status"  equals "Processed".  Is there anyway of doing this?