• GMASJ
  • NEWBIE
  • 335 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 3
    Likes Received
  • 0
    Likes Given
  • 135
    Questions
  • 133
    Replies
Hi, 

Is there a way to get the date different between start and end date in years. 

Example : Start Date = 4/1/2020 and End Date = 4/12/2020 

Can we get a differnce in year? because I need to use this in a formual 

Thanks
GMASJ
  • April 28, 2020
  • Like
  • 0
Hi, 

I need to get this logical formual in salesforce formula. 

Below is the logical formula. 

(365 – ( MIN(365,MAX(0,LSD-FYSD)) + MIN(365,MAX (0,FYED-LED)))*100)/365

Here 
LSD , FYSD, FYED LED are date fields. 

Please suggest me how to put this inside a salesforce formula field. 

Thanks
Sudhir
  • April 21, 2020
  • Like
  • 0
Hi, 

Below code is working when bulk updates are make it is failing can you suggest me what might be the issue in below code. 
public class OpportunityProductPurchased{
    
    @InvocableMethod
    public static void OpplineProdPurch(List<ID> OppId){
    String[] stringList = new String[0];

    list<opportunitylineitem> oplnlst = new list<opportunitylineitem>([select id, name,f_Entitlement_Product_Description__c from opportunitylineitem where opportunityid = :OppId and isdeleted = false and product2.family like '%Subscription%']);
    list<opportunity> opplst = new list<opportunity>();

    for(opportunity opp :[select id, Products_Purchased__c from opportunity where id = :OppId]){
    for(opportunitylineitem opl : oplnlst){
     
        If (opl.f_Entitlement_Product_Description__c!=NULL){
            stringlist.add(opl.f_Entitlement_Product_Description__c);
        
        } 
    }
//Using join method to concatenate f_Entitlement_Product_Description__c field of all the opp line item records
     String allproducts = String.join(stringList, '\n'); 
     opp.Products_Purchased__c = allproducts.remove('null');
     opplst.add(opp);
    }

    if(opplst.size() > 0){
      update opplst;
    }       
  }
}

Thanks
Sam
  • March 24, 2020
  • Like
  • 0
Hi, 

In this below code. 
 
public class OpportuntiyProductPurchased{
    
    @InvocableMethod
    public static void OpplineProdPurch(List<ID> OppId){
    String Str;

    list<opportunitylineitem> oplnlst = new list<opportunitylineitem>([select id, name,f_Entitlement_Product_Description__c from opportunitylineitem where opportunityid = :OppId]);
    list<opportunity> opplst = new list<opportunity>();

    for(opportunity opp :[select id, Products_Purchased__c from opportunity where id = :OppId]){
    for(opportunitylineitem opl : oplnlst){
       system.debug(opl.f_Entitlement_Product_Description__c);  
      Str += opl.f_Entitlement_Product_Description__c;
        If (Str <> null){
         Str = Str;
        } 
    }
     opp.Products_Purchased__c = Str; 
      opplst.add(opp);
    }

    System.debug(Str);

    if(opplst.size() > 0){
      update opplst;
    }       
  } 
}
Values are assigned to string and that string is getting updated to textarea field in opportunity. 

Problem I have here is null and string alignment is one next to another Please suggest me for how to remove null and align string values one below another.

Thanks
Sudhir
  • March 12, 2020
  • Like
  • 0
Hi, 

 Need help in resolving below error happening when adding opportuntiy products Please suggest me what is the issue here. 

Apex trigger SAASTRICS.OpportunityLineTrigger caused an unexpected exception, contact your administrator: SAASTRICS.OpportunityLineTrigger: execution of BeforeInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []: Class.SAASTRICS.OpportunityLineItemTriggerUtil.OrderLineCreation: line 37, column 1 
  
 
Trigger OpportunityLineTrigger on OpportunityLineItem (Before Insert, Before Update, After Insert, After Update){

  if(Trigger.isBefore) {
      OpportunityLineItemTriggerUtil.OrderLineCreation(Trigger.new);  
   }  

}


helper class
=========
public class OpportunityLineItemTriggerUtil{

  public static void OrderLineCreation(List<OpportunityLineItem> newLst){
     list<OrderItem> lstOrdItm = new list<OrderItem>();
     OrderItem ObjOrdItm = new OrderItem();
     
     for(OpportunityLineItem oppLn : newLst){ 
         ObjOrdItm.OrderId = oppLn.opportunity.SAASTRICS__Order__c;
         ObjOrdItm.PricebookEntryId = oppLn.PricebookEntryId;
         ObjOrdItm.Quantity = OppLn.Quantity;
         ObjOrdItm.UnitPrice = OppLn.UnitPrice;

lstOrdItm.add(ObjOrdItm);         
      }
      
       if(!lstOrdItm.isEmpty()){
          insert lstOrdItm;
        }
  
  }
  
}
Thanks
GMASJ
 
  • August 31, 2019
  • Like
  • 0
We have some unused trigger some of active and inactive in production is there a way to delete a trigger in production. 

Thanks
GMASJ
  • June 28, 2019
  • Like
  • 0
Hi, 

  I want to extract owner name from below query. 
SELECT  Ownerid,Ownerid.name,
                Userid,User.name,
                opportunityaccesslevel,teammemberrole FROM UserTeamMember
I am getting below error message. not able to get the relation name please suggest me how to extract name in soql query

User-added image

Thanks
  • May 13, 2019
  • Like
  • 0
Hi,

I want to clear the "localStorage" which is set in JS controller when user logs out of salesforce. It should avaialble only till user is logged in salesforce. 

  Component
<aura:component implements="flexipage:availableForAllPageTypes" access="global" controller="PopupMessageController">  
    <aura:attribute name="ListOfMessage" type="Popup_Message__c[]" description="displayes list of messages"/>
    <aura:handler name='init' action="{!c.doInit}" value="{!this}" /> 
    <aura:attribute name="isOpen" type="boolean" default="False" />
    
    <aura:if isTrue="{!and(v.isOpen,v.ListOfMessage != null)}">          
    <div class="slds-backdrop" aura:id="Modalbackdrop"></div>         
        <div role="dialog" tabindex="-1" aria-labelledby="header43" class='pop-up slds-modal' aura:id="popupDiv1">
            <div class="slds-modal__container">               
              <div class="slds-modal__pinner">                      
                    <div class="message">	
                        <!-- <p>Sudhir First </p> -->                         
                         <ul>  
      					<aura:iteration items="{!v.ListOfMessage}" var="msg">
                             <li> {!msg.Message_Text__c} </li> 
  						   <br/>
      					</aura:iteration>
                        </ul> 
                     </div>                                           
                    <div class="slds-form-element" >
                     <!--   <lightning:button class="slds-button slds-button_neutral" variant="success" label="OK" title="OK" onclick="{!c.close }" /> -->                       
                          <button  onclick="{!c.close }">OK</button>                     
                  </div>
                </div>                    
            </div>
            
        </div>   
        <aura:set attribute="else">
             <div> 
            </div> 
        </aura:set>
   </aura:if> 
</aura:component>

Controller
({
    doInit : function(component, event, helper) {
        var action = component.get('c.fetchMessage',true);
        action.setCallback(this, function(response) {
        //store state of response
        var state = response.getState();
        if (state === "SUCCESS") {
         //set response value in ListOfMessage attribute on component.
         component.set('v.ListOfMessage', response.getReturnValue());
         }
       });
        $A.enqueueAction(action); 
        var temperorySession = localStorage.getItem('tempSession');
         alert(temperorySession);
        if(temperorySession == '1')
        {  
            component.set("v.isOpen", false); //This should be set to false to testing set to true
        }
        else
        {
            component.set("v.isOpen", true);
            var cmpTarget1 = component.find('popupDiv1');
            var cmpBack1 = component.find('Modalbackdrop1');
            $A.util.addClass(cmpTarget1, 'slds-fade-in-open');
            $A.util.addClass(cmpBack1, 'slds-backdrop--open');
            $A.enqueueAction(action); 
        }
        localStorage.setItem('tempSession', '1'); 
        
    },
    close: function(component, event, helper) {
        component.set("v.isOpen", false);
        //localStorage.clear();
    }
})

Please suggest me how to implement.

Thanks

 
  • May 09, 2019
  • Like
  • 0
Hi, 

  Below controller is working as expected but when user tries to open for first time its not working when user clicks for second time only then it starts working. 

I see the issue is because urlEvent.fire() is inside the condition. 

if(erpId != 'nullPPP') { urlEvent.fire(); }

Please suggest me how to fix the first time issue is there an alternative way to approch this isuse. 
({
	doInit : function(component, event, helper) {

        console.log("doInit == Start " );
        var action = component.get("c.getAccessKey");
        action.setParams({
            recordId: component.get("v.recordId")
        });
        action.setCallback(this, function(data) {
            console.log('Return Value _____________' + data.getReturnValue());
            component.set("v.key", data.getReturnValue());
            
             console.log("handleRecordUpdated == Start " );

		var urlEvent = $A.get("e.force:navigateToURL");
        console.log(component.get("v.key") );
        var url = 'https://salesportal.fortinet.com/potracker/login?moduleName=trackingService&accessKey=' +  data.getReturnValue();

        console.log(url);
        urlEvent.setParams({
            "url": url
        });
        var erpId = component.get("v.act.Oracle_ERP_ID__c") + 'PPP';
        console.log(erpId + '___erpd_id ' + ( erpId  != 'nullPPP'));
        if(erpId != 'nullPPP') {
	        urlEvent.fire();
        }
        console.log("doInit == innnEnd");
            
        });
        $A.enqueueAction(action);
                
        console.log("doInit == End");
    },
    handleRecordUpdated: function(component, event, helper) {
        console.log("handleRecordUpdated == Start " );
        var eventParams = event.getParams();
         console.log("eventParams.type == " + eventParams.changeType);
        if(eventParams.changeType === "LOADED") {
           // record is loaded (render other component which needs record data value)
            console.log("Record is loaded successfully. == " + eventParams.changeType);
            console.log("doInit == innnnnStart " );

		var urlEvent = $A.get("e.force:navigateToURL");
        console.log(component.get("v.key") );
        var url = 'https://apptest.fortinet.com/potracker/login?moduleName=trackingService&accessKey=' + component.get("v.key");

        console.log(url);
        urlEvent.setParams({
            "url": url
        });
        //urlEvent.fire();
        console.log("doInit == innnEnd");
            
        } else if(eventParams.changeType === "CHANGED") {
            // record is changed
        } else if(eventParams.changeType === "REMOVED") {
            // record is deleted
        } else if(eventParams.changeType === "ERROR") {
            // there’s an error while loading, saving, or deleting the record
        }
        console.log("handleRecordUpdated == End");
    }		
})
Thanks

 
  • May 06, 2019
  • Like
  • 0
Hi, 

 Below component is working as expected to "System Administrator" profile. I added below component in Home page when user login and have authorized this component to two profiles "System Administrator" and "Finance"

Below component is just a popup screen when "Finance" profile user logs in I am getting below mesage. When system administrator logins it is working Please suggest me what might be the issue here. 

User-added image

  Lightning Component 
<aura:component implements="flexipage:availableForAllPageTypes" access="global"  controller="PopupMessageController">  
    <aura:handler name='init' action="{!c.doInit}" value="{!this}" /> 
    <aura:attribute name="ListOfMessage" type="Popup_Message__c[]" description="displayes list of messages"/>
    <aura:attribute name="isOpen" type="boolean" default="false" />

    <div class="slds-backdrop" aura:id="Modalbackdrop"></div>
    <aura:if isTrue="{!v.isOpen}"> 
        <div role="dialog" tabindex="-1" aria-labelledby="header43" class='pop-up slds-modal' aura:id="popupDiv1">
            <div class="slds-modal__container">
                <div class="slds-modal__pinner">
                    <div class="message">	
                        <!-- <p>Sudhir First </p> -->                         
                        <ul>
      					<aura:iteration items="{!v.ListOfMessage}" var="msg">
         					<li type="dice">{!msg.Message_Text__c}</li>
  						 <hr/>
      					</aura:iteration>
   						</ul>
                     
                     </div>   
                    <div class="slds-form-element">
                        <lightning:button variant="success" label="Ok" title="ok" onclick="{!c.close }" class="OKButton button4"/>
                    </div>
                </div>
            </div>
        </div>
   </aura:if> 
</aura:component>

 Controller
({
    doInit : function(component, event, helper) {
        var action = component.get('c.fetchMessage');
        action.setCallback(this, function(response) {
        //store state of response
        var state = response.getState();
        if (state === "SUCCESS") {
         //set response value in ListOfMessage attribute on component.
         component.set('v.ListOfMessage', response.getReturnValue());
         }
       });
        $A.enqueueAction(action); 
        var temperorySession = localStorage.getItem('tempSession');
        if(temperorySession == '1')
        {  
            component.set("v.isOpen", true); //This should be set to false to testing set to true
        }
        else
        {
            component.set("v.isOpen", true);
            var cmpTarget1 = component.find('popupDiv1');
            var cmpBack1 = component.find('Modalbackdrop1');
            $A.util.addClass(cmpTarget1, 'slds-fade-in-open');
            $A.util.addClass(cmpBack1, 'slds-backdrop--open');
            $A.enqueueAction(action); 
        }
        localStorage.setItem('tempSession', '1');
        
    },
    close: function(component, event, helper) {
        component.set("v.isOpen", false);
    }
})

Class
public class PopupMessageController {
 @AuraEnabled
 public static list <Popup_Message__c> fetchMessage() {
   String profileName = [SELECT Name FROM Profile WHERE Id = :UserInfo.getProfileId() LIMIT 1].name;
   
   
   List<Popup_Message__c> lstOfMsg = [SELECT Message_Text__c, Start_Date__c, End_Date__c, Active_Status__c, Ordering__c, Profile__c FROM Popup_Message__c WHERE Active_Status__c = 'Active' and (Profile__c includes(:profileName) or Profile__c = null) and Start_Date__c <= TODAY and End_Date__c >= TODAY Order by Ordering__c Limit 4];  
   
   return lstOfMsg; 
   
   //return null;
   
 }
}

Thanks
Sam
  • May 06, 2019
  • Like
  • 0
Hi, 

   In custom object Popup_Message__c there is a  custom field  Profile__c which stores comma seprated values now I need a extract a particular value using a soql 

example : In Profile__c is the value is stored as A,B,C

  I want to extract a find if Profile__c = C exit or not. Please suggest me how to extract. 

select Profile__c from Popup_Message__c where Profile__c = 'C' this is not returning 


Thanks 
SUD
  • May 02, 2019
  • Like
  • 0
Hi, 

 I want to write a login in class. Have a custom object with name Popup_Message__c it has two date fields. Start_Date__c and End_Date__c 

 Below is the code I have writen I want to display the rows when Start date <= today and do not display the message when end date is set 

 Example if Start date = 1-May-2019 it must dispaly the message. 
  if End date is  10-May-2019 it must not display the message 

How to add this condition in soql please suggest. 
public class PopupMessageController {
 @AuraEnabled
 public static list <Popup_Message__c> fetchMessage() {
   String profileName = [SELECT Name FROM Profile WHERE Id = :UserInfo.getProfileId() LIMIT 1].name;
  
 List<Popup_Message__c> lstOfMsg = [SELECT Message_Text__c, Start_Date__c, End_Date__c, Active_Status__c, Ordering__c, Profile__c FROM Popup_Message__c WHERE Active_Status__c = 'Active' and ( Profile__c = :profileName or Profile__c = null ) and Start_Date__c <= TODAY  Order by Ordering__c];  
   
  return lstOfMsg;
 }
}
Thanks
Sud
 
  • May 02, 2019
  • Like
  • 0
Hi, 
  
   Below lightning component is working as expected only problem I see in this is when component is called from button for very first time i see both the message are populating same time. normally it must display the message only based on the condition is met. 

"Oracle ERP disti ID" is not set for this account. Please contact system administrator for more information."

 AND

"PO Tracker is lunched in New window!"
 
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" controller="POTrackerExtLtn" >
	<aura:attribute name="act" type="Object"/>
	<aura:attribute name="key" type="String" access="private"/>
    
   <force:recordData aura:id="forceRecord"
                      recordId="{!v.recordId}"
                      targetFields="{!v.act}"
                      fields="Id,Name,Distributor__r.Oracle_ERP_disti_ID__c"
                      recordUpdated="{!c.handleRecordUpdated}"
                      mode="EDIT" />
    <div class="slds-box slds-theme_info">
     
   <!-- console.log("Record Id" + "{!v.recordId}");  
   console.log("Object " + "{!v.act}"); 
   console.log("ERP ID " + "{!v.act.Distributor__r.Oracle_ERP_disti_ID__c}");  -->
   
    <aura:if isTrue="{!v.act.Distributor__r.Oracle_ERP_disti_ID__c == null}">
	<p>"Oracle ERP disti ID" is not set for this account. Please contact system administrator for more information. </p>
    <aura:set attribute="else">
        <p>PO Tracker is lunched in New window!</p>
    </aura:set>
    </aura:if>
        
    </div>
	<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
</aura:component>
 
({
	doInit : function(component, event, helper) {

        console.log("doInit == Start " );
        var action = component.get("c.getAccessKey");
        action.setParams({
            recordId: component.get("v.recordId")
        });
        action.setCallback(this, function(data) {
            console.log('Return Value _____________' + data.getReturnValue());
            component.set("v.key", data.getReturnValue());
            
             console.log("handleRecordUpdated == Start " );

		var urlEvent = $A.get("e.force:navigateToURL");
        console.log(component.get("v.key") );
            var url = 'https://apptest.sudhir.com/potracker/login?moduleName=trackingService&accessKey=' +  data.getReturnValue();
  
        console.log(url);
        urlEvent.setParams({
            "url": url
        });
        var erpId = component.get("v.act.Distributor__r.Oracle_ERP_disti_ID__c") + 'PPP';
        console.log(erpId + '___erpd_id ' + ( erpId  != 'nullPPP'));
        if(erpId != 'nullPPP') {
	        urlEvent.fire();
        }
        console.log("doInit == innnEnd");
            
        });
        $A.enqueueAction(action);
                
        console.log("doInit == End");
    },
    handleRecordUpdated: function(component, event, helper) {
        console.log("handleRecordUpdated == Start " );
        var eventParams = event.getParams();
         console.log("eventParams.type == " + eventParams.changeType);
        if(eventParams.changeType === "LOADED") {
           // record is loaded (render other component which needs record data value)
            console.log("Record is loaded successfully. == " + eventParams.changeType);
            console.log("doInit == innnnnStart " );

		var urlEvent = $A.get("e.force:navigateToURL");
        console.log(component.get("v.key") );
        var url = 'https://apptest.sudhir.com/potracker/login?moduleName=trackingService&accessKey=' + component.get("v.key");

        console.log(url);
        urlEvent.setParams({
            "url": url
        });
        //urlEvent.fire();
        console.log("doInit == innnEnd");
            
        } else if(eventParams.changeType === "CHANGED") {
            // record is changed
        } else if(eventParams.changeType === "REMOVED") {
            // record is deleted
        } else if(eventParams.changeType === "ERROR") {
            // there’s an error while loading, saving, or deleting the record
        }
        console.log("handleRecordUpdated == End");
    }		
})
Please suggest me how to fix this issue. 

Thanks
Sam
 
  • April 25, 2019
  • Like
  • 0
Hi, 

  Code coverage for below class is 90% in sandbox. 
public class LeadTriggerUtils {
    
    public static void processLeadOnUpdate(Map<id, Lead> newMap, Map<id, Lead> oldMap) { 
        List<Lead> leadLst = new List<Lead>();
        for (Lead lead : newMap.values()) {
            Lead oldLead = oldMap.get(lead.id);
            if(lead.rvpe__IsDealRegistration__c && lead.rvpe__RVAccount__c != null && lead.rvpe__RVAccount__c != oldLead.rvpe__RVAccount__c) {
        leadLst.add(lead);
            }
        }
        if(!leadLst.isEmpty()) {
      processChangeOwnerAsPartnerAccount(leadLst); 
        }
    }
    
    public static void processLeadOnInsert(List<Lead> newLst) {
      processChangeOwnerAsPartnerAccount(newLst);
    }
    public static void processChangeOwnerAsPartnerAccount(List<Lead> newLst) {
        List<ID> rvAcctIDs = new List<ID>();
        for(Lead lead : newLst) {
            if(lead.rvpe__IsDealRegistration__c && (lead.Global_Region__c == 'EMEA' || lead.Global_Region__c == 'LATAM') && lead.rvpe__RVAccount__c != null) {
                rvAcctIds.add(lead.rvpe__RVAccount__c);
            }
        }
        Map<ID, rvpe__RVAccount__c> rvActMap = new Map<Id, rvpe__RVAccount__c>([select id, rvpe__SFAccount__c, rvpe__SFAccount__r.OwnerId from rvpe__RVAccount__c where id in :rvAcctIDs]);
        for(Lead lead : newLst) {
            rvpe__RVAccount__c rvAct = rvActMap.get(lead.rvpe__RVAccount__c);
            if(rvAct != null && rvAct.rvpe__SFAccount__c != null) {
                lead.OwnerId = rvAct.rvpe__SFAccount__r.OwnerId;
            }
        }
    }
}

Test Class
@isTest(seealldata=true)
public class LeadTriggerUtilsTest
{
    
    public static testMethod void Method1(){
        
           
          rvpe__RVAccount__c rpv = [select id from rvpe__RVAccount__c where rvpe__SFAccount__c <> null and rvpe__PartnerLevel__c = 'NA Reseller' limit 1];
          rvpe__RVAccount__c rpv2 = [select id from rvpe__RVAccount__c where rvpe__SFAccount__c <> null and rvpe__PartnerLevel__c = 'NA Reseller' limit 1];
          
            Lead l1 = new Lead();
            l1.FirstName = 'Pranavan';
            l1.LastName = 'Karthi';
            l1.Email = 'karthi@pranavan.com';
            l1.Company = 'Pranavan';
            l1.country = 'United States';
            l1.rvpe__IsDealRegistration__c = true;
            l1.Global_Region__c = 'EMEA'; 
            l1.rvpe__RVAccount__c = rpv.id;
            
            insert l1;
            
            l1.FirstName = 'Velu';
            l1.rvpe__RVAccount__c = rpv2.id;
            
            update l1;
            
       }
}

When I try to validate the change set in production it shows 0% code coverage. Please suggest me what is the issue here in test class

Thanks
Sudhir​​​​​​​
  • April 09, 2019
  • Like
  • 0
Hi, 
 
 I wrote below test class for helper class but it is not covering not sure what is the issue when i run the test class its just run in fractions of seconds. 
 
@isTest(seealldata=true)
public class CaseTriggerUtilsTest {

    static void CreateTestData()
    {
      test.StartTest();
 
      Case cse = new Case(Status='New',Case_Category__c='Analytics',Subject='Testing for email',Origin='Email');
      
      insert cse;
      
       test.StopTest();  
     }
     
}

  
public class CaseTriggerUtils {

    private static Set<String> keyWords = new Set<String>{'FW:', 'RE:', 'RW:'};
    private static String CASEORIGIN = 'Email';
    private static integer SUBJLEN = 18;

    public static void processInsert(list<Case> cseLst) {
        String subject;
        Map<String, List<Case>> caseMap = new Map<String, List<Case>>();

        // build map for case orgin from email and subject more than 18 characters        
        for (Case c : cseLst) {
            if ((c.subject <> null) && (c.Origin == CASEORIGIN) && (c.subject.length() >= SUBJLEN) ) {
                subject = c.Subject;
                for(String keyWord : keyWords) {
                    if(subject.startsWith(keyWord)) {
                        subject = subject.replaceFirst(keyWord,'').trim();
                    }
                }
                system.debug('Subject : '  + subject);

                List<Case> cases = new List<Case>();
                if(caseMap.containsKey(subject)) {
                    cases = caseMap.get(Subject);
                }
                cases.add(c);
                caseMap.put(subject, cases);
            }
        }
        
        // loop through subject - case map to get match case owner
        for (String subj: caseMap.keySet()) {
        
            list<case> cseQry = [select id, casenumber,subject,createddate,ownerid,owner.name  from case where CreatedDate = LAST_N_DAYS:10 and subject like :('%' + subj + '%') order by createddate desc limit 1];   
                                                                                         
            for(Case cs: cseQry){
                 system.debug('Case Number :' + cs.casenumber + 'Case Subject : ' + cs.subject);
                 for(Case locCase : caseMap.get(subj)) {
                      if(locCase.Duplicate_With__c == null) {
                           locCase.Duplicate_Case__c = cs.id;
                           locCase.Duplicate_With__c = cs.id;
                           locCase.ownerid = cs.ownerId;
                           System.debug('___KKK__' + locCase);
                      }
                 }
            }
        }        
    }
}

Please suggest me

Thanks
GMASJ
  • March 14, 2019
  • Like
  • 0
Hi, 

 Below trigger on case is not firing when case is created via email. Please suggest me how to fix thi issue.
Trigger
======
trigger CaseTrigger on Case (Before Insert){

   CaseTriggerUtils.processInsert(Trigger.new);

}


Class
=====
public class CaseTriggerUtils {
    
    public static void processInsert(list<Case> cseLst) {        
        processCase(cseLst, new Set<String>{'FW:', 'RE:', 'RW:'});  //Keywords are passed     
    }   
   
 public static void processCase(list<Case> cseLst, Set<String> keyWords) {
        String CaseSubject;
        String CaseId;
        String CaseOwnr;
       
        Map<String, List<String>> keyWordSubjectListMap = new Map<String,List<String>>();
        list<Case> caseLst = new list<Case>();
       
        for (Case c : cseLst) {    
            CaseId = c.id;   
            if(c.subject <> null){
                for(String keyWord : keyWords) {
                    if(c.Subject.contains(keyWord)) {
                        CaseSubject = c.subject.replaceAll(keyWord,'');
                        List<String> subjectList = keyWordSubjectListMap.containsKey(keyWord) ?
                        keyWordSubjectListMap.get(keyWord) : new List<String>();
                        subjectList.add(CaseSubject);
                        keyWordSubjectListMap.put(keyWord, subjectList);
                        break;
                    }
                     if(CaseSubject == null)  
                       CaseSubject = c.subject;
                }
            }
        }
        System.debug('Case Subject' +  CaseSubject);
        System.debug('MAP' + keyWordSubjectListMap);
        
       list<case> cseQry = [select id, casenumber,subject,createddate,ownerid,owner.name from case where CreatedDate = this_year and id <> :CaseId and subject like :('%' + CaseSubject + '%') order by createddate asc limit 10];
        //system.debug('Existing Cases :'  + cs.casenumber + ' ' + cs.subject + ' ' + cs.createddate + ' ' + cs.owner.name); 
        
       for(Case cs: cseLst){     
         if(!cseQry.isEmpty()){  
           if(cs.ownerid <> cseQry[0].ownerid)   // if owner is different from the current owner, then update the owner and set duplicate flag.
             cs.ownerid = cseQry[0].ownerid;   
             cs.Duplicate_With__c = cseQry[0].casenumber;   
           if ( cs.subject.length() > 18 ){    //keyword check is more than 18 character remove keyword and save.
              cs.subject = CaseSubject;
            } 
          }     
       }
        
 }
    
}
Thanks
GMASJ
 
  • March 05, 2019
  • Like
  • 0
Hi, 

  In below code I am hard coding RW: and FW: in the loop to compare and replace please suggest me how to  user keywords. 
public static void processUpdate(list<Case> cseLst) {
        String FWSubject;
        String RWSubject;
        String CaseSubject;
        list<Case> caseLst = new list<Case>();
       
        for (Case c : cseLst) {       
            if(c.subject <> null){     
                // Remove FW and RW from case subject to get exact string
                if(c.subject.Contains('FW:')){
                    FWSubject = c.subject.replaceAll('FW:','');
                    System.debug('FQ Trim String :' + FWSubject);
                    CaseSubject = FWSubject;     
                } else if(c.subject.Contains('RW:')){ 
                    RWSubject = c.subject.replaceAll('RW:','');
                    System.debug('RW Trim String :' + RWSubject);   
                    CaseSubject = RWSubject;

   }
}

Thanks
GMASJ
  • February 28, 2019
  • Like
  • 2
Hi, 

In below trigger its working logically only problem I am facing is its not updating the mached records 
  
Have highlighted the code in bold which is not working. 
trigger CaseTrigger on Case (Before Insert,Before Update){ 
   if(Trigger.isBefore){ 
       CaseTriggerUtils.processInsert(Trigger.new);
    }     
}


public class CaseTriggerUtils {
    
    public static void processInsert(list<Case> cseLst) {        
        processUpdate(cseLst);       
    }   
    
    public static void processUpdate(Map<id, Case> newMap, Map<id, Case> oldMap) { 
        processUpdate(newMap.values());
    }
    
    public static void processUpdate(list<Case> cseLst) {
        String FWSubject;
        String RWSubject;
        String CaseSubject;
        list<Case> caseLst = new list<Case>();
   
        for (Case c : cseLst) {       
            if(c.subject <> null){     
                // Remove FW and RW from case subject to get exact string
                if(c.subject.Contains('FW:')){
                    FWSubject = c.subject.replaceAll('FW:','');
                    System.debug('FQ Trim String :' + FWSubject);
                    CaseSubject = FWSubject;     
                } else if(c.subject.Contains('RW:')){ 
                    RWSubject = c.subject.replaceAll('RW:','');
                    System.debug('RW Trim String :' + RWSubject);   
                    CaseSubject = RWSubject;
                }  else {
                    CaseSubject = c.subject;
                }  
            }                
        }
        
        // Query to get list of all case subject values
        list<case> ctendays = [select id, casenumber,subject,createddate,ownerid,owner.name from case where CreatedDate = LAST_N_DAYS:10 and  subject like :('%' + CaseSubject + '%') order by createddate desc limit 100];
      
        for(case ctndays : ctendays){
            system.debug('Existing Cases :'  + ctndays.casenumber + ' ' + ctndays.subject + ' ' + ctndays.createddate + ' ' + ctndays.owner.name);      
            system.debug('Latest Case Owner ' + ctendays[0].owner.name); 
            
            // If case subject is more than 18 character
            if(ctndays.subject != null &&  ctndays.subject.length() > 18){
                if(FWSubject <> null){
                    ctndays.subject = FWSubject; 
                } else if (RWSubject <> null){
                    ctndays.subject = RWSubject; 
                }
            } 
 
                // Get the latest owner to assign ownership. 
               ctndays.ownerid = ctendays[0].ownerid;
               ctndays.Duplicate_With__c = ctendays[0].casenumber;
               ctndays.New_Hire_Email__c = ctendays[0].owner.name;
               //caseLst.add(ctndays);
            
        }  
  
    }
    
}

 
  • February 22, 2019
  • Like
  • 0
Hi,

   In case object we have a picklist "type" I want to display a alert message when user selects picklist "Enhancement" or "Issue" as value please suggest me how to implement this on salesforce standard page. 

Thanks
Sudhir
  • February 21, 2019
  • Like
  • 0
Hi, 

  I want to add a condition to by pass the case assignment rule for below trigger is working as expected only this I want to add by pass case assignement rule. 
Trigger
======

trigger CaseTrigger on Case (Before Insert, Before Update,After Insert, After Update){
   
   if(Trigger.isAfter ) { 
      if(AvoidRecursion.isFirstRun()) {
         CaseTriggerUtils.processInsert(Trigger.newMap);
         CaseTriggerUtils.processUpdate(Trigger.newMap, Trigger.oldMap);     
      }
    } 
}


Class
=====
public class CaseTriggerUtils {
    
    public static void processInsert(Map<id, Case> newMap) {
        processUpdate(newMap,newMap);
    }   
    
    public static void processUpdate(Map<id, Case> newMap, Map<id, Case> oldMap) {
        String FWSubject;
        String RWSubject;
        String CaseSubject;
        list<Case> caseLst=new list<Case>();
        boolean isExecuted = True;
        
        for (Case c : newMap.values()) {
            
            // Remove FW and RW from case subject to get exact string
            if(c.subject.Contains('FW:')){
                FWSubject = c.subject.replaceAll('FW:','');
                System.debug('FQ Trim String :' + FWSubject);
                CaseSubject = FWSubject;     
            } else if(c.subject.Contains('RW:')){ 
                RWSubject = c.subject.replaceAll('RW:','');
                System.debug('RW Trim String :' + RWSubject);   
                CaseSubject = RWSubject;
            }  else {
                CaseSubject = c.subject;
            }    
            
        }
        
        // Query to get list of all case subject values
        list<case> ctendays = [select id, casenumber,subject,createddate,ownerid,owner.name from case where CreatedDate = this_year and  subject like :('%' + CaseSubject + '%') order by createddate asc limit 100];
        for(case ctndays : ctendays){
            system.debug('Existing Cases :'  + ctndays.casenumber + ' ' + ctndays.subject + ' ' + ctndays.createddate + ' ' + ctndays.owner.name);      
            system.debug('Latest Case Owner ' + ctendays[0].owner.name); 
            
            // If case subject is more than 18 character
            if(ctndays.subject != null &&  ctndays.subject.length() > 18){
                if(FWSubject <> null){
                    ctndays.subject = FWSubject; 
                } else if (RWSubject <> null){
                    ctndays.subject = RWSubject; 
                }
            } 
            
            // Get the latest owner to assign ownership. 
            ctndays.ownerid = ctendays[0].ownerid;
            ctndays.Duplicate_With__c = ctendays[0].casenumber;
            caseLst.add(ctndays);
        }  
        
        if(caseLst.size()>0){
            update caseLst;
        } 
    }
    
}

 
  • February 20, 2019
  • Like
  • 0
Hi, 

  In below code I am hard coding RW: and FW: in the loop to compare and replace please suggest me how to  user keywords. 
public static void processUpdate(list<Case> cseLst) {
        String FWSubject;
        String RWSubject;
        String CaseSubject;
        list<Case> caseLst = new list<Case>();
       
        for (Case c : cseLst) {       
            if(c.subject <> null){     
                // Remove FW and RW from case subject to get exact string
                if(c.subject.Contains('FW:')){
                    FWSubject = c.subject.replaceAll('FW:','');
                    System.debug('FQ Trim String :' + FWSubject);
                    CaseSubject = FWSubject;     
                } else if(c.subject.Contains('RW:')){ 
                    RWSubject = c.subject.replaceAll('RW:','');
                    System.debug('RW Trim String :' + RWSubject);   
                    CaseSubject = RWSubject;

   }
}

Thanks
GMASJ
  • February 28, 2019
  • Like
  • 2
Hi, 

 I have a trigger and a helper class created need a suggestion on how to create a test class for below
trigger RenwalQuote on QuoteLineItem (After Insert, After Update, Before Delete) {
 
 public static Boolean bool = true;
 Set<Id> setid = new Set<id>();
 List<QuoteLineItem> listoli = new  List<QuoteLineItem> ();
 List< OpportunitylineItem> lisopt = new  List< OpportunitylineItem > ();
 List< OpportunitylineItem> Dellisopt = new  List< OpportunitylineItem > ();
 set<id> setoppid = new set<id>();
 set<string> setprodcode = new set<string>();
 set<string> setrecordtype = new set<string>();
 Set<Id> setoldid = new Set<id>();
    
  if(trigger.isafter){
      
   If(preventRecursive.runOnce)return;
   if(bool){
      bool = false;
 
      for (QuoteLineItem qtl :  Trigger.new){
         setid.add(qtl.id);
        }
   } 
 
   List<QuoteLineItem> listem = [Select id,quoteid,Prior_Discount__c,product2.productcode,quote.opportunityid,
                                        quote.opportunity.recordtype.name                   
                                 from QuoteLineItem where id In : Setid];
   
   for(QuoteLineItem qlt:listem){
       
         if ( qlt.quote.opportunity.recordtype.name == 'Renewal Opportunity'){
          qlt.Prior_Discount__c = RenewalUtils.OppLineDisc(qlt.quote.opportunityid,qlt.quoteid,qlt.product2.productcode);
          qlt.Opportunity_Line_Item_ID__c = RenewalUtils.OppLineID(qlt.quote.opportunityid,qlt.quoteid,qlt.product2.productcode);
          system.debug('Quote ID' + qlt.quoteid);
          system.debug('qlt.product2.productcode' + qlt.product2.productcode);
          system.debug('Discount Value' + RenewalUtils.OppLineDisc(qlt.quote.opportunityid,qlt.quoteid,qlt.product2.productcode));
          listoli.add(qlt);
          setoppid.add(qlt.quote.opportunityid);
          setprodcode.add(qlt.product2.productcode);
         }
      } 
       
        if (!listoli.isEmpty()){
          preventRecursive.runOnce = true; update listoli;
                                     
         Opportunity Opp = [select id, Prior_Year_Opportunity__c from Opportunity where id = :setoppid];                                   
                                            
         List<OpportunityLineItem> PrilisOpp = [select id, Renewed__c, opportunity.Prior_Year_Opportunity__c 
                                                from OpportunityLineItem 
                                                where opportunityid = :Opp.Prior_Year_Opportunity__c and 
                                                      product2.productcode = :setprodcode ]; 
        
          for(OpportunitylineItem Opln : PrilisOpp){
              Opln.Renewed__c = true;
              lisopt.add(Opln);
         }
   
           if (!lisopt.isEmpty()){
              update lisopt;
            }  
  
       }
   }    
   
      if(Trigger.isbefore){
      
         for (QuoteLineItem qtl :  Trigger.old){
                setoldid.add(qtl.id);
          }
         
        QuoteLineItem oldQli = [select id, Opportunity_Line_Item_ID__c from QuoteLineItem where id = :setoldid];  
        List<OpportunityLineItem> LstOppline =  [select id, Renewed__c from OpportunityLineItem where id = : oldQli.Opportunity_Line_Item_ID__c];
              
          for(OpportunitylineItem DOpln : LstOppline){
            DOpln.Renewed__c = false;
            Dellisopt.add(DOpln);
          }
          
         if (! Dellisopt.isEmpty()){
                 update Dellisopt;
                }  
        
        
      }
      
}

Helper Class
public with sharing class RenewalUtils {

 public static String OppLineDisc(String QOppID, String Quoteid, String ProdCode) {
 
   Decimal Disctot;
   
   Opportunity ropp = [select Prior_Year_Opportunity__c from opportunity where id = :QOppID and recordtype.name = 'Renewal Opportunity']; 
 
   List<AggregateResult>  Opplst = [select avg(Discount_Percent__c) totdisc
                                    from OpportunityLineItem 
                                    where Opportunityid = :ropp.Prior_Year_Opportunity__c and 
                                          product2.productcode = :ProdCode 
                                          ];
                           
   for (AggregateResult arOpplst : Opplst)
     {
       Disctot = ((Decimal)arOpplst.get('totdisc'));
       
     }                                              
                        
     system.debug(Disctot);
                                              
      return string.valueof(Disctot);
 
 }
 
 
public static String OppLineID(String QOppID, String Quoteid, String ProdCode) {
 
   
   Opportunity ropp = [select Prior_Year_Opportunity__c from opportunity where id = :QOppID and recordtype.name = 'Renewal Opportunity']; 
 
   OpportunityLineItem  Opplst = [select id
                                    from OpportunityLineItem 
                                    where Opportunityid = :ropp.Prior_Year_Opportunity__c and 
                                          product2.productcode = :ProdCode limit 1
                                          ];
                    
     system.debug(Opplst.id);
                                              
      return string.valueof(Opplst.id);
 
 } 
 
}

Recurssive class
public class preventRecursive{
    public static Boolean runOnce = false;
}

Thanks
Sudhir
  • February 28, 2017
  • Like
  • 1
Hi, 

I need to get this logical formual in salesforce formula. 

Below is the logical formula. 

(365 – ( MIN(365,MAX(0,LSD-FYSD)) + MIN(365,MAX (0,FYED-LED)))*100)/365

Here 
LSD , FYSD, FYED LED are date fields. 

Please suggest me how to put this inside a salesforce formula field. 

Thanks
Sudhir
  • April 21, 2020
  • Like
  • 0
Hi, 

In this below code. 
 
public class OpportuntiyProductPurchased{
    
    @InvocableMethod
    public static void OpplineProdPurch(List<ID> OppId){
    String Str;

    list<opportunitylineitem> oplnlst = new list<opportunitylineitem>([select id, name,f_Entitlement_Product_Description__c from opportunitylineitem where opportunityid = :OppId]);
    list<opportunity> opplst = new list<opportunity>();

    for(opportunity opp :[select id, Products_Purchased__c from opportunity where id = :OppId]){
    for(opportunitylineitem opl : oplnlst){
       system.debug(opl.f_Entitlement_Product_Description__c);  
      Str += opl.f_Entitlement_Product_Description__c;
        If (Str <> null){
         Str = Str;
        } 
    }
     opp.Products_Purchased__c = Str; 
      opplst.add(opp);
    }

    System.debug(Str);

    if(opplst.size() > 0){
      update opplst;
    }       
  } 
}
Values are assigned to string and that string is getting updated to textarea field in opportunity. 

Problem I have here is null and string alignment is one next to another Please suggest me for how to remove null and align string values one below another.

Thanks
Sudhir
  • March 12, 2020
  • Like
  • 0
Hi, 

  I want to extract owner name from below query. 
SELECT  Ownerid,Ownerid.name,
                Userid,User.name,
                opportunityaccesslevel,teammemberrole FROM UserTeamMember
I am getting below error message. not able to get the relation name please suggest me how to extract name in soql query

User-added image

Thanks
  • May 13, 2019
  • Like
  • 0
Hi, 

 Below component is working as expected to "System Administrator" profile. I added below component in Home page when user login and have authorized this component to two profiles "System Administrator" and "Finance"

Below component is just a popup screen when "Finance" profile user logs in I am getting below mesage. When system administrator logins it is working Please suggest me what might be the issue here. 

User-added image

  Lightning Component 
<aura:component implements="flexipage:availableForAllPageTypes" access="global"  controller="PopupMessageController">  
    <aura:handler name='init' action="{!c.doInit}" value="{!this}" /> 
    <aura:attribute name="ListOfMessage" type="Popup_Message__c[]" description="displayes list of messages"/>
    <aura:attribute name="isOpen" type="boolean" default="false" />

    <div class="slds-backdrop" aura:id="Modalbackdrop"></div>
    <aura:if isTrue="{!v.isOpen}"> 
        <div role="dialog" tabindex="-1" aria-labelledby="header43" class='pop-up slds-modal' aura:id="popupDiv1">
            <div class="slds-modal__container">
                <div class="slds-modal__pinner">
                    <div class="message">	
                        <!-- <p>Sudhir First </p> -->                         
                        <ul>
      					<aura:iteration items="{!v.ListOfMessage}" var="msg">
         					<li type="dice">{!msg.Message_Text__c}</li>
  						 <hr/>
      					</aura:iteration>
   						</ul>
                     
                     </div>   
                    <div class="slds-form-element">
                        <lightning:button variant="success" label="Ok" title="ok" onclick="{!c.close }" class="OKButton button4"/>
                    </div>
                </div>
            </div>
        </div>
   </aura:if> 
</aura:component>

 Controller
({
    doInit : function(component, event, helper) {
        var action = component.get('c.fetchMessage');
        action.setCallback(this, function(response) {
        //store state of response
        var state = response.getState();
        if (state === "SUCCESS") {
         //set response value in ListOfMessage attribute on component.
         component.set('v.ListOfMessage', response.getReturnValue());
         }
       });
        $A.enqueueAction(action); 
        var temperorySession = localStorage.getItem('tempSession');
        if(temperorySession == '1')
        {  
            component.set("v.isOpen", true); //This should be set to false to testing set to true
        }
        else
        {
            component.set("v.isOpen", true);
            var cmpTarget1 = component.find('popupDiv1');
            var cmpBack1 = component.find('Modalbackdrop1');
            $A.util.addClass(cmpTarget1, 'slds-fade-in-open');
            $A.util.addClass(cmpBack1, 'slds-backdrop--open');
            $A.enqueueAction(action); 
        }
        localStorage.setItem('tempSession', '1');
        
    },
    close: function(component, event, helper) {
        component.set("v.isOpen", false);
    }
})

Class
public class PopupMessageController {
 @AuraEnabled
 public static list <Popup_Message__c> fetchMessage() {
   String profileName = [SELECT Name FROM Profile WHERE Id = :UserInfo.getProfileId() LIMIT 1].name;
   
   
   List<Popup_Message__c> lstOfMsg = [SELECT Message_Text__c, Start_Date__c, End_Date__c, Active_Status__c, Ordering__c, Profile__c FROM Popup_Message__c WHERE Active_Status__c = 'Active' and (Profile__c includes(:profileName) or Profile__c = null) and Start_Date__c <= TODAY and End_Date__c >= TODAY Order by Ordering__c Limit 4];  
   
   return lstOfMsg; 
   
   //return null;
   
 }
}

Thanks
Sam
  • May 06, 2019
  • Like
  • 0
Hi, 

   In custom object Popup_Message__c there is a  custom field  Profile__c which stores comma seprated values now I need a extract a particular value using a soql 

example : In Profile__c is the value is stored as A,B,C

  I want to extract a find if Profile__c = C exit or not. Please suggest me how to extract. 

select Profile__c from Popup_Message__c where Profile__c = 'C' this is not returning 


Thanks 
SUD
  • May 02, 2019
  • Like
  • 0
Hi, 

  Code coverage for below class is 90% in sandbox. 
public class LeadTriggerUtils {
    
    public static void processLeadOnUpdate(Map<id, Lead> newMap, Map<id, Lead> oldMap) { 
        List<Lead> leadLst = new List<Lead>();
        for (Lead lead : newMap.values()) {
            Lead oldLead = oldMap.get(lead.id);
            if(lead.rvpe__IsDealRegistration__c && lead.rvpe__RVAccount__c != null && lead.rvpe__RVAccount__c != oldLead.rvpe__RVAccount__c) {
        leadLst.add(lead);
            }
        }
        if(!leadLst.isEmpty()) {
      processChangeOwnerAsPartnerAccount(leadLst); 
        }
    }
    
    public static void processLeadOnInsert(List<Lead> newLst) {
      processChangeOwnerAsPartnerAccount(newLst);
    }
    public static void processChangeOwnerAsPartnerAccount(List<Lead> newLst) {
        List<ID> rvAcctIDs = new List<ID>();
        for(Lead lead : newLst) {
            if(lead.rvpe__IsDealRegistration__c && (lead.Global_Region__c == 'EMEA' || lead.Global_Region__c == 'LATAM') && lead.rvpe__RVAccount__c != null) {
                rvAcctIds.add(lead.rvpe__RVAccount__c);
            }
        }
        Map<ID, rvpe__RVAccount__c> rvActMap = new Map<Id, rvpe__RVAccount__c>([select id, rvpe__SFAccount__c, rvpe__SFAccount__r.OwnerId from rvpe__RVAccount__c where id in :rvAcctIDs]);
        for(Lead lead : newLst) {
            rvpe__RVAccount__c rvAct = rvActMap.get(lead.rvpe__RVAccount__c);
            if(rvAct != null && rvAct.rvpe__SFAccount__c != null) {
                lead.OwnerId = rvAct.rvpe__SFAccount__r.OwnerId;
            }
        }
    }
}

Test Class
@isTest(seealldata=true)
public class LeadTriggerUtilsTest
{
    
    public static testMethod void Method1(){
        
           
          rvpe__RVAccount__c rpv = [select id from rvpe__RVAccount__c where rvpe__SFAccount__c <> null and rvpe__PartnerLevel__c = 'NA Reseller' limit 1];
          rvpe__RVAccount__c rpv2 = [select id from rvpe__RVAccount__c where rvpe__SFAccount__c <> null and rvpe__PartnerLevel__c = 'NA Reseller' limit 1];
          
            Lead l1 = new Lead();
            l1.FirstName = 'Pranavan';
            l1.LastName = 'Karthi';
            l1.Email = 'karthi@pranavan.com';
            l1.Company = 'Pranavan';
            l1.country = 'United States';
            l1.rvpe__IsDealRegistration__c = true;
            l1.Global_Region__c = 'EMEA'; 
            l1.rvpe__RVAccount__c = rpv.id;
            
            insert l1;
            
            l1.FirstName = 'Velu';
            l1.rvpe__RVAccount__c = rpv2.id;
            
            update l1;
            
       }
}

When I try to validate the change set in production it shows 0% code coverage. Please suggest me what is the issue here in test class

Thanks
Sudhir​​​​​​​
  • April 09, 2019
  • Like
  • 0
Hi, 
 
 I wrote below test class for helper class but it is not covering not sure what is the issue when i run the test class its just run in fractions of seconds. 
 
@isTest(seealldata=true)
public class CaseTriggerUtilsTest {

    static void CreateTestData()
    {
      test.StartTest();
 
      Case cse = new Case(Status='New',Case_Category__c='Analytics',Subject='Testing for email',Origin='Email');
      
      insert cse;
      
       test.StopTest();  
     }
     
}

  
public class CaseTriggerUtils {

    private static Set<String> keyWords = new Set<String>{'FW:', 'RE:', 'RW:'};
    private static String CASEORIGIN = 'Email';
    private static integer SUBJLEN = 18;

    public static void processInsert(list<Case> cseLst) {
        String subject;
        Map<String, List<Case>> caseMap = new Map<String, List<Case>>();

        // build map for case orgin from email and subject more than 18 characters        
        for (Case c : cseLst) {
            if ((c.subject <> null) && (c.Origin == CASEORIGIN) && (c.subject.length() >= SUBJLEN) ) {
                subject = c.Subject;
                for(String keyWord : keyWords) {
                    if(subject.startsWith(keyWord)) {
                        subject = subject.replaceFirst(keyWord,'').trim();
                    }
                }
                system.debug('Subject : '  + subject);

                List<Case> cases = new List<Case>();
                if(caseMap.containsKey(subject)) {
                    cases = caseMap.get(Subject);
                }
                cases.add(c);
                caseMap.put(subject, cases);
            }
        }
        
        // loop through subject - case map to get match case owner
        for (String subj: caseMap.keySet()) {
        
            list<case> cseQry = [select id, casenumber,subject,createddate,ownerid,owner.name  from case where CreatedDate = LAST_N_DAYS:10 and subject like :('%' + subj + '%') order by createddate desc limit 1];   
                                                                                         
            for(Case cs: cseQry){
                 system.debug('Case Number :' + cs.casenumber + 'Case Subject : ' + cs.subject);
                 for(Case locCase : caseMap.get(subj)) {
                      if(locCase.Duplicate_With__c == null) {
                           locCase.Duplicate_Case__c = cs.id;
                           locCase.Duplicate_With__c = cs.id;
                           locCase.ownerid = cs.ownerId;
                           System.debug('___KKK__' + locCase);
                      }
                 }
            }
        }        
    }
}

Please suggest me

Thanks
GMASJ
  • March 14, 2019
  • Like
  • 0
Hi, 

  In below code I am hard coding RW: and FW: in the loop to compare and replace please suggest me how to  user keywords. 
public static void processUpdate(list<Case> cseLst) {
        String FWSubject;
        String RWSubject;
        String CaseSubject;
        list<Case> caseLst = new list<Case>();
       
        for (Case c : cseLst) {       
            if(c.subject <> null){     
                // Remove FW and RW from case subject to get exact string
                if(c.subject.Contains('FW:')){
                    FWSubject = c.subject.replaceAll('FW:','');
                    System.debug('FQ Trim String :' + FWSubject);
                    CaseSubject = FWSubject;     
                } else if(c.subject.Contains('RW:')){ 
                    RWSubject = c.subject.replaceAll('RW:','');
                    System.debug('RW Trim String :' + RWSubject);   
                    CaseSubject = RWSubject;

   }
}

Thanks
GMASJ
  • February 28, 2019
  • Like
  • 2
Hi, 

  I want to update set of records on same object when condition is met below it the logic implemented but its not working 
 
trigger CaseTrigger on Case (After Insert, After Update){
   
   if(Trigger.isAfter && Trigger.isUpdate){
     CaseTriggerUtils.processUpdate(Trigger.newMap, Trigger.oldMap);     
    } 
}


public class CaseTriggerUtils {

 public static void CaseUtils(List<Case> newLst) {  

   public static void processUpdate(Map<id, Case> newMap, Map<id, Case> oldMap) {
      String CaseSubject;
      list<Case> caseLst=new list<Case>();
      boolean isExecuted = True;
      
      for (Case c : newMap.values()) {
           CaseSubject = c.subject;
       }
      
      list<case> ctendays = [select id, casenumber,subject,createddate,ownerid,owner.name from case where CreatedDate = this_year and subject like :('%' + CaseSubject + '%') order by createddate asc limit 10];
      for(case ctndays : ctendays){
         system.debug('Existing Cases :'  + ctndays.casenumber + ' ' + ctndays.subject + ' ' + ctndays.createddate + ' ' + ctndays.owner.name);      
         system.debug('Latest Case Owner ' + ctendays[0].owner.name); 
       
        ctndays.ownerid = ctendays[0].ownerid;
        ctndays.Duplicate_With__c = ctendays[0].casenumber;
        caseLst.add(ctndays);
      }  
      
      if(isExecuted) //To check whether the trigger is not get stuck in recursion if we are updating the same object
        {
          isExecuted=False;
          update caseLst;
        }  
    }
 }
}

I am getting below error 

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger CaseTrigger caused an unexpected exception, contact your administrator: CaseTrigger: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 5002D000004JCQhQAO; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CaseTrigger: maximum trigger depth exceeded Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate Case trigger event AfterUpdate: []: Class.CaseTriggerUtils.processUpdate: line 68, column 1

Please suggest me how to fix this issue. 

Thanks
GMASJ
  • February 18, 2019
  • Like
  • 0
Hi,

   I want to add below code inside trigger please help should this is before insert/update or after insert/update 

  
String FWSubject;
  String RWSubject;
  String CaseSubject;
  list<case> cselst = new list<case>();

    for (Case c : [select id,casenumber,subject,ownerid,owner.name from case where id = '5002D000004JCQm']) {
       system.debug('Case Number :' + c.casenumber); 
       system.debug('Case Subject : ' + c.subject);
       system.debug('Case Subject length : ' + c.subject.length());
       system.debug('Case Owner Name : ' + c.owner.name);
       
       CaseSubject = c.subject;
       
       //Search for FW and RW key word were length of the subject is more than 18
        if(c.subject != null && c.subject.length() > 18){
            if(!c.subject.Contains('FW:')){
              FWSubject = c.subject.replaceAll('FW:','');
              System.debug('FQ Trim String :' + FWSubject);     
         }  
    
        if(!c.subject.Contains('RW:')){ 
         RWSubject = c.subject.replaceAll('RW:','');
         System.debug('RW Trim String :' + RWSubject);   
         }     
       }  
     }
     
   //Map<Id, case> c = new Map<Id, case>([select id, casenumber,subject,createddate,ownerid,owner.name from case where CreatedDate = this_year and subject like :('%' + CaseSubject + '%') order by createddate asc limit 10]);
     
   //Search for same case based on subject within 10days. 
   list<case> ctendays = [select id, casenumber,subject,createddate,ownerid,owner.name from case where CreatedDate = this_year and subject like :('%' + CaseSubject + '%') order by createddate asc limit 10];
    
   for(case ctndays : ctendays){
      system.debug('Existing Cases :'  + ctndays.casenumber + ' ' + ctndays.subject + ' ' + ctndays.createddate + ' ' + ctndays.owner.name);      
       system.debug('Latest Case Owner ' + ctendays[0].owner.name); 
       
      ctndays.ownerid = ctendays[0].ownerid;
      ctndays.Duplicate_With__c = ctendays[0].casenumber;
       cselst.add(ctndays);
      }  
   
if(cselst.size()>0){
     update cselst;
}

Thanks
GMASJ
  • February 15, 2019
  • Like
  • 0
Hi, 

   In below code class CaseTriggerUtils
 
trigger CaseTrigger on Case (Before Insert, Before Update,After Insert, After Update){


   if(Trigger.isBefore) {
      CaseTriggerUtils.CaseUtils(Trigger.new);     
   } 
      

}
There is a error in line  
Map<Id, case> c = new Map<Id, case>([select id, casenumber,subject,createddate,ownerid,owner.name from case where subject like :('%' + CaseSubject + '%') order by createddate asc limit 10]);

When i try to update the case i am getting below error. 

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger CaseTrigger caused an unexpected exception, contact your administrator: CaseTrigger: execution of BeforeUpdate caused by: System.QueryException: Non-selective query against large object type (more than 200000 rows). Consider an indexed filter or contact salesforce.com about custom indexing. Even if a field is indexed a filter might still not be selective when: 1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times): Class.CaseTriggerUtils.CaseUtils: line 31, column 1
public class CaseTriggerUtils {

 public static void CaseUtils(List<Case> newLst) {  
  
  String FWSubject;
  String RWSubject;
  String CaseSubject;
  
    for (Case c : newLst) {
       system.debug('Case Number :' + c.casenumber); 
       system.debug('Case Subject : ' + c.subject);
       system.debug('Case Subject length : ' + c.subject.length());
       system.debug('Case Owner Name : ' + c.owner.name);
       
       CaseSubject = c.subject;
       
       //Search for FW and RW key word were length of the subject is more than 18
        if(c.subject != null && c.subject.length() > 18){
            if(!c.subject.Contains('FW:')){
              FWSubject = c.subject.replaceAll('FW:','');
              System.debug('FQ Trim String :' + FWSubject);     
         }  
    
        if(!c.subject.Contains('RW:')){ 
         RWSubject = c.subject.replaceAll('RW:','');
         System.debug('RW Trim String :' + RWSubject);   
         }     
       }  
     }
     
   Map<Id, case> c = new Map<Id, case>([select id, casenumber,subject,createddate,ownerid,owner.name from case where subject like :('%' + CaseSubject + '%') order by createddate asc limit 10]);
   
     
   //Search for same case based on subject within 10days. 
   /* list<case> ctendays = [select id, casenumber,subject,createddate,ownerid,owner.name from case where subject like :('%' + CaseSubject + '%') order by createddate asc limit 10];

   for(case ctndays : ctendays){
      system.debug('Existing Cases :'  + ctndays.casenumber + ' ' + ctndays.subject + ' ' + ctndays.createddate + ' ' + ctndays.owner.name);      
   }  */
  
  }

}

 
  • February 14, 2019
  • Like
  • 0
Hi, 

  How to by pass trigger for a specific users in salesforce. 

Thanks
Sudhir
  • December 07, 2018
  • Like
  • 0
Hi, 

  There is very old trigger logic written in our instance this is failing due to not being bulkified can someone please suggest how to bulkifie below trigger 
trigger updateprimarycampaign on Opportunity (Before Update ,After insert)
{
 if ( checkRecursive_updateprimarycampaign.runOnce()) 
 {
    if(Trigger.isUpdate)
    {
        try
        {
            for (Opportunity op : Trigger.new) 
            {
                CampaignMember cm = [SELECT CampaignId FROM CampaignMember 
                                     where ContactId = :op.Contact__c and HasResponded = true and 
                                           CreatedDate <= :op.createddate limit 1];
               if ( cm.CampaignId == NULL)
               {
                    op.CampaignId = null;
               } 
               else
               {
                op.CampaignId = cm.CampaignId;
                }
            }
        }
        catch (Exception e)
        {
            for (Opportunity op : Trigger.new) {
                op.CampaignId = null;
            }
        }
    }
    else if (Trigger.isInsert)
    {
        Set<ID> setoppId = new Set<Id>();
        String getCampaignId;

        for(Opportunity opp: Trigger.new ) 
        {
            setoppId.add(opp.id);
        }
     
        List<Opportunity> lstOpp = [select id , CampaignId from Opportunity where id in :setoppId ];
        
        try
        {
            List<Opportunity> lstOppToUpdate = new List<Opportunity>();
            for (Opportunity op : lstOpp) 
            {
                CampaignMember cm = [SELECT CampaignId FROM CampaignMember 
                                     where ContactId = :op.Contact__c and HasResponded = true and
                                           CreatedDate <= :op.createddate limit 1];
               
               if ( cm.CampaignId == NULL)
               {
                    op.CampaignId = null;
                    lstOppToUpdate.add(op);
               } 
                else
               {
                   op.CampaignId = cm.CampaignId;
                   lstOppToUpdate.add(op);
                }
            }
            if(lstOppToUpdate.size() > 0 )
            {
                update lstOppToUpdate;
            }
        }
        catch (Exception e)
        {
            /*
                for ( Opportunity op : lstOpp ) 
                {
                    op.CampaignId = null;
                }
                update lstOpp;
            */
             update lstOpp; 
        }
    }   
}
}
Thanks
Sam
 
  • October 29, 2018
  • Like
  • 0
Hi, 

  Is there a way to send notification when accounts are merged in salesforce. 

Thanks
Sudhir
  • October 29, 2018
  • Like
  • 0
Hi, 

  I need to create a validation rule in contact where user can select one contact as primary associated to an account please suggest me how to add this validation please suggest me a best method to incorporate this rule. 

Thanks
Sudhir
  • October 15, 2018
  • Like
  • 0
Hi, 

 Created a approva process on account object, When submitted for approval notification goes out and able to approve or reject via email reply. 

 When approved or rejected there is a status pick list which gets updated to approved or rejected. Based on this value there is a workflow which updates the account owner conditionally but this workflow or process builder is not getting called or firing. Please suggest me what is the issue is there any other logic to be used. 

Problem is when approved via email other workflow or process builder is not getting fired Please suggest me. 

Thanks
Sudhir
 
  • July 25, 2018
  • Like
  • 0