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

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 25
    Questions
  • 24
    Replies

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

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

Hello All,

Taking a shot at my first Lighting Component App and cannot resolve my #^&!# error. The purpose of my app is to display CaseComments related to a Case. When I attempt to Preview my app get the following error:

User-added image

*** Can Someone please help me find my error? ***

Thanks in advance.

Robert

Here's my code:

CaseCommentListController.cls

// Apex Controller for CaseComment List Lightning Component
public class CaseCommentListController {
  
    @AuraEnabled
    public static List<CaseComment> getCaseCommentsList(List<Id> parentIds) {
      // Getting the list of casecomments from where Id is in parentIds
    List<CaseComment> casecommentList = [SELECT Id, CommentBody, ParentId FROM CaseComment WHERE ParentId in :parentIds];
    // Returning the casecomment list
        return casecommentList;
    }

    @AuraEnabled
    public static Map<String,String> saveCaseCommentList(List<CaseComment> casecommentList) {
      // Forming a  string map to return response
        Map<String,String> resultMap = new Map<String,String>();
        // Adding try catch for exception handling
        try {
          // Updating the CaseComment List
            update casecommentList;
            // Setting the success status and message in resultMap
            resultMap.put('status', 'success');
          resultMap.put('message', 'CaseComments Updated Successfully');        
      }
      catch(Exception e) {
            // Setting the error status and message in resultMap
            resultMap.put('status', 'error');
      resultMap.put('message',e.getMessage());
      }
      // Returning the result string map
        return resultMap;
    }
    
    @AuraEnabled
    public static Map<String,String> deleteCaseCommentList(List<Id> casecommentIds) {
        //Fetching CaseComments
        List<CaseComment> casecommentsToDelete = [SELECT Id FROM CaseComment WHERE Id in :casecommentIds];
        // Forming a  string map to return response
        Map<String,String> resultMap = new Map<String,String>();
        // Adding try catch for exception handling
        try {
          // Deleting the CaseComments
            delete casecommentsToDelete;
            // Setting the success status and message in resultMap
            resultMap.put('status', 'success');
          resultMap.put('message', 'CaseComments Deleted Successfully');        
      }
      catch(Exception e) {
            // Setting the error status and message in resultMap
            resultMap.put('status', 'error');
      resultMap.put('message',e.getMessage());
      }
      // Returning the result string map
        return resultMap;                
    }

    @AuraEnabled
    public static Map<String, String> createCaseCommentRecord(CaseComment newCaseComment) {
        // Forming a  string map to return response
        Map<String,String> resultMap = new Map<String,String>();
        // Adding try catch for exception handling
        try {
            // Inserting the CaseComment
            insert newCaseComment;
            // Setting the success status and message in resultMap
            resultMap.put('status', 'success');
            resultMap.put('message', 'CaseComment Inserted Successfully');        
        }
        catch(Exception e) {
            // Setting the error status and message in resultMap
            resultMap.put('status', 'error');
            resultMap.put('message',e.getMessage());
        }
        // Returning the result string map
        return resultMap;        
    }
}

CaseCommentListApp.app

<!-- Application to call CaseCommentList component -->
<aura:application extends="force:slds" >
	<!-- force:slds extended to apply lightning design system styling and passed in the record Id -->
    <c:CaseCommentList recordId="5000y00001dWMmQAAW" />
</aura:application>

CaseCommentListAppController.js

({
    // Function called on initial page loading to get casecomment list from server
    getCaseCommentsList : function(component, event, helper) { 
        // Helper function - fetchCaseComments called for interaction with server
		helper.fetchCaseComments(component, event, helper);
	},

    // Function used to create a new CaseComment
    newCaseComment: function(component, event, helper) {
        // Global event force:createRecord is used
        var createCaseComment = $A.get("e.force:createRecord");
        // Parameters like apiName and defaultValues are set
        createCaseComment.setParams({
            "entityApiName": "CaseComment",
            "defaultFieldValues": {
                "ParentId": component.get("v.recordId")
            }
        });
        // Event fired and new casecomment dialog open
        createCaseComment.fire();
    },

    // Function used to update the casecomments
    editCaseComments: function(component, event, helper) {
        // Getting the button element
        var btn = event.getSource();
        // Getting the value in the name attribute
        var name = btn.get('v.name');
        // Getting the record view form and the record edit form elements
        var recordViewForm = component.find('recordViewForm');
        var recordEditForm = component.find('recordEditForm'); 
        // If button is edit
        if(name=='edit') {
            // Hiding the recordView Form and making the recordEdit form visible
            $A.util.addClass(recordViewForm,'formHide');
            $A.util.removeClass(recordEditForm,'formHide');
            // Changing the button name and label
            btn.set('v.name','save');
            btn.set('v.label','Save');
        }
        else if(name=='save') {
            // Calling saveCaseCommentList if the button is save
            helper.saveCaseCommentList(component, event, helper);
        }
    }
})

CaseCommentListAppHelper.js

({
	helperMethod : function() {
		
	}
})

CaseCommentListApp.css

.THIS {
}
.THIS .formHide {
	display: none;
}

CaseCommentListCmp.cmp

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" controller="CaseCommentListController" access="global">
    <!-- Handler to call function when page is loaded initially -->
    <aura:handler name="init" action="{!c.getCaseComments}" value="{!this}" />
    <!-- List of casecomments stored in attribute -->
    <aura:attribute name="casecommentList" type="List" />
    <!-- New CaseComment Object -->
    <aura:attribute name="casecomment" type="CaseComment"
    default="{
        'SObjectType': 'CaseComment', 'CommentBody': ''
    }">            
    </aura:attribute>
    <!-- Method to validate new casecomment -->
    <aura:method name="validateCaseComment" action="{!c.validateCaseComment}" />
    <!-- Lightning card to show casecomments -->
    <lightning:card title="CaseComments">
        <!-- Body of lightning card starts here -->
        <p class="slds-p-horizontal_small">
            <!-- Aura iteration to iterate list, similar to apex:repeat -->
            <div aura:id="recordViewForm">
                <aura:iteration items="{!v.casecommentList}" var="casecomment">
                    <!-- recordViewForm to view the record -->
                    <lightning:recordViewForm recordId="{!casecomment.Id}" objectApiName="CaseComment">
                        <div class="slds-box slds-theme_default">
                            <!-- inputfield checkbox used to check wether to delete the casecomment or not -->
                            <lightning:input type="checkbox" value="{!casecomment.Id}" label="Mark for Deletion" aura:id="deleteCaseComment" />
                            <br />
                            <!-- outputfield used to output the record field data inside recordViewForm -->
                            <lightning:outputField fieldName="CommentBody" />
                        </div>
                    </lightning:recordViewForm>
                    <!-- Line break between two records -->
                    <br />
                </aura:iteration>
            </div>
            <div aura:id="recordEditForm" class="formHide">
                <aura:iteration items="{!v.casecommentList}" var="casecomment">
                    <div class="slds-box slds-theme_default">
                        <!-- inputfield used to update the record field data -->
                        <!-- Validation added -->
                        <lightning:input aura:id="fieldToValidate" value="{!casecomment.CommentBody}" messageWhenValueMissing="Comment is Mandatory" required="true"/>
                    </div>
                    <br />
                    <!-- Line break between two records -->
                </aura:iteration>
            </div>
        </p>
        <!-- Lightning card actions -->
        <aura:set attribute="actions">
            <!-- New casecomment modal button added -->
            <lightning:button name="casecommentModal" label="New CaseComment" onclick="{!c.openModal}" />
            <!-- Delete button added -->
            <lightning:button variant="destructive" label="Delete" onclick="{!c.deleteCaseComments}" />
            <!-- New button added -->
            <lightning:button label="New" onclick="{!c.newCaseComment}" />
            <!-- Edit/Save button added -->
            <lightning:button variant="brand" label="Edit" name="edit" onclick="{!c.editCaseComments}" />
        </aura:set>
    </lightning:card>
    <!-- CaseComments Modal Section -->
    <div>
        <section aura:id="casecommentModal" role="dialog" tabindex="-1" aria-labelledby="casecommentModalHeading" aria-modal="true" aria-describedby="casecommentModalBody" class="slds-modal">
            <!-- Modal Container -->
            <div class="slds-modal__container">
                <!-- Modal Header ( consists of close button and heading of modal ) -->
                <header class="slds-modal__header">
                    <lightning:buttonIcon class="slds-modal__close" alternativeText="Close" iconName="utility:close" onclick="{!c.closeModal}" variant="bare-inverse" size="large"></lightning:buttonIcon>
                    <h2 id="casecommentModalHeading" class="slds-text-heading_medium slds-hyphenate">New CaseComment</h2>
                </header>
                <!-- Modal Body ( consists of form ) -->
                <div class="slds-modal__content slds-p-around_medium" id="casecommentModalBody">
                    <!-- Validation added -->
                    <lightning:input aura:id="formFieldToValidate" label="Comment" messageWhenValueMissing="Comment is Mandatory" required="true" value="{!v.casecomment.CommentBody}" />
                </div>
                <!-- Modal Footer ( consists of cancel and save buttons ) -->
                <footer class="slds-modal__footer">
                    <lightning:button onclick="{!c.closeModal}" variant="neutral">Cancel</lightning:button>
                    <lightning:button onclick="{!c.createCaseComment}" variant="brand" >Save</lightning:button>
                </footer>
            </div>
        </section>
        <!-- Modal Backdrop -->
        <div aura:id="casecommentModalBackdrop" class="slds-backdrop"></div>
    </div>
</aura:component>

CaseCommentListCmpController.js

({
    // Function called on initial page loading to get casecomment list from server
	getCaseCommentsList : function(component, event, helper) {
        // Helper function - fetchCaseComments called for interaction with server
		helper.fetchCaseComments(component, event, helper);
	},

    // Function used to create a new casecomment
    newcasecomment: function(component, event, helper) {
        // Global event force:createRecord is used
        var createcasecomment = $A.get("e.force:createRecord");
        // Parameters like apiName and defaultValues are set
        createcasecomment.setParams({
            "entityApiName": "casecomment",
            "defaultFieldValues": {
                "ParentId": component.get("v.recordId")
            }
        });
        // Event fired and new casecomment dialog open
        createcasecomment.fire();
    },

    // Function used to update the casecomments
    editCaseComments: function(component, event, helper) {
        // Getting the button element
        var btn = event.getSource();
        // Getting the value in the name attribute
        var name = btn.get('v.name');
        // Getting the record view form and the record edit form elements
        var recordViewForm = component.find('recordViewForm');
        var recordEditForm = component.find('recordEditForm'); 
        // If button is edit
        if(name=='edit') {
            // Hiding the recordView Form and making the recordEdit form visible
            $A.util.addClass(recordViewForm,'formHide');
            $A.util.removeClass(recordEditForm,'formHide');
            // Changing the button name and label
            btn.set('v.name','save');
            btn.set('v.label','Save');
        }
        else if(name=='save') {
            // Getting the edit form fields to validate
            var casecommentFields = component.find("fieldToValidate");
            // Initialize the counter to zero - used to check validity of fields
            var blank=0;
            // If there are more than 1 fields
            if(casecommentFields.length!=undefined) {
                // Iterating all the fields
                var allValid = casecommentFields.reduce(function (validSoFar, inputCmp) {
                // Show help message if single field is invalid
                inputCmp.showHelpMessageIfInvalid();
                // return whether all fields are valid or not
                return validSoFar && inputCmp.get('v.validity').valid;
                }, true);
                // If all fields are not valid increment the counter
                if (!allValid) {
                    blank++;
                }
            } else {
                // If there is only one field, get that field and check for validity (true/false)
                var allValid = casecommentFields;
                // If field is not valid, increment the counter
                if (!allValid.get('v.validity').valid) {
                    blank++;
                }
            }
            // Call the helper method only when counter is 0
            if(blank==0) {
                // Calling saveCaseComments if the button is save
                helper.saveCaseComments(component, event, helper);                
            }
        }
    },
    
    // Function used to delete the casecomments
    deleteCaseComments: function(component, event, helper) {
        // Calling removeCaseComments Helper Function
        helper.removeCaseComments(component, event, helper);
    },

    // Function used to open the casecomment modal
    openModal: function(component, event, helper) {
        var modal = component.find("casecommentModal");
        var modalBackdrop = component.find("casecommentModalBackdrop");
        $A.util.addClass(modal,"slds-fade-in-open");
        $A.util.addClass(modalBackdrop,"slds-backdrop_open");
    },

    // Function used to close the casecomment modal
    closeModal: function(component, event, helper) {
        var modal = component.find("casecommentModal");
        var modalBackdrop = component.find("casecommentModalBackdrop");
        $A.util.removeClass(modal,"slds-fade-in-open");
        $A.util.removeClass(modalBackdrop,"slds-backdrop_open");
    },

    // Function used to create new casecomment
    createcasecomment: function(component, event, helper) {
        var iscasecommentValid = component.validatecasecomment(component, event, helper);
        if(iscasecommentValid) {
           helper.insertcasecomment(component, event, helper);
        }
    },

    // Function to validate new casecomment - Aura method used for the same
    validatecasecomment: function(component, event, helper) {
        // Getting all fields and iterate them to check for validity
        var allValid = component.find('formFieldToValidate').reduce(function (validSoFar, inputCmp) {
            // Show help message if single field is invalid
            inputCmp.showHelpMessageIfInvalid();
            // Get the name of each field
            var name = inputCmp.get('v.name');
            // Check if name is emailField
            if(name=='emailField') {
                // Getting the value of that field
                var value = inputCmp.get('v.value');
                // If value is not equal to robert.wambold@almacgroup.com, add custom validation
                if(value != 'robert.wambold@almacgroup.com') {
                    // Focus on that field to make custom validation work
                    inputCmp.focus();
                    // Setting the custom validation
                    inputCmp.set('v.validity', {valid:false, badInput :true});
                }                
            }
            // Returning the final result of validations
            return validSoFar && inputCmp.get('v.validity').valid;
        }, true);
        // Returning Validate casecomment result in boolen
        return allValid;
    }

})

CaseCommentListCmpHelper.js

({
    // Function to fetch data from server called in initial loading of page
	fetchCaseComments : function(component, event, helper) {
        // Assign server method to action variable
        var action = component.get("c.getCaseCommentList");
        // Getting the parent id from page
        var parentId = component.get("v.recordId");
        // Setting parameters for server method
        action.setParams({
            parentIds: parentId
        });
        // Callback function to get the response
        action.setCallback(this, function(response) {
            // Getting the response state
            var state = response.getState();
            // Check if response state is success
            if(state === 'SUCCESS') {
                // Getting the list of casecomments from response and storing in js variable
                var casecommentList = response.getReturnValue();
                // Set the list attribute in component with the value returned by function
                component.set("v.casecommentList",casecommentList);
            }
            else {
                // Show an alert if the state is incomplete or error
                alert('Error in getting data');
            }
        });
        // Adding the action variable to the global action queue
        $A.enqueueAction(action);
	},

    // Function to update the casecomments on server
    saveCaseComments: function(component, event, helper) {
        // Getting the casecomment list from lightning component
        var casecommentList = component.get("v.casecommentList");
        // Getting the recordViewForm and recordEditForm component
        var recordViewForm = component.find('recordViewForm');
        var recordEditForm = component.find('recordEditForm'); 
        // Initializing the toast event to show toast
        var toastEvent = $A.get('e.force:showToast');
        // Defining the action to save casecomment List ( will call the saveCaseCommentList apex controller )
        var saveAction = component.get("c.saveCaseCommentList");
        // setting the params to be passed to apex controller
        saveAction.setParams({ casecommentList: casecommentList });
        // callback action on getting the response from server
        saveAction.setCallback(this, function(response) {
            // Getting the state from response
            var state = response.getState();
            if(state === 'SUCCESS') {
                // Getting the response from server
                var dataMap = response.getReturnValue();
                // Checking if the status is success
                if(dataMap.status=='success') {
                    // Remove the formHide class
                    $A.util.removeClass(recordViewForm,'formHide');
                    // Add the formHide class
                    $A.util.addClass(recordEditForm,'formHide');
                    // Getting the button element
                    var btn = event.getSource();
                    // Setting the label and name of button back to edit
                    btn.set('v.name','edit');
                    btn.set('v.label','Edit');
                    // Setting the success toast which is dismissable ( vanish on timeout or on clicking X button )
                    toastEvent.setParams({
                        'title': 'Success!',
                        'type': 'success',
                        'mode': 'dismissable',
                        'message': dataMap.message
                    });
                    // Fire success toast event ( Show toast )
                    toastEvent.fire();            
                }
                // Checking if the status is error 
                else if(dataMap.status=='error') {
                    // Setting the error toast which is dismissable ( vanish on timeout or on clicking X button )
                    toastEvent.setParams({
                        'title': 'Error!',
                        'type': 'error',
                        'mode': 'dismissable',
                        'message': dataMap.message
                    });
                    // Fire error toast event ( Show toast )
                    toastEvent.fire();                
                }
            }
            else {
                // Show an alert if the state is incomplete or error
                alert('Error in getting data');
            }
        });
        $A.enqueueAction(saveAction);
    }    
})

CaseCommentListCmp.css

.THIS {
}
.THIS .formHide {
	display: none;
}
 

*** Thanks again for helping !!! ***

 

 

Hello all,


I have been tasked with creating a way to monitor who is Creating or Modifing Listviews. I know I can view Listviews with SOQL however I would like to use VF.


Is it even possible to be notified when a Listview is Created or Modified? How?


Thanks.


Robert

Hello All,

Has anyone created a VF page to replace the standard page with Salesforce Promotions (https://c.salesforce.com/login-messages/promos.html) content of the right side of the login page? I want to replace the Salesforce Promotions with something more pertinient to my company.

I think many would like to do the same? Can someone point me in the right direction? Any suggestions?

Thanks,

Robert

 

 

Happy Friday All!

Our AEs don't always remeber to add CampaignMembers when they create Tasks related to the Campaign. To save the AEs and kepp marketing happy it was decided that we could use an Apex Trigger to check if the Contact was already a CampaignMember and add if they were not.

I think my code is close, but it is not adding the CampaignMember. Can someone please take a look at my code to show me what I missing?


Kind regards,


Robert.

 

trigger Task_to_CampaignMember on Task (after insert, before update) {

//WhoId is ContactId;
//WhatId is CampaignId;

  List<ID> WhoIds = new List<ID>();
  List<String> prStr = new List<String>();
  List<CampaignMember> newList = new List<CampaignMember>();

for(Task Tsk: Trigger.new){
    String WhtId = Tsk.WhatId;
    String CmpPfx = WhtId.substring(0,3);	 

    if(CmpPfx == '701') //'701' Prefix is Campaign
	{
		prStr.add(Tsk.WhatId); 
	}
}

  
Map<String,Id> cmMap = new Map<String,ID>();

for(CampaignMember cm1 :[select id,CampaignId,ContactId from CampaignMember where CampaignId IN: prStr])
{
	cmMap.put(cm1.CampaignId,cm1.Id);

}

for(Task Tsk: Trigger.new){
    if(Tsk.WhatId!=Null)

	{
		CampaignMember cm = new CampaignMember(CampaignId=Tsk.WhatId,ContactId=Tsk.Whoid,Status='Responded');
		newList.add(cm);
	}
}

if(newList.size()==0)
{
	insert newList;
}


}

In SOQL...select id, whatid from task where WHAT.TYPE = 'Opportunity'.

Is there an alternative to WHAT.TYPE in APEX.

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 All,

I have a simple trigger, PreventCCDeletion that should only allow Users with Profile='System Administrator-2012' or with Permission Set='Super User'  to delete Case Comments. The trigger works well...unfortunately I cannot reach the proper Code Coverage and cannot get over 66%.

Thanks in advance for your help.

Kned regards,

Robert

User-added image

Here is my trigger:

trigger PreventCCDeletion on CaseComment (before delete) {

Boolean YouCanDelete;
YouCanDelete=FALSE; 

    for(CaseComment cc : trigger.old)
    {
       
    // Check for 'System Administrator-2012' Profile
    
      List<Profile> PROFILE = [SELECT Id, Name FROM Profile WHERE Id=:userinfo.getProfileId() LIMIT 1];
      String MyProfileName = PROFILE[0].Name;
      If (MyProfileName=='System Administrator-2012'){ 
        YouCanDelete=TRUE;
      }
    
   
     // Check for 'Super User' ( 0PS0y000000D0dvGAC ) Permission Set
     
     If (YouCanDelete=FALSE){
        List<PermissionSetAssignment> SUPERUSER = [SELECT PermissionSet.Name FROM PermissionSetAssignment WHERE AssigneeId= :UserInfo.getUserId() AND PermissionSet.Name = 'Super_User' LIMIT 1];
        String MyPermissionName = SUPERUSER[0].PermissionSet.Name;
          If (MyPermissionName=='Super_User'){   
          YouCanDelete=TRUE;
        }
      }
  
      If (YouCanDelete=FALSE) 
      { 
        cc.adderror('Case Comments cannot be deleted');
      }
    } 
}
 

Here is my test class:

@isTest
public class PreventCCDeletion_Test{
    
    static Case tCase;
    static CaseComment tComment;
    static Profile tProfile;
    static User tUser;
    
// Start of Test 1    
    static void createTestData1(){
        tCase = new Case();
        tCase.Status = 'Open';
        tCase.Description = 'Test Description-1 ';
        tCase.Origin = 'Annuity External';
        tCase.Type = 'Feature Request';
        tCase.Priority = 'Low';
        INSERT tCase;
        
        tComment = new CaseComment();
        tComment.ParentId = tCase.Id;
        tComment.CommentBody = 'Some Comment-1';
        tComment.IsPublished = TRUE;
        INSERT tComment;
        
        tProfile = 
            [
                SELECT Id 
                FROM   Profile 
                WHERE  Name = 'System Administrator-2012'
            ];
            
        tUser = new User(
            Alias = 'standt', 
            Email='standarduser@testorg.com', 
            EmailEncodingKey='UTF-8', 
            LastName='Testing', 
            LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', 
            ProfileId = tProfile.Id, 
            TimeZoneSidKey='America/Los_Angeles', 
            UserName='testuser@sometestorg.com',
            Non_Use_Send_Deactivation_Alert__c=FALSE,
            DefaultCurrencyIsoCode='USD',
            CurrencyIsoCode='USD',
            ReceivesAdminInfoEmails=FALSE,
            ByPass_New_Hire_Welcome__c=TRUE
        );
        INSERT tUser; 
                             
    }
    
    testMethod
    static void execCaseCommentDelete1(){
    test.startTest();
     
    createTestData1();
    
       try{
           System.runAs(tUser)
            {
             DELETE tComment;
            }
          }
       catch(Exception e){ }
       test.stopTest();
    }    
// End of Test 1


    
// Start of Test 2    
    static void createTestData2(){
        tCase = new Case();
        tCase.Status = 'Open';
        tCase.Description = 'Test Description-2 ';
        tCase.Origin = 'Annuity External';
        tCase.Type = 'Feature Request';
        tCase.Priority = 'Low';
        INSERT tCase;
        
        tComment = new CaseComment();
        tComment.ParentId = tCase.Id;
        tComment.CommentBody = 'Some Comment-2';
        tComment.IsPublished = TRUE;
        INSERT tComment;
        
        tProfile = 
            [
                SELECT Id 
                FROM   Profile 
                WHERE  Name = 'Prod IT Support User'
            ];
            
        tUser = new User(
            Alias = 'standt2', 
            Email='standarduser2@testorg.com', 
            EmailEncodingKey='UTF-8', 
            LastName='Testing', 
            LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', 
            ProfileId = tProfile.Id, 
            TimeZoneSidKey='America/Los_Angeles', 
            UserName='testuser2@sometestorg.com',
            Non_Use_Send_Deactivation_Alert__c=FALSE,
            DefaultCurrencyIsoCode='USD',
            CurrencyIsoCode='USD',
            ReceivesAdminInfoEmails=FALSE,
            ByPass_New_Hire_Welcome__c=TRUE
        );
        INSERT tUser; 
                             
    }
    
    testMethod
    static void execCaseCommentDelete2(){
    test.startTest();
     
    createTestData2();
            
    // Query your permission set name from Organization that your want to test.
       PermissionSet PS2 = [SELECT Id FROM PermissionSet WHERE Name = 'Super_User'];
       PermissionSetAssignment PSA2=new PermissionSetAssignment
       (AssigneeId = tUser.Id,PermissionSetId = PS2.Id); 
                       
       try{
           System.runAs(tUser)
            {
             insert PSA2; 
              System.debug('****testPS2....'+PS2);
              DELETE tComment;
            }
          }
       catch(Exception e){ }
       test.stopTest();
    }    
// End of Test 2
    
}
 

 

 

 

 

Hello all,

I have a Before Update trigger that is working mostly correct. I have added a custom field to User called Send_Deactivation_Alert__c (SDA).

I want the Admin to check the SDA box when a user has not signed on in a long time. I want my trigger to load 2 other fields when the SDA box is checked.

My problem is as soon as I open the User record the SDA gets checked somehow...is this becuse I am using Before Update?

 

trigger Load_Custom_User_Fields_Trigger on User (before update) {
for(User u:trigger.new){
    if (u.Send_Deactivation_Alert__c=TRUE){ 
      u.Last_Login_for_PB_Flows__c = u.LastLoginDate;
      u.Managers_Email_for_PB_Flows__c =         u.Managers_Email_del__c;
      }
    }
}

 

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 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

Happy Friday All!

Our AEs don't always remeber to add CampaignMembers when they create Tasks related to the Campaign. To save the AEs and kepp marketing happy it was decided that we could use an Apex Trigger to check if the Contact was already a CampaignMember and add if they were not.

I think my code is close, but it is not adding the CampaignMember. Can someone please take a look at my code to show me what I missing?


Kind regards,


Robert.

 

trigger Task_to_CampaignMember on Task (after insert, before update) {

//WhoId is ContactId;
//WhatId is CampaignId;

  List<ID> WhoIds = new List<ID>();
  List<String> prStr = new List<String>();
  List<CampaignMember> newList = new List<CampaignMember>();

for(Task Tsk: Trigger.new){
    String WhtId = Tsk.WhatId;
    String CmpPfx = WhtId.substring(0,3);	 

    if(CmpPfx == '701') //'701' Prefix is Campaign
	{
		prStr.add(Tsk.WhatId); 
	}
}

  
Map<String,Id> cmMap = new Map<String,ID>();

for(CampaignMember cm1 :[select id,CampaignId,ContactId from CampaignMember where CampaignId IN: prStr])
{
	cmMap.put(cm1.CampaignId,cm1.Id);

}

for(Task Tsk: Trigger.new){
    if(Tsk.WhatId!=Null)

	{
		CampaignMember cm = new CampaignMember(CampaignId=Tsk.WhatId,ContactId=Tsk.Whoid,Status='Responded');
		newList.add(cm);
	}
}

if(newList.size()==0)
{
	insert newList;
}


}

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 All,

I have a simple trigger, PreventCCDeletion that should only allow Users with Profile='System Administrator-2012' or with Permission Set='Super User'  to delete Case Comments. The trigger works well...unfortunately I cannot reach the proper Code Coverage and cannot get over 66%.

Thanks in advance for your help.

Kned regards,

Robert

User-added image

Here is my trigger:

trigger PreventCCDeletion on CaseComment (before delete) {

Boolean YouCanDelete;
YouCanDelete=FALSE; 

    for(CaseComment cc : trigger.old)
    {
       
    // Check for 'System Administrator-2012' Profile
    
      List<Profile> PROFILE = [SELECT Id, Name FROM Profile WHERE Id=:userinfo.getProfileId() LIMIT 1];
      String MyProfileName = PROFILE[0].Name;
      If (MyProfileName=='System Administrator-2012'){ 
        YouCanDelete=TRUE;
      }
    
   
     // Check for 'Super User' ( 0PS0y000000D0dvGAC ) Permission Set
     
     If (YouCanDelete=FALSE){
        List<PermissionSetAssignment> SUPERUSER = [SELECT PermissionSet.Name FROM PermissionSetAssignment WHERE AssigneeId= :UserInfo.getUserId() AND PermissionSet.Name = 'Super_User' LIMIT 1];
        String MyPermissionName = SUPERUSER[0].PermissionSet.Name;
          If (MyPermissionName=='Super_User'){   
          YouCanDelete=TRUE;
        }
      }
  
      If (YouCanDelete=FALSE) 
      { 
        cc.adderror('Case Comments cannot be deleted');
      }
    } 
}
 

Here is my test class:

@isTest
public class PreventCCDeletion_Test{
    
    static Case tCase;
    static CaseComment tComment;
    static Profile tProfile;
    static User tUser;
    
// Start of Test 1    
    static void createTestData1(){
        tCase = new Case();
        tCase.Status = 'Open';
        tCase.Description = 'Test Description-1 ';
        tCase.Origin = 'Annuity External';
        tCase.Type = 'Feature Request';
        tCase.Priority = 'Low';
        INSERT tCase;
        
        tComment = new CaseComment();
        tComment.ParentId = tCase.Id;
        tComment.CommentBody = 'Some Comment-1';
        tComment.IsPublished = TRUE;
        INSERT tComment;
        
        tProfile = 
            [
                SELECT Id 
                FROM   Profile 
                WHERE  Name = 'System Administrator-2012'
            ];
            
        tUser = new User(
            Alias = 'standt', 
            Email='standarduser@testorg.com', 
            EmailEncodingKey='UTF-8', 
            LastName='Testing', 
            LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', 
            ProfileId = tProfile.Id, 
            TimeZoneSidKey='America/Los_Angeles', 
            UserName='testuser@sometestorg.com',
            Non_Use_Send_Deactivation_Alert__c=FALSE,
            DefaultCurrencyIsoCode='USD',
            CurrencyIsoCode='USD',
            ReceivesAdminInfoEmails=FALSE,
            ByPass_New_Hire_Welcome__c=TRUE
        );
        INSERT tUser; 
                             
    }
    
    testMethod
    static void execCaseCommentDelete1(){
    test.startTest();
     
    createTestData1();
    
       try{
           System.runAs(tUser)
            {
             DELETE tComment;
            }
          }
       catch(Exception e){ }
       test.stopTest();
    }    
// End of Test 1


    
// Start of Test 2    
    static void createTestData2(){
        tCase = new Case();
        tCase.Status = 'Open';
        tCase.Description = 'Test Description-2 ';
        tCase.Origin = 'Annuity External';
        tCase.Type = 'Feature Request';
        tCase.Priority = 'Low';
        INSERT tCase;
        
        tComment = new CaseComment();
        tComment.ParentId = tCase.Id;
        tComment.CommentBody = 'Some Comment-2';
        tComment.IsPublished = TRUE;
        INSERT tComment;
        
        tProfile = 
            [
                SELECT Id 
                FROM   Profile 
                WHERE  Name = 'Prod IT Support User'
            ];
            
        tUser = new User(
            Alias = 'standt2', 
            Email='standarduser2@testorg.com', 
            EmailEncodingKey='UTF-8', 
            LastName='Testing', 
            LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', 
            ProfileId = tProfile.Id, 
            TimeZoneSidKey='America/Los_Angeles', 
            UserName='testuser2@sometestorg.com',
            Non_Use_Send_Deactivation_Alert__c=FALSE,
            DefaultCurrencyIsoCode='USD',
            CurrencyIsoCode='USD',
            ReceivesAdminInfoEmails=FALSE,
            ByPass_New_Hire_Welcome__c=TRUE
        );
        INSERT tUser; 
                             
    }
    
    testMethod
    static void execCaseCommentDelete2(){
    test.startTest();
     
    createTestData2();
            
    // Query your permission set name from Organization that your want to test.
       PermissionSet PS2 = [SELECT Id FROM PermissionSet WHERE Name = 'Super_User'];
       PermissionSetAssignment PSA2=new PermissionSetAssignment
       (AssigneeId = tUser.Id,PermissionSetId = PS2.Id); 
                       
       try{
           System.runAs(tUser)
            {
             insert PSA2; 
              System.debug('****testPS2....'+PS2);
              DELETE tComment;
            }
          }
       catch(Exception e){ }
       test.stopTest();
    }    
// End of Test 2
    
}
 

 

 

 

 

Hello all,

I have a Before Update trigger that is working mostly correct. I have added a custom field to User called Send_Deactivation_Alert__c (SDA).

I want the Admin to check the SDA box when a user has not signed on in a long time. I want my trigger to load 2 other fields when the SDA box is checked.

My problem is as soon as I open the User record the SDA gets checked somehow...is this becuse I am using Before Update?

 

trigger Load_Custom_User_Fields_Trigger on User (before update) {
for(User u:trigger.new){
    if (u.Send_Deactivation_Alert__c=TRUE){ 
      u.Last_Login_for_PB_Flows__c = u.LastLoginDate;
      u.Managers_Email_for_PB_Flows__c =         u.Managers_Email_del__c;
      }
    }
}

 

Hello,

I have a simple trigger to update a few custom fields on the User Profile Object. Not sure what is missing...I want my trigger to fire when the User Profile is updated.

Thanks for your help!

 

trigger Update_User_Custom_Fields_Trigger on User (before insert, before update) {
for(User u:trigger.new){
u.Last_Login_for_PB_Flows__c = u.LastLoginDate;
u.Managers_Email_for_PB_Flows__c = u.Managers_Email_del__c;
u.AboutMe = '*** This is a Test ***'
}
}

 

Hello all,

I have very simple trigger that loads a custom field  NewLead.NetNewLead__c=TRUE when a Lead is Cloned.

trigger Load_Cloned_NetNewLead_Trigger on Lead (before update) {
    for (Lead NewLead : Trigger.new) {
        if (NewLead.isClone() ){
          NewLead.NetNewLead__c=TRUE;
        }
    }
}

 

I am unable to write a test class to meet code coverage requirement. How do I simulate a Cloned Lead?

Thanks for your help.

 

@isTest
private class Load_Cloned_NetNewLead_TriggerTest {

static testMethod void testEx(){
        
Test.startTest();
        
 Account a = new Account(
 Name ='test 1', Industry='Academia', SI_Type__c='Prospect',           BillingCountry='United States');
 insert a; 
     Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Business_Contact').getRecordTypeId();
 

//CREATE CONTACT      
 Contact c=new Contact(
  FirstName='fname',recordtypeid ='0121A0000007rgsQAA',
  LastName = 'lname', accountid = a.Id , 
  Email = 'Test_002.email@gmail.com',
  Clinical_Services__c = True,
  Phone = '9743800309'); 
  insert c; 
 

//CREATE 1ST LEAD                  
Lead l = new Lead(FirstName='FirstName-Test1', LastName='LastName-Test1', Company='Company-Test1', Status='Untouched' , Email='Test_001.email@gmail.com', Industry='Academia' ,LeadSource='Advertising(Online)', Almac_Division__c='CS', NetNewLead__c=TRUE );
insert l ;

//CREATE 2ND LEAD        
Lead l1 = new Lead(FirstName='FirstName-Test2', LastName='LastName-Test2', Company='Company-Test2', Status='Untouched', Email='Test_002.email@gmail.com', Industry='Academia' ,LeadSource='Advertising(Online)', Almac_Division__c='CS', NetNewLead__c=FALSE );
insert l1 ;
    
//ATTEMPT TO CLONE LEAD???       
l1.FirstName='FirstName-Test3';
l1.LastName='LastName-Test3';
l1.Company='Company-Test3';
l1.Status='Untouched';
update l1 ;
System.assertEquals(true, l1.isClone());
        
Test.stopTest();
    }
    }

 

 

Hello all,

I have a Before Insert Trigger on Leads object. On my Leads object I have a custom field, NetNewLead with a default value of TRUE.

My trigger checks the Contacts object looking for a match on Leads.Email = Contacts.Email and when a match is found NetNewLead is set to FALSE.

My trigger works correctly when I enter a new Lead, however Web-To-Lead always sets my custom field NetNewLead to FALSE even when the Leads.Email is not found as a Contacts.Email.

Any ideas? I have includded my code if you would like to take a look.

* I know I need to remove hard-coded check for RecrdTypeId.

Thanks for your help in advance.

Robert.


trigger Update_NetNewLead_Trigger on Lead (before insert) {

// Step 1 - Iterate over incoming Leads and store email in a set
    List<String> leadEmails = new List<String>();
    for(Lead lead:Trigger.new){
        leadEmails.add(lead.Email);
    }

// Step 2 - Check whether there are any existing Business Contacts with matching email

    //Id RecordTypeIdContact = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Business_Contact').getRecordTypeId();

    List<Contact> contacts = [
        SELECT 
            Id, Email 
        FROM 
            Contact
        WHERE 
            //Email IN :leadEmails and RecordTypeId=:RecordTypeIdContact 
            Email IN :leadEmails and RecordTypeId='0121A0000007rgsQAA'
            // Only Select "Business Contacts" 
    ];

    Set<String> contactEmails = new Set<String>();
    for(Contact contact:contacts){
        contactEmails.add(contact.Email);
    }

// Step 3 - Iterate over Leads if Business Contact has matching email set NetNewLead = False
    for(Lead lead:Trigger.new){
        if(contactEmails.contains(lead.Email)){
            lead.NetNewLead__c = False;
        }
    }
}