• Robert Wambold 10
  • NEWBIE
  • 205 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 34
    Questions
  • 34
    Replies

I want to improve my Apex coding skills, other than Trail Head can anyone reccomend some good courses?

Thanks,

Robert

 

 

Hello all,

I have an Apex Trigger that fires when a custom check box field ( Freeze_User__c ) on the User object is updated. The process will set UserLogin.IsFrozen = true, Update Contact record, and send an email to the User's Manager if the User is owner of any Open Cases.

I have a request to include a table of Open Case information or a link to each Open Case.

I know I can build a List of Open Cases, but how do I display the data in a Dynamic Table?

I found a link  "Generate Collection Report" that uses GenerateCustomReport action to generate a chunk of HTML suitable for adding to the Body of an email action that supports rich text, like Send Rich Email.

https://unofficialsf.com/convert-record-data-into-tables-for-email-automation-with-generate-collection-report/

Has anyone used this action in an Apex Trigger?

Thanks for looking and offering assitance.

Best regards,

Robert

 

Hello,

I have a custom Time field called Scheduled_ET__c. The drop-down displays time in 15 minute increments, however we do not want the user to select 15 or 45 minute increments. Since there is no way I can find to eliminate 15 or 45 from the drop-down I need to find another soultion.

My thoughts are...use a validation rule or Apex to change the minutes to a 30 min increment.

Is it possble to extract the minutes part of a custom time field in Apex and how would one do that?

My rounding logic would be if user enters <16 round down to 00, >16 and <45 round to 30, >45 up to 00 and increment hour.

Any thoughts or suggestions would greatly be appreciated.

Kind regards,

Robert

Hello all,

I been struggling trying to get my Custom Email Template to display the current date/time using {!NOW()} and HyperLink to render.

When I so a Preview my email renders perfect. When I generate the email from Apex  {!NOW()} displays as "{!NOW()}" and Hyperlink as "HL_ENCODED_url_HL_OpenLink_HL__self_HL".

When I use an HTML Template I ge no output at all.

Any ideas?

Thank you!

Robert

 

Output from Preview

Output from APEX

 

Hello all,

Looking for advice. I have a trigger on the EmailMessage object where I use an SOQL query to look for more than 10 related records added in the last hour. My problem is that I only want to notify the administrator once, but not every record inserted after initial notification.

I was thinking I could create a "control" record with the last notification information and this culd be checked before send additional notifications.

Thanks in advance for suggestions.

I have attached my code for review and humor.

Kind regards,

Robert

 

trigger CountEmailMessagesCreated1HourAgo on EmailMessage (after insert) {

  String NEW_RelatedToId;
  DateTime OneHourAgo = System.Now().addHours(-1);
  List<String> EmlLst = new List<String>();
  String Email_Sent = 'No';
  
  for(EmailMessage Eml : Trigger.new)
  {
   NEW_RelatedToId=Eml.RelatedToId;  
   List<AggregateResult> EmlLst = [SELECT RelatedToId, COUNT(ID) 
                                                        FROM EmailMessage 
                                                        WHERE CreatedDate>=:OneHourAgo AND
                                                                      RelatedToId =:NEW_RelatedToId 
                                                        GROUP BY RelatedToId
                                                        HAVING Count(Id) >10
                                                       ];
      
      If (EmlLst.size() >0){
      If (Email_Sent == 'No'){
         List<Messaging.SingleEmailMessage> mails = new 
         List<Messaging.SingleEmailMessage>();
              Messaging.SingleEmailMessage mail = new 
              Messaging.SingleEmailMessage();
              String[] sendTo = new String[]{'Admin-1@group.com'};
              String[] sendToCc = new String[]{'Admin-2@group.com'};
              mail.setHtmlBody('Hello, <br/> This Case Id ' +NEW_RelatedToId +' has generated more than 10 Email Messages in the last hour. <br/><br/> Thanks, <br/>Salesforce Admin');
              mail.setSubject('Case EmailMessage Limit of 10 Exceeded');
              mail.setToAddresses(sendTo);
              mail.setCcAddresses(sendToCc);
              mails.add(mail);
              Messaging.sendEmail(mails);
              Email_Sent = 'Yes';
          return;}
     }
  
  } 
}
 

 

 

Hello All,

I have a trigger where I want to be alerted when more than 10 EmailMessage records are inserted in an hour. I am unable to get past  "Illegal assignment from list to list" error. I am at a loss what to do to solve.

Thanks for your help in advance!

Robert.


* Here's my code *

 

trigger CountEmailMessagesCreated1HourAgo on EmailMessage (after insert) {

  String NEW_RelatedToId;
  System.debug('Record Map: '+Trigger.newMap);
  DateTime OneHourAgo = System.Now().addHours(-1);
  System.debug('System.Now(): ' + System.Now());
  System.debug('One Hour Ago: ' + OneHourAgo);
  List<String> EmlLst = new List<String>();

  for(EmailMessage Eml : Trigger.new)
  {
   NEW_RelatedToId=Eml.RelatedToId;
   List<EmailMessage> EmlLst = [SELECT RelatedToId, COUNT(ID) 
                                FROM EmailMessage 
                                WHERE RelatedToId =:NEW_RelatedToId AND 
                                              CreatedDate>=:OneHourAgo
                                GROUP BY RelatedToId
                                HAVING Count(Id) >10
                               ];

     If (EmlLst.size() >0){
         List<Messaging.SingleEmailMessage> mails = new 
         List<Messaging.SingleEmailMessage>();
                 Messaging.SingleEmailMessage mail = new 
                 Messaging.SingleEmailMessage();
                 List<String> sendTo = new List<String>();
                sendTo.add('SendToSomeone.@gmail.com' );
                mail.setHtmlBody('Hello, <br/> This Case Id ' +NEW_RelatedToId +' has 
                generated more than 10 in the last hour. <br/><br/> Thanks, <br/>Salesforce 
                Admin');
                mail.setSubject('Case EmailMessage Limit of 10 Exceeded');
                mail.setToAddresses(sendTo);
                mails.add(mail);
                Messaging.sendEmail(mails);
     }
  } 
}
 

 

 

 

Hello All,

I am trying to get a  of EmailMessage records created in the last hour?

For some resaon it does not like my System.debug statement...any idea? 

User-added imageThanks for your help in advance!

Robert

 

 

Hello all,

I have a request to prevent users from pasting data into a text field, is this even possible?

Thanks in advance for your help!

Robert

 

 

 

Hello All,

Pretty simple question. My table amc_Project__c contains field Project_Manager__c (PM), If the User changes PM I want check if the NEW PM is different from the OLD PM. My problem is PM is Lookup field and when I compare in my code it is a Name vs  an Id. How do I make both either Names or Ids.

Thank you all.

Robert

 

My Code:

trigger Update_MC_Milestone_Action_Owners on amc__Project__c (after update) {

    Set<Id> ProjectId = new Set<Id>();
    String NEW_Project_Manager;
    String OLD_Project_Manager;
    
    for(amc__Project__c prj : Trigger.new)
    {
         if(prj.amc__Status__c !='All Products Offline' && prj.amc__Status__c !='Archived')
            System.debug('*** Project changed ***');
            NEW_Project_Manager=prj.Project_Manager__c;

            if(NEW_Project_Manager != trigger.oldMap.get(prj.Id).Project_Manager__c) {               
               System.debug('*** PM has changed ***');
               ProjectId.add(prj.Id);
               OLD_Project_Manager=trigger.oldMap.get(prj.Id).Project_Manager__c;
            }
    }

     List<amc__Milestone__c> mileToUpdate = new List<amc__Milestone__c>();

     for(amc__Milestone__c mil : [select id, amc__Milestone_Owner__c from amc__Milestone__c where amc__Project__c in: ProjectId])
     {
         if(System.Label.MC_Role_PM == mil.amc__Milestone_Owner__c || mil.amc__Milestone_Owner__c != OLD_Project_Manager){ 
             mil.amc__Milestone_Owner__c=NEW_Project_Manager;          
             mileToUpdate.add(mil);
         }

     }

     update mileToUpdate;
}


Screen Shot of Error

User-added image

Screen Shot of Excution Log

User-added image

 

 

Hello all,

Is it possible to update a custom field (User_IsFrozen__c) on the User object when the Freeze / UnFreeze button is clicked?

Originally I was thinking an Apex Trigger or Process Builder could be used however UserLogin will not allow this.

So, what options are possible? Create custom buttons to Update UserLogin.IsFrozen and User.User_IsFrozen__c.

Any suggestions?

Thanks,

Robert

 

 

Hello All,

More than a year ago I set up Push Notifications for our Salesforce Requests and it works great. The only issue I have is when the User creates a request and pastes in the Details. The special character make the Notification look messy.

Example:

Example of Special Characters in Push Notification

Is there a way to strip out these special characters form the Details field?

Send Custom Notification

Thanks for your help in advance!

Robert

 

 

Hello All,

I inherited an Apex Class that's purpose is to check if Child Cases are still "Open" (not "Resolved" or "Closed") before allowing the Parent Case to be "Resolved" or "Closed".

The Apex Class has been working well until recently when a Case with 222 Child Cases and 59 Related Cases was trying to be "Closed".

The query of the Child Cases uses a FOR loop, but returned error:

 "Aggregate query has too many rows for direct assignment, use FOR loop."

I tried utilizing my companies Premier Support, but go nowhere. Lot's of links, but little help.

So I am asking if anyone has suggestions to make this Apex Class work.

Thanks friends.

Robert

 

Error:

System.QueryException: Aggregate query has too many rows for direct assignment, use FOR loop
External entry point

Problem Statement

//query all child cases

for(Case c:[SELECT Id, status,(select Id,status from cases) FROM  Case

 

Apex Class:

public class UpdateClosedCaseHelper {
    public static boolean skipSuperUserFilter = false;
    public static void updateCase(List<Case>  newcaselist,Map<Id,Case> oldMap,Map<Id,Case> newMap){
        if(!skipSuperUserFilter){
            //get current user info
            User u=[SELECT Id,Support_Super_User__c From User WHERE Id=:UserInfo.getUserId()];
            Set<Id> caseIdset=new Set<Id>();
            Map<Id,case> junctionMap=new Map<Id,case>();
            //get all case id's
            for(Case cd:newcaselist){
                caseIdset.add(cd.Id);
                junctionMap.put(cd.Id,cd);
            }
            //query all child cases                     
            for(Case c:[SELECT Id, status,(select Id,status from cases) FROM Case WHERE Id IN:caseIdset]){
                //check for value change
                if(oldMap.get(c.Id)!=newMap.get(c.Id)){
                    //case is not going to close
                    if(!newMap.get(c.Id).status.equals('Closed') 
                       &&
                       !newMap.get(c.Id).status.equals('Resolved')){
                           if(u.Support_Super_User__c){
                               //update case 
                           }
                           else{
                               if(oldMap.get(c.Id).status.equals('Closed'))
                                   newMap.get(c.Id).addError('Please contact your Almac Super User to re-open closed cases');
                               else{
                                   //update case 
                               }
                           }                        
                       }else{ 
                           //closing or resolving case
                           if((newMap.get(c.Id).status.equals('Closed') || newMap.get(c.Id).status.equals('Resolved')) && 
                              !isAllchildsClosed(c.cases)){                        
                                  if(u.Support_Super_User__c){
                                      //update case 
                                  }
                                  else{
                                      if(oldMap.get(c.Id).status.equals('Closed'))
                                          newMap.get(c.Id).addError('Please contact your Almac Super User to re-open closed cases');
                                      else{
                                          //update case 
                                      }
                                  }
                              }
                           else{
                               junctionMap.get(c.Id).addError('Child Case(s) need to be resolved before resolving a Parent Case');
                           }
                       }
                }
            }    
        }
    }
    public static boolean isAllchildsClosed(List<Case> childs){
        boolean flag=false;
        for(Case c:childs){
            if(!'Closed'.equals(c.Status) && !'Resolved'.equals(c.Status)){
                flag=true;
                break;
            }
        }
        return flag;
    }
}

 

Hello All,

I have a VF Page that displays a list of Opportunites when a custom field OS_Number__c contains the same value.

My scenario is...

User selects an Opportunity,

Then my controller JoinedProposalCheckController uses the Opportunity from the currentPage() to builds List OSNUM to contain that Opportunies OS_Number__c.

Then my controller JoinedProposalCheckController builds List OpptyList to contain all Opportunites that have the same OS_Number__c  contained in List OSNum..

Finally my VF page JoinedProposalCheck displayes the results for the queries. 

This works as expected.

I am unable to get my test class to work, please please help.

Test Class Error:

System.ListException: List index out of bounds: 0

Stack Trace:

Class.JoinedProposalCheckController.<init>: line 43, column 1
Class.JoinedProposalCheckController_Test.testEx: line 253, column 1

* I had to remove some code to load that loaded Oppotunity fields in order upload my Test Class.

Line 253 in my test class is: 

JoinedProposalCheckController obj = new JoinedProposalCheckController(sc);

 

Here's my code:

Apex Controller:

public with sharing class JoinedProposalCheckController {
  
  public List<Opportunity> OpptyList{get;set;}
  public JoinedProposalCheckController(ApexPages.StandardController sc) {

     // Get Opportunity.OS_Number__c for passed Opportunity   
        List<Opportunity> OSNum = [SELECT OS_Number__c   
                                   FROM Opportunity  
                                   //WHERE Id = '0060y000017j0IRAAY'  
                                   WHERE Id = :ApexPages.currentPage().getParameters().get('id')
                                   LIMIT 1]; 

        OpptyList = [SELECT Id, Name, Account.Name, OS_Number__c, Opportunity_Number__c, Joint_Proposal__c   
                     FROM Opportunity 
                     WHERE OS_Number__c = :OSNum[0].OS_Number__c
                     LIMIT 10];
       
  }  
  
}

 

Visualforce Page:

<apex:page standardController="Opportunity"  extensions="JoinedProposalCheckController" showHeader="true" sidebar="false" tabStyle="Opportunity">  
     <apex:form id="JPForm">  
          <apex:pageBlock title="Opportunities List" >   
            
            <apex:pageBlockSection >
                Please review Opportunities without a Joined Proposal
            </apex:pageBlockSection>
                 
            <apex:pageBlockSection >         
               <apex:pageBlockTable value="{!OpptyList}" var="op" width="100%">
                        <apex:column headerValue=" Opportunity">
                             <apex:outputLink value="/{!URLFOR(op.Id)}">{!op.Opportunity_Number__c}
                             </apex:outputLink>
                        </apex:column>  
                        <apex:column Value="{!op.Name}" headerValue="Opportunity Name___________________ ">
                        </apex:column>                               
                        <apex:column Value="{!op.OS_Number__c}" headerValue=" OS Number">
                        </apex:column>  
                        <apex:column Value="{!op.Account.Name}" headerValue="Account Name______________________________________ ">
                        </apex:column>                                       
                        <apex:column Value="{!op.Joint_Proposal__c}" headerValue="Joined Proposal____________________________________________________________">
                        </apex:column>                                            
               </apex:pageBlockTable> 
            </apex:pageBlockSection>                 
        
          </apex:pageBlock>    
     </apex:form>
</apex:page>

 

Test Class:
 

@isTest
public class JoinedProposalCheckController_Test
{ 
static testMethod void testEx() 
{ 

// Add First Opportunity
Opportunity opportunity_Obj1 = new Opportunity(AccountId = '0018000000f7GkqAAE',                                                   Name = 'First Opportunity',                                                 StageName = 'Qualified',                                                   CloseDate = Date.today(),                                                   CreatedDate = DateTime.now(),                                                  CreatedById = '00580000002GuxyAAC',                                                   LastModifiedDate = DateTime.now(),                                                                                                     Joint_Proposal__c = 'a061A00001So9e9QAB',                                                                                                     OS_Number__c = '44831',                                                                                                    PS_OTHER_Processes__c = false);                                                   Insert opportunity_Obj1;
System.Debug('* First Opportunity Added *'+opportunity_Obj1.Id);                                                   
    
// Add Second Opportunity
Opportunity opportunity_Obj2 = new Opportunity(AccountId = '0018000000f7GkqAAE', 
Name = 'Second Opportunity',                                                   StageName = 'Qualified',                                                   CloseDate = Date.today(),                                                   CreatedDate = DateTime.now(),                                                   CreatedById = '00580000002GuxyAAC',                                                   LastModifiedDate = DateTime.now(), 
Joint_Proposal__c = 'a061A00001So9e9QAB',                                                                                                     OS_Number__c = '44831',                                                   PS_OTHER_Processes__c = false);
Insert opportunity_Obj2; 
System.Debug('** Second Opportunity Added **'+opportunity_Obj2.Id);  
                                                    
// Add Third Opportunity
Opportunity opportunity_Obj3 = new Opportunity(AccountId = '0018000000f7GkqAAE', 
Name = 'Third Opportunity',                                                   StageName = 'Qualified',                                                   CloseDate = Date.today(),                                                   CreatedDate = DateTime.now(),                                                   CreatedById = '00580000002GuxyAAC',                                                   LastModifiedDate = DateTime.now(), 
Joint_Proposal__c = 'a061A00001So9e9QAB',                                                   OS_Number__c = '44831',                                                   PS_OTHER_Processes__c = false);                                                   Insert opportunity_Obj3; 
System.Debug('*** Third Opportunity Added ***'+opportunity_Obj3.Id);                                                  
    
test.startTest();                                               

List<Opportunity> OSNum = [SELECT OS_Number__c   
                           FROM Opportunity  
                           WHERE OS_Number__c = '44831'   
                           LIMIT 1]; 
                        
List<Opportunity> OpptyList = [SELECT Id, Name,                Account.Name, OS_Number__c, Opportunity_Number__c, Joint_Proposal__c   
                               FROM Opportunity 
                               WHERE OS_Number__c = '44831'
                               LIMIT 10];                                                                                                                                      
    
ApexPages.StandardController sc = new      ApexPages.StandardController(opportunity_Obj1);
JoinedProposalCheckController obj = new JoinedProposalCheckController(sc);  
    
     test.stopTest();
   }
}
 

 

Hello All!

I have Custom Controller I want to call with a Custom Button on the Opportunity Page. The Custom Controller will get the Opportunity Id from the Opportunity page. I want to get an Opportunity Custom Field, OS_Number__c  (Text 6) from the passed Opportunity Id then save OS_Number__c for use in another query.

My VF Page displays the data correctly when I hard-code the OS_Number__c as '44831' so that part seems to be working correctly.

How do I correct my Custom Controller to work without hard-coding?

How do I add the Custom Button to the Opportunity Page?

Thank you for your help!

Robert

 

Controller:

public class JoinedProposalCheckController {

    public List<Opportunity> OSNum {get;set;} 
    public List<Opportunity> opptyList {get;set;}

    	public JoinedProposalCheckController() {
           populateOSNum();
		   populateOpptyList();
	    }

        private void populateOSNum() {    
           OSNum = [SELECT OS_Number__c   
                    FROM Opportunity  
                    WHERE Id = :ApexPages.currentPage().getParameters().get('id')
                    LIMIT 1 
                   ]; 
           System.Debug('OSNum='+OSNum); 
        }

        private void populateOpptyList() {    
           opptyList = [SELECT Id, Name, Account.Name, OS_Number__c, Opportunity_Number__c, Joint_Proposal__c   
                        FROM Opportunity 
                        WHERE OS_Number__c = '44831' 
                       ]; 
        }
      
        public List<Opportunity> getopptyList() {
          return opptyList;        
        }    
}
 

VFP:

<apex:page Controller="JoinedProposalCheckController" showHeader="true" sidebar="false" tabStyle="Opportunity">  
     <apex:form id="JPForm">  
          <apex:pageBlock title="Opportunities List" >   

            <apex:pageBlockSection >
                Please review Opportunities without a Joined Proposal
            </apex:pageBlockSection>
                 
            <apex:pageBlockSection >         
               <apex:pageBlockTable value="{!OpptyList}" var="op" width="100%">
                        <apex:column headerValue=" Opportunity">
                             <apex:outputLink value="/{!URLFOR(op.Id)}">{!op.Opportunity_Number__c}
                             </apex:outputLink>
                        </apex:column>  
                        <apex:column Value="{!op.Name}" headerValue="Opportunity Name___________________ ">
                        </apex:column>                               
                        <apex:column Value="{!op.OS_Number__c}" headerValue=" OS Number">
                        </apex:column>  
                        <apex:column Value="{!op.Account.Name}" headerValue="Account Name______________________________________ ">
                        </apex:column>                                       
                        <apex:column Value="{!op.Joint_Proposal__c}" headerValue="Joined Proposal____________________________________________________________">
                        </apex:column>                                            
               </apex:pageBlockTable> 
            </apex:pageBlockSection>                 
        
          </apex:pageBlock>    
     </apex:form>
</apex:page>


Custom Button:

Joint Proposal Check - Custom Button

Hello All!

I have been banging my head try to figure out Unknown property 'JoinedProposalCheckController.Opportunity'. I am hoping a 2nd set of eyes will see the cause.

My VF page will eventually execute when the user clicks a button on the Opportunity page, but for now I have hard-coded a value. The purpose of my VF page will be to display Opportunities with a common value in OS_Number__c and finally link to an Opportunity that needs review.

So, my problem at present is I cannot see what is causing Unknown property 'JoinedProposalCheckController.Opportunity'.

Thank you for reading and helping.

Kind regards,

Robert

 

Here's my code:

 

VFP.

<apex:page Controller="JoinedProposalCheckController" showHeader="true" sidebar="false" >  
     <apex:form id="JPForm">  
          <apex:pageBlock title="Opportunities List" >   

   			<apex:pageBlockSection >
				{!$User.FirstName} {!$User.LastName}
			</apex:pageBlockSection>
			     
            <apex:pageBlockSection >         
               <apex:pageBlockTable value="{!Opportunity}" var="op" width="100%">
                    <apex:column HeaderValue="Select">
						<apex:outputText Value="{!op.Op.Id}"></apex:outputText>
                        <apex:outputText Value="{!op.Op.Name}"></apex:outputText>
                        <apex:outputText Value="{!op.Op.Account.Name}"></apex:outputText>
                        <apex:outputText Value="{!op.Op.OS_Number__c}"></apex:outputText>
                        <apex:outputText Value="{!op.Op.Opportunity_Number__c}"></apex:outputText>
                        <apex:outputText Value="{!op.Op.Joint_Proposal__c}"></apex:outputText>   
					</apex:column>
               </apex:pageBlockTable> 
            </apex:pageBlockSection>                 
        
          </apex:pageBlock>    
     </apex:form>
</apex:page>
 

APXC.

public class JoinedProposalCheckController {

    public List<Opportunity> opptyList {get;set;}

    	public JoinedProposalCheckController() {
		   populateOpptyList();
	    }

        private void populateOpptyList() {    
           opptyList = [SELECT Id, Name, Account.Name, OS_Number__c, Opportunity_Number__c, Joint_Proposal__c   
                        FROM Opportunity 
                        WHERE OS_Number__c = '44831']; 
        }
      
        public List<Opportunity> getopptyList() {
          return opptyList;        
        }    
}

Hello All,

Hope everyone is safe and healthy.

I have a field on the Opportunity object called NetworkPath__c which composed of Account and Opportunity fields.

When the Opportunity is created or updated or the Account is updated NetworkPath__c may need to be updated. All is good except when the Opportunity Stage is "Closed" where a Validation Rule (VR) presents the User with an error message "You cannot update a Closed Opportunity". This by design.

I need a way to allow the user to update Opportunity NetworkPath__c when certain Opportunity or Account fields are changed. I don't want allow the User update to complete Opportunity, only the fields that compose NetworkPath__c.

I am thinking a pagelayout limited to the fields that compose NetworkPath__c, but how do I get past the VR that presents the User with the error message.

How about this idea...add a field to the User Profile that grants certain individuals the ability to update the fields that compose NetworkPath__c, then modify the VR to check User Profile for new field.

Doe's this make any sense? Or is there a better way to do this? I am open to all ideas.

Thanks for reading my caffine driven rant.

Cheers!

Robert

My APEX trigger was timing out, so I thought I would  to use a MAP, but I cannot get past the above error.

Anyone willing to take a look?

Map<Id,List<Opportunity>> accountOppMap = new Map<Id,List<Opportunity>>();
for(Opportunity opp : [Select id,accountId from opportunity Where Almac_Division__c='SI']){
    List<Opportunity> opplst = AccountOppMap.get(opp.accountId);
    if(opplst == null)
        opplst = new List<Opportunity>();
    opplst.add(opp);
    accountOppMap.add(opp.accountId,opplst); <- error line
}

Hello All,

I have trigger on the the Account object that updates a custom field (MyOpsPath) on the Opportunity object when Account.Name,Site, or SI_Site_Reference__c changes. My trigger fails after the 4th update due to the CPU time limit error.

Is anyone willing to take a look, other suggestions, or help fix my code?

With thanks in advance.

Robert

trigger UpdateMyOpsPathFromAccount on Account (after update) {
System.Debug('*** UpdateMyOpsPathFromAccount *** ');
//String ClosedLit='Closed%'; *** 27/Feb/2020
String Slsh = '\\';
String PthLit1 = 'ni-cr-svc-fp1';
String PthLit2 = 'QUOTES AND CONTRACTS - LIBRARY';

Set<Id> accountIds = new Set<Id>();

   for(Account acc : trigger.new) {
       if(acc.SI_Site_Reference__c!=null){ 
          //System.Debug('This Accounts SI_Site Reference__c='+acc.SI_Site_Reference__c);   
          if((acc.Name != trigger.oldMap.get(acc.Id).Name) ||
             (acc.Site != trigger.oldMap.get(acc.Id).Site) ||
             (acc.SI_Site_Reference__c != trigger.oldMap.get(acc.Id).SI_Site_Reference__c)){      
              accountIds.add(acc.Id);
              
              String FrstLtr=acc.Name.substring(0,1);
              String Ctgry='2 Accounts (A to H)';
              If(FrstLtr.containsAny('ABCDEFGH'))   {Ctgry='2 Accounts (A to H)';}
              If(FrstLtr.containsAny('IJKLMNOP'))   {Ctgry='3 Accounts (I to P)';}
              If(FrstLtr.containsAny('QRSTUVWXYZ')) {Ctgry='4 Accounts (Q to Z)';}  

              System.Debug('acc.Name='+acc.Name);
              System.Debug('FrstLtr='+FrstLtr);  
              System.Debug('Ctgry='+Ctgry);   
              System.debug('Account with Change='+acc.Id);           
              System.Debug('Old Account Name='+trigger.oldMap.get(acc.Id).Name);
              System.Debug('New Account Name='+acc.Name);
              System.Debug('Old Account Site='+trigger.oldMap.get(acc.Id).Site); 
              System.Debug('New Account Site='+acc.Site);
              System.Debug('Old Account Site Reference='+trigger.oldMap.get(acc.Id).SI_Site_Reference__c);
              System.Debug('New Account Site Reference='+acc.SI_Site_Reference__c);                           
              
              if (!accountIds.isEmpty()){
                  // Get Opportunity Information
                  List<Opportunity>
                  LstOpps=[SELECT Id, MyOpsPath__c, AccountId, Almac_Division__c, StageName, Reference_Number__c  
                  FROM Opportunity
                  //WHERE AccountId in: accountIds AND Almac_Division__c='SI' AND (NOT StageName LIKE:ClosedLit)]; *** 27/Feb/2020
                  WHERE AccountId in: accountIds AND Almac_Division__c='SI' ];

                    System.Debug('LstOpps.size='+LstOpps.size()); 
                    System.Debug('Id='+LstOpps[0].Id);
                    System.Debug('AccountId='+LstOpps[0].AccountId); 
                    System.Debug('Alamc_Division__c='+LstOpps[0].Almac_Division__c);
                    System.Debug('StageName='+LstOpps[0].StageName);                   
                   
                    If(!LstOpps.isEmpty()){ 
                       for(Opportunity o: LstOpps) {

                       System.Debug('BEFORE-MyOpsPath='+LstOpps[0].MyOpsPath__c);                       
   
                       LstOpps[0].MyOpsPath__c=(Slsh+Slsh+PthLit1+Slsh+'sqman'+Slsh+PthLit2+Slsh+Ctgry+Slsh+acc.Name+' ('+acc.Site+') '+acc.SI_Site_Reference__c+Slsh+'Quotes'+Slsh+LstOpps[0].Reference_Number__c+Slsh);
                       
                       System.Debug('AFTER-MyOpsPath__c='+LstOpps[0].MyOpsPath__c);

                       Update LstOpps;
                       System.Debug('*** Opportunity Updated ***');

                       }
                    }
              }
          } 
       }
   }
}
 

 

 

Hi All,

I have a user request where the User would like a Path to a Windows Directory created from Salesforce data.

I originally tried using Apex, but APex did not like the Forward Slash. So I thought I would create Text Field on the Object with Forward Slash as the default value, but this was not allowed.

Any suggestions o should I just tell the user no. I hate saying no.

Goal is to create MyOpsPath = '\\MyFiles\MyFolder\';

Hi All,

Thought this would be easy, but I cannot get past this Error.

User-added image

Thanks in advance.

 

Robert

I want to improve my Apex coding skills, other than Trail Head can anyone reccomend some good courses?

Thanks,

Robert

 

 

Hello all,

So I created a trigger to Cases in a queue, when size is reached I want to send an email once..only once.

My trigger is firing at limit (3), but is sending the email 3 times. I think I need a second or third set of eyes to see what I am missing.

Thanks for your help.

Robert 

trigger NotificationExceedingQueueLimit3 on Case (before insert,before update) {

boolean EmailSent = False;

    list<group> queuelist= [SELECT id  FROM Group where DeveloperName = 'CPS_Default_Queue'and Type = 'Queue' limit 1];     
    if(queuelist.size()>0){
                
             list<case> caselist = [select id from case where ownerid =:queuelist[0].id];
             for(case cs : trigger.new){
             
                if(caselist.size()==3 && EmailSent == False)
                {
                  EmailSent = True; 
                  List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
                  Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                  List<String> sendTo = new List<String>();
                  sendTo.add('Hello.Friend@gmail.com' );
                  mail.setHtmlBody('Hello, <br/> Default Queue Limit Exceeded. The count has exceeded 2 cases.<br/><br/> Thanks, <br/>Salesforce Admin');
                  mail.setSubject('Case Limit of 02 Exceeded');
                  mail.setToAddresses(sendTo);
                  mails.add(mail);   
                  Messaging.sendEmail(mails); 
                }
        
             }
    }  
}
 

 

 

Hello,

I have a custom Time field called Scheduled_ET__c. The drop-down displays time in 15 minute increments, however we do not want the user to select 15 or 45 minute increments. Since there is no way I can find to eliminate 15 or 45 from the drop-down I need to find another soultion.

My thoughts are...use a validation rule or Apex to change the minutes to a 30 min increment.

Is it possble to extract the minutes part of a custom time field in Apex and how would one do that?

My rounding logic would be if user enters <16 round down to 00, >16 and <45 round to 30, >45 up to 00 and increment hour.

Any thoughts or suggestions would greatly be appreciated.

Kind regards,

Robert

Hello all,

I been struggling trying to get my Custom Email Template to display the current date/time using {!NOW()} and HyperLink to render.

When I so a Preview my email renders perfect. When I generate the email from Apex  {!NOW()} displays as "{!NOW()}" and Hyperlink as "HL_ENCODED_url_HL_OpenLink_HL__self_HL".

When I use an HTML Template I ge no output at all.

Any ideas?

Thank you!

Robert

 

Output from Preview

Output from APEX

 

Hello All,

I have a trigger where I want to be alerted when more than 10 EmailMessage records are inserted in an hour. I am unable to get past  "Illegal assignment from list to list" error. I am at a loss what to do to solve.

Thanks for your help in advance!

Robert.


* Here's my code *

 

trigger CountEmailMessagesCreated1HourAgo on EmailMessage (after insert) {

  String NEW_RelatedToId;
  System.debug('Record Map: '+Trigger.newMap);
  DateTime OneHourAgo = System.Now().addHours(-1);
  System.debug('System.Now(): ' + System.Now());
  System.debug('One Hour Ago: ' + OneHourAgo);
  List<String> EmlLst = new List<String>();

  for(EmailMessage Eml : Trigger.new)
  {
   NEW_RelatedToId=Eml.RelatedToId;
   List<EmailMessage> EmlLst = [SELECT RelatedToId, COUNT(ID) 
                                FROM EmailMessage 
                                WHERE RelatedToId =:NEW_RelatedToId AND 
                                              CreatedDate>=:OneHourAgo
                                GROUP BY RelatedToId
                                HAVING Count(Id) >10
                               ];

     If (EmlLst.size() >0){
         List<Messaging.SingleEmailMessage> mails = new 
         List<Messaging.SingleEmailMessage>();
                 Messaging.SingleEmailMessage mail = new 
                 Messaging.SingleEmailMessage();
                 List<String> sendTo = new List<String>();
                sendTo.add('SendToSomeone.@gmail.com' );
                mail.setHtmlBody('Hello, <br/> This Case Id ' +NEW_RelatedToId +' has 
                generated more than 10 in the last hour. <br/><br/> Thanks, <br/>Salesforce 
                Admin');
                mail.setSubject('Case EmailMessage Limit of 10 Exceeded');
                mail.setToAddresses(sendTo);
                mails.add(mail);
                Messaging.sendEmail(mails);
     }
  } 
}
 

 

 

 

Hello All,

I am trying to get a  of EmailMessage records created in the last hour?

For some resaon it does not like my System.debug statement...any idea? 

User-added imageThanks for your help in advance!

Robert

 

 

Hello all,

I have a request to prevent users from pasting data into a text field, is this even possible?

Thanks in advance for your help!

Robert

 

 

 

Hello All,

More than a year ago I set up Push Notifications for our Salesforce Requests and it works great. The only issue I have is when the User creates a request and pastes in the Details. The special character make the Notification look messy.

Example:

Example of Special Characters in Push Notification

Is there a way to strip out these special characters form the Details field?

Send Custom Notification

Thanks for your help in advance!

Robert

 

 

Hello All,

I have a VF Page that displays a list of Opportunites when a custom field OS_Number__c contains the same value.

My scenario is...

User selects an Opportunity,

Then my controller JoinedProposalCheckController uses the Opportunity from the currentPage() to builds List OSNUM to contain that Opportunies OS_Number__c.

Then my controller JoinedProposalCheckController builds List OpptyList to contain all Opportunites that have the same OS_Number__c  contained in List OSNum..

Finally my VF page JoinedProposalCheck displayes the results for the queries. 

This works as expected.

I am unable to get my test class to work, please please help.

Test Class Error:

System.ListException: List index out of bounds: 0

Stack Trace:

Class.JoinedProposalCheckController.<init>: line 43, column 1
Class.JoinedProposalCheckController_Test.testEx: line 253, column 1

* I had to remove some code to load that loaded Oppotunity fields in order upload my Test Class.

Line 253 in my test class is: 

JoinedProposalCheckController obj = new JoinedProposalCheckController(sc);

 

Here's my code:

Apex Controller:

public with sharing class JoinedProposalCheckController {
  
  public List<Opportunity> OpptyList{get;set;}
  public JoinedProposalCheckController(ApexPages.StandardController sc) {

     // Get Opportunity.OS_Number__c for passed Opportunity   
        List<Opportunity> OSNum = [SELECT OS_Number__c   
                                   FROM Opportunity  
                                   //WHERE Id = '0060y000017j0IRAAY'  
                                   WHERE Id = :ApexPages.currentPage().getParameters().get('id')
                                   LIMIT 1]; 

        OpptyList = [SELECT Id, Name, Account.Name, OS_Number__c, Opportunity_Number__c, Joint_Proposal__c   
                     FROM Opportunity 
                     WHERE OS_Number__c = :OSNum[0].OS_Number__c
                     LIMIT 10];
       
  }  
  
}

 

Visualforce Page:

<apex:page standardController="Opportunity"  extensions="JoinedProposalCheckController" showHeader="true" sidebar="false" tabStyle="Opportunity">  
     <apex:form id="JPForm">  
          <apex:pageBlock title="Opportunities List" >   
            
            <apex:pageBlockSection >
                Please review Opportunities without a Joined Proposal
            </apex:pageBlockSection>
                 
            <apex:pageBlockSection >         
               <apex:pageBlockTable value="{!OpptyList}" var="op" width="100%">
                        <apex:column headerValue=" Opportunity">
                             <apex:outputLink value="/{!URLFOR(op.Id)}">{!op.Opportunity_Number__c}
                             </apex:outputLink>
                        </apex:column>  
                        <apex:column Value="{!op.Name}" headerValue="Opportunity Name___________________ ">
                        </apex:column>                               
                        <apex:column Value="{!op.OS_Number__c}" headerValue=" OS Number">
                        </apex:column>  
                        <apex:column Value="{!op.Account.Name}" headerValue="Account Name______________________________________ ">
                        </apex:column>                                       
                        <apex:column Value="{!op.Joint_Proposal__c}" headerValue="Joined Proposal____________________________________________________________">
                        </apex:column>                                            
               </apex:pageBlockTable> 
            </apex:pageBlockSection>                 
        
          </apex:pageBlock>    
     </apex:form>
</apex:page>

 

Test Class:
 

@isTest
public class JoinedProposalCheckController_Test
{ 
static testMethod void testEx() 
{ 

// Add First Opportunity
Opportunity opportunity_Obj1 = new Opportunity(AccountId = '0018000000f7GkqAAE',                                                   Name = 'First Opportunity',                                                 StageName = 'Qualified',                                                   CloseDate = Date.today(),                                                   CreatedDate = DateTime.now(),                                                  CreatedById = '00580000002GuxyAAC',                                                   LastModifiedDate = DateTime.now(),                                                                                                     Joint_Proposal__c = 'a061A00001So9e9QAB',                                                                                                     OS_Number__c = '44831',                                                                                                    PS_OTHER_Processes__c = false);                                                   Insert opportunity_Obj1;
System.Debug('* First Opportunity Added *'+opportunity_Obj1.Id);                                                   
    
// Add Second Opportunity
Opportunity opportunity_Obj2 = new Opportunity(AccountId = '0018000000f7GkqAAE', 
Name = 'Second Opportunity',                                                   StageName = 'Qualified',                                                   CloseDate = Date.today(),                                                   CreatedDate = DateTime.now(),                                                   CreatedById = '00580000002GuxyAAC',                                                   LastModifiedDate = DateTime.now(), 
Joint_Proposal__c = 'a061A00001So9e9QAB',                                                                                                     OS_Number__c = '44831',                                                   PS_OTHER_Processes__c = false);
Insert opportunity_Obj2; 
System.Debug('** Second Opportunity Added **'+opportunity_Obj2.Id);  
                                                    
// Add Third Opportunity
Opportunity opportunity_Obj3 = new Opportunity(AccountId = '0018000000f7GkqAAE', 
Name = 'Third Opportunity',                                                   StageName = 'Qualified',                                                   CloseDate = Date.today(),                                                   CreatedDate = DateTime.now(),                                                   CreatedById = '00580000002GuxyAAC',                                                   LastModifiedDate = DateTime.now(), 
Joint_Proposal__c = 'a061A00001So9e9QAB',                                                   OS_Number__c = '44831',                                                   PS_OTHER_Processes__c = false);                                                   Insert opportunity_Obj3; 
System.Debug('*** Third Opportunity Added ***'+opportunity_Obj3.Id);                                                  
    
test.startTest();                                               

List<Opportunity> OSNum = [SELECT OS_Number__c   
                           FROM Opportunity  
                           WHERE OS_Number__c = '44831'   
                           LIMIT 1]; 
                        
List<Opportunity> OpptyList = [SELECT Id, Name,                Account.Name, OS_Number__c, Opportunity_Number__c, Joint_Proposal__c   
                               FROM Opportunity 
                               WHERE OS_Number__c = '44831'
                               LIMIT 10];                                                                                                                                      
    
ApexPages.StandardController sc = new      ApexPages.StandardController(opportunity_Obj1);
JoinedProposalCheckController obj = new JoinedProposalCheckController(sc);  
    
     test.stopTest();
   }
}
 

 

Hello All!

I have Custom Controller I want to call with a Custom Button on the Opportunity Page. The Custom Controller will get the Opportunity Id from the Opportunity page. I want to get an Opportunity Custom Field, OS_Number__c  (Text 6) from the passed Opportunity Id then save OS_Number__c for use in another query.

My VF Page displays the data correctly when I hard-code the OS_Number__c as '44831' so that part seems to be working correctly.

How do I correct my Custom Controller to work without hard-coding?

How do I add the Custom Button to the Opportunity Page?

Thank you for your help!

Robert

 

Controller:

public class JoinedProposalCheckController {

    public List<Opportunity> OSNum {get;set;} 
    public List<Opportunity> opptyList {get;set;}

    	public JoinedProposalCheckController() {
           populateOSNum();
		   populateOpptyList();
	    }

        private void populateOSNum() {    
           OSNum = [SELECT OS_Number__c   
                    FROM Opportunity  
                    WHERE Id = :ApexPages.currentPage().getParameters().get('id')
                    LIMIT 1 
                   ]; 
           System.Debug('OSNum='+OSNum); 
        }

        private void populateOpptyList() {    
           opptyList = [SELECT Id, Name, Account.Name, OS_Number__c, Opportunity_Number__c, Joint_Proposal__c   
                        FROM Opportunity 
                        WHERE OS_Number__c = '44831' 
                       ]; 
        }
      
        public List<Opportunity> getopptyList() {
          return opptyList;        
        }    
}
 

VFP:

<apex:page Controller="JoinedProposalCheckController" showHeader="true" sidebar="false" tabStyle="Opportunity">  
     <apex:form id="JPForm">  
          <apex:pageBlock title="Opportunities List" >   

            <apex:pageBlockSection >
                Please review Opportunities without a Joined Proposal
            </apex:pageBlockSection>
                 
            <apex:pageBlockSection >         
               <apex:pageBlockTable value="{!OpptyList}" var="op" width="100%">
                        <apex:column headerValue=" Opportunity">
                             <apex:outputLink value="/{!URLFOR(op.Id)}">{!op.Opportunity_Number__c}
                             </apex:outputLink>
                        </apex:column>  
                        <apex:column Value="{!op.Name}" headerValue="Opportunity Name___________________ ">
                        </apex:column>                               
                        <apex:column Value="{!op.OS_Number__c}" headerValue=" OS Number">
                        </apex:column>  
                        <apex:column Value="{!op.Account.Name}" headerValue="Account Name______________________________________ ">
                        </apex:column>                                       
                        <apex:column Value="{!op.Joint_Proposal__c}" headerValue="Joined Proposal____________________________________________________________">
                        </apex:column>                                            
               </apex:pageBlockTable> 
            </apex:pageBlockSection>                 
        
          </apex:pageBlock>    
     </apex:form>
</apex:page>


Custom Button:

Joint Proposal Check - Custom Button

Hello All!

I have been banging my head try to figure out Unknown property 'JoinedProposalCheckController.Opportunity'. I am hoping a 2nd set of eyes will see the cause.

My VF page will eventually execute when the user clicks a button on the Opportunity page, but for now I have hard-coded a value. The purpose of my VF page will be to display Opportunities with a common value in OS_Number__c and finally link to an Opportunity that needs review.

So, my problem at present is I cannot see what is causing Unknown property 'JoinedProposalCheckController.Opportunity'.

Thank you for reading and helping.

Kind regards,

Robert

 

Here's my code:

 

VFP.

<apex:page Controller="JoinedProposalCheckController" showHeader="true" sidebar="false" >  
     <apex:form id="JPForm">  
          <apex:pageBlock title="Opportunities List" >   

   			<apex:pageBlockSection >
				{!$User.FirstName} {!$User.LastName}
			</apex:pageBlockSection>
			     
            <apex:pageBlockSection >         
               <apex:pageBlockTable value="{!Opportunity}" var="op" width="100%">
                    <apex:column HeaderValue="Select">
						<apex:outputText Value="{!op.Op.Id}"></apex:outputText>
                        <apex:outputText Value="{!op.Op.Name}"></apex:outputText>
                        <apex:outputText Value="{!op.Op.Account.Name}"></apex:outputText>
                        <apex:outputText Value="{!op.Op.OS_Number__c}"></apex:outputText>
                        <apex:outputText Value="{!op.Op.Opportunity_Number__c}"></apex:outputText>
                        <apex:outputText Value="{!op.Op.Joint_Proposal__c}"></apex:outputText>   
					</apex:column>
               </apex:pageBlockTable> 
            </apex:pageBlockSection>                 
        
          </apex:pageBlock>    
     </apex:form>
</apex:page>
 

APXC.

public class JoinedProposalCheckController {

    public List<Opportunity> opptyList {get;set;}

    	public JoinedProposalCheckController() {
		   populateOpptyList();
	    }

        private void populateOpptyList() {    
           opptyList = [SELECT Id, Name, Account.Name, OS_Number__c, Opportunity_Number__c, Joint_Proposal__c   
                        FROM Opportunity 
                        WHERE OS_Number__c = '44831']; 
        }
      
        public List<Opportunity> getopptyList() {
          return opptyList;        
        }    
}

My APEX trigger was timing out, so I thought I would  to use a MAP, but I cannot get past the above error.

Anyone willing to take a look?

Map<Id,List<Opportunity>> accountOppMap = new Map<Id,List<Opportunity>>();
for(Opportunity opp : [Select id,accountId from opportunity Where Almac_Division__c='SI']){
    List<Opportunity> opplst = AccountOppMap.get(opp.accountId);
    if(opplst == null)
        opplst = new List<Opportunity>();
    opplst.add(opp);
    accountOppMap.add(opp.accountId,opplst); <- error line
}

Hi All,

I have a user request where the User would like a Path to a Windows Directory created from Salesforce data.

I originally tried using Apex, but APex did not like the Forward Slash. So I thought I would create Text Field on the Object with Forward Slash as the default value, but this was not allowed.

Any suggestions o should I just tell the user no. I hate saying no.

Goal is to create MyOpsPath = '\\MyFiles\MyFolder\';

global class Schedule_CreditEvaluation_LastYearDetail implements Schedulable {

    global void execute(SchedulableContext sc) {
        
        String body;
        String bodyHeader;
        String footer;  
        List<Messaging.SingleEmailMessage> listMessageEmail = new List<Messaging.SingleEmailMessage>();
        Set<Id> setCustomerId = new Set<Id>();
        Map<Id, List<Credit_Evaluation__c>> mapCustomerCreditEvaluation = new Map<Id, List<Credit_Evaluation__c>>();
        map<Id, Credit_Evaluation__c> mapCustIdToCE = new map<Id, Credit_Evaluation__c>();
        List<Credit_Evaluation__c> ceCustomer = new List<Credit_Evaluation__c>(); 
        
        // getting the start date and end date for fetching credit evaluations approved last year 
        Date dtLastYearEndDate = null;
        Date dtLastYearStartDate = date.newInstance(System.today().year() - 1, System.today().month() , 01);
        if(System.today().month() == 1 || System.today().month() == 3 || System.today().month() == 5 || System.today().month() == 7 || System.today().month() == 8 || System.today().month() == 10 || System.today().month() == 12) {
            dtLastYearEndDate = date.newInstance(System.today().year() - 1, System.today().month(), 31);
        } else if (System.today().month() == 4 || System.today().month() == 6 || System.today().month() == 9 || System.today().month() == 11) {
            dtLastYearEndDate = date.newInstance(System.today().year() - 1, System.today().month(), 30);
        } else {
            dtLastYearEndDate = date.newInstance(System.today().year() - 1, System.today().month(), 29);
        }
        // comment the below two lines later
        // Date dtLastYearStartDate = date.newInstance(2013, 06, 01);
        // Date dtLastYearEndDate = date.newInstance(2013, 06, 31);
        
        List<Credit_Evaluation__c> creditEval = [Select c.Approved_By__c,c.Customer_Owner_ID__c,c.Last_Approved_Credit_Limit_Internal__c,c.Last_Approved_Credit_Limit_Customer__c, c.CreatedDate, c.Credit_Term__c, c.Proposed_Credit_Limit__c, c.Customer_Name__r.Name, c.Customer_Sold_to_Party_Code__c, c.Customer_Name__c, c.Id, c.Name, c.Current_Approval_date__c, c.Status__c, c.Customer_Name__r.Customer_Type__c From Credit_Evaluation__c  c where Status__c =: 'Approved' AND Current_Approval_date__c >=: dtLastYearStartDate AND Current_Approval_date__c <=: dtLastYearEndDate AND Customer_Name__r.Type = 'Customer' limit 50000];
        System.debug('@@ creditEval @@' + creditEval);
        if(creditEval.size() > 0) {
            for(Credit_Evaluation__c ce: creditEval) {
                setCustomerId.add(ce.Customer_Name__c);
            }
            List<Credit_Evaluation__c> checkRenewalDoneCE = [Select c.Approved_By__c,c.Customer_Owner_ID__c,c.Last_Approved_Credit_Limit_Internal__c,c.Last_Approved_Credit_Limit_Customer__c,c.Insured_Credit_Limit__c,c.Last_Approved_Credit_Term_Customer__c, c.CreatedDate, c.Credit_Term__c, c.Proposed_Credit_Limit__c, c.Customer_Name__r.Name, c.Customer_Sold_to_Party_Code__c, c.Customer_Name__c, c.Id, c.Name, c.Current_Approval_date__c, c.Status__c, c.Customer_Name__r.Customer_Type__c From Credit_Evaluation__c  c where Status__c =: 'Approved' AND Customer_Name__c IN: setCustomerId ORDER BY Customer_Name__c ASC limit 50000];
            if(!checkRenewalDoneCE.isEmpty() && checkRenewalDoneCE != null) {
                for(Credit_Evaluation__c chkRenewal: checkRenewalDoneCE) {
                    if(chkRenewal.Current_Approval_date__c >= dtLastYearStartDate) {
                        if(!mapCustomerCreditEvaluation.isEmpty() && mapCustomerCreditEvaluation != null) {
                            if(chkRenewal != null && chkRenewal.Customer_Name__c != null && !mapCustIdToCE.isEmpty() && mapCustIdToCE != null && mapCustIdToCE.get(chkRenewal.Customer_Name__c) != null && mapCustIdToCE.get(chkRenewal.Customer_Name__c).Customer_Name__c != null && mapCustIdToCE.get(chkRenewal.Customer_Name__c).Customer_Name__c == chkRenewal.Customer_Name__c) {
                                   ceCustomer.add(chkRenewal);
                                   mapCustomerCreditEvaluation.put(chkRenewal.Customer_Name__c, ceCustomer);
                            } else {
                                ceCustomer = new List<Credit_Evaluation__c>();
                                   ceCustomer.add(chkRenewal); 
                                   mapCustIdToCE.put(chkRenewal.Customer_Name__c, chkRenewal); 
                                   mapCustomerCreditEvaluation.put(chkRenewal.Customer_Name__c, ceCustomer);
                            }
                        } else {
                            ceCustomer = new List<Credit_Evaluation__c>();
                               ceCustomer.add(chkRenewal); 
                               mapCustIdToCE.put(chkRenewal.Customer_Name__c, chkRenewal); 
                               mapCustomerCreditEvaluation.put(chkRenewal.Customer_Name__c, ceCustomer);
                        }
                    }
                }
            }
            System.debug('@@ mapCustomerCreditEvaluation @@' +mapCustomerCreditEvaluation);
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            
            //Ishwar 08-Oct-15 Removed hardcoded emails, get emails ids from given Public Group
            String[] toAddresses = CommonUtil.getGroupMemberEmailIds('CreditEvalRenew_Email');
            
            // change shirlin tan email address    
            //String[] toAddresses = new String[] {'ST@natsteel.com.sg'};
            
            // Setting the To Address & Cc Address
            mail.setToAddresses(toAddresses);
            mail.setBccSender(false);
            mail.setUseSignature(false);
            
            // Creating the main table for Credit Evaluations for the Email Body
            bodyHeader = '<table width="100%" cellpadding="0", border="1">';
            bodyHeader += '<th> Customer Name </th> <th> Customer Code </th> <th> Last Approved Credit Limit (Customer) </th><th>Last Approved Credit Limit (Internal)</th> <th> Last Approved Credit Term (Customer) </th> <th>Insured Limit</th> <th>Last Approved Date</th> <th>Customer Owner</th>';            
            body = '';
            
            // querying the Credit Evaluations for the ones which are approved 1 year before and also only for those Customers with Type Customer
            for(Credit_Evaluation__c ce: [Select c.Approved_By__c,c.Customer_Owner_ID__c,c.Last_Approved_Credit_Limit_Internal__c,
                                          c.Last_Approved_Credit_Limit_Customer__c,
                                          c.Insured_Credit_Limit__c,c.Last_Approved_Credit_Term_Customer__c, 
                                          c.CreatedDate, c.Credit_Term__c, c.Proposed_Credit_Limit__c, 
                                          c.Customer_Name__r.Name, c.Customer_Sold_to_Party_Code__c, c.Customer_Name__c, c.Id, 
                                          c.Name, c.Current_Approval_date__c, c.Status__c, 
                                          c.Customer_Name__r.Customer_Type__c From Credit_Evaluation__c  c where 
                                          Status__c =: 'Approved' AND Current_Approval_date__c >=: dtLastYearStartDate AND 
                                          Current_Approval_date__c <=: dtLastYearEndDate AND Customer_Name__r.Type = 'Customer'
                                          AND Last_Approved_Credit_Term_Customer__c != 'COD' AND 
                                          Last_Approved_Credit_Limit_Customer__c != 0
                                          limit 50000])
            {
                if(!mapCustomerCreditEvaluation.isEmpty() && mapCustomerCreditEvaluation != null) {
                    if(mapCustomerCreditEvaluation.get(ce.Customer_Name__c).size() == 1) {
                        String strApprovalDate = ce.Current_Approval_date__c.format();
                        body += '<td>' +ce.Customer_Name__r.Name + '</td>';
                        body += '<td>' +ce.Customer_Sold_to_Party_Code__c + '</td>';
                        body += '<td>' +ce.Last_Approved_Credit_Limit_Customer__c + '</td>';
                        body += '<td>' + ce.Last_Approved_Credit_Limit_Internal__c + '</td>';
                        body += '<td>' + ce.Last_Approved_Credit_Term_Customer__c + '</td>';
                        body += '<td>' + ce.Insured_Credit_Limit__c  + '</td>';  
                        body += '<td>' +strApprovalDate+ '</td>';
                        body += '<td>' +ce.Customer_Owner_ID__c+ '</td></tr>';
                    }
                }
            }
            
            
            
            // setting the footer for Email body
            footer = '<p> The above customer'+ '\'' +'s credit evaluation is due for renewal. </p>';
            footer += '<p> Please do the evaluation in Salesforce within 14 days. </p>';
            footer += 'Thank you.';
            
            // Set the Email body content 
            if(body != null && body != '') {
                body += '</table>';
                body = body.replace('null' , '') ;
            }
            
            //Ishwar 08-Oct-15 Removed hardcoded name, get name from given Public Group
            String toNames='';
            for(User u : [SELECT Name FROM User WHERE Email in :toAddresses])
            {
                toNames = toNames + u.Name +', ';
            }
            //mail.setHtmlBody('<p> Hi ' + toNames + '</p>' +bodyHeader + body + footer);
            mail.setHtmlBody('<p> Dear Credit Controllers' + '</p>' +bodyHeader + body + footer);
            
            // set the subject Name
            
            Integer iMonth = System.today().month();
            String strMonth;
            if(iMonth == 1) strMonth = 'Jan';
            else if(iMonth == 2) strMonth = 'Feb';
            else if(iMonth == 3) strMonth = 'Mar';
            else if(iMonth == 4) strMonth = 'Apr';
            else if(iMonth == 5) strMonth = 'May';
            else if(iMonth == 6) strMonth = 'June';
            else if(iMonth == 7) strMonth = 'July';
            else if(iMonth == 8) strMonth = 'Aug';
            else if(iMonth == 9) strMonth = 'Sep';
            else if(iMonth == 10) strMonth = 'Oct';
            else if(iMonth == 11) strMonth = 'Nov';
            else if(iMonth == 12) strMonth = 'Dec';

            String strSubject = String.valueof((System.today().year())) + ' - ' + strMonth;
            mail.setSubject('Renewal of Credit Evaluation for ' +strSubject);
            if(body != null && body != '') {
                listMessageEmail.add(mail);
            }
            System.debug('@@ listMessageEmail @@' +listMessageEmail);
            // send the email to respective customer Owners with details of Credit Request
            if(!listMessageEmail.isEmpty() && listMessageEmail != null) {
                Messaging.sendEmail(listMessageEmail);
            }
        }
    }
}

Happy Holidays!

I created a CaseComment Trigger to send an email to the Case Owner when a new CaseComment has been added.

I created a custom field Case_Community_Comment__c on the Case object to hold the most recent CaseComment and utilize a workflow rule to keep it current.

My issue is... my trigger program sends the email before Case_Community_Comment__c has been updated with the most recent CaseComment.

Anyone willing to take look?

Thanks.

Robert

trigger SendCaseCommentEmail on CaseComment (after update) {

  {
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    for(Casecomment cc: Trigger.new)
    {
        case cs=new case(id=cc.ParentId);
        contact co=new contact(id=cs.ContactId);
        user us=new user(id=cs.OwnerId); 
      //if(us.ProfileId == '00e0y000001jD95') // Almac Community Login User  
        if(cc.IsPublished == True){
            // Messaging.SingleEmailMessage message1 = new Messaging.SingleEmailMessage();
            mail.setSubject(cs.Subject);
            mail.setToAddresses(new list<string>{'Robert.Wambold@AlmacGroup.com'}); // CaseOwner Email Address
            //mail.setToAddresses(new list<string>{us.Email}); // send email to Case Owner
            mail.settemplateid('00Xc0000000Nimi'); 
            mail.setTargetObjectId('003c000001Mz1vOAAR'); // ContactId
            mail.whatid= cs.id;
            // mailmsglist.add(message1);
           
        } 
       
    }
    
//  Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> (mailmsglist); 
//  Messaging.SendEmailResult[] results = Messaging.sendEmail(messages); 
    Messaging.SendEmailResult[] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});  
    if(results.size()>0){
    if (results[0].success) {
            System.debug('The email was sent successfully.');
            } else {
            System.debug('The email failed to send: '
            + results[0].errors[0].message);
            }
    }
  }
}
 

Email Template

Hi,

We have a custom object on which we have already created 40 Lookup fields,now there is a requirement to create an additional Lookup Field,
Can anyone let me know the workarounds for this solution  other than raising a case with salesforce to increase the limit.

Thanks.
 

Hi All,

 

I have a inputText field in a VF page and I need to disable paste function(Ctrl+v and paste using mouse button) so that we need to compulsorily type in the text box instead of just copy pasting.

 

I have tried the following script:

<script>

function DisableCtrlKey(e)
{
    var code = (document.all) ? event.keyCode:e.which;
    // look for CTRL key press
    if (parseInt(code)==17)
    {
        alert("Please re-type your email address");
        window.event.returnValue = false;
    }
}

function DisableRightClick(event)
{
    //For mouse right click
    if (event.button==2)
    {
        alert("Please re-type your email address");       
    }
}

</script>

 and under the VF page:

<apex:inputText id="confirmemail" value="{!email}" onKeyDown="return DisableCtrlKey(event)" onMouseDown="DisableRightClick(event)" </apex:inputText>

 It works fine but I want to implement the same functionality without using alert function.

 

Can anyone please let me know any work around to accomplish the above scenario.

Any help on this will be highly appreciated.

 

 

 

I thought this should be fairly straightforward, but I can't figure out how to do it.  How do you get the current date inserted into a merge field in an Email template?