• NehaDabas16
  • NEWBIE
  • 140 Points
  • Member since 2018
  • Salesforce Consultant

  • Chatter
    Feed
  • 5
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 22
    Replies
Hey there, 

the System.FinalException: Record is read-only error is a well known error when talking about After Insert Triggers. I was wondering what's the most common workaround to resolve it.

Example scenario:

Let's say we want to write an After Insert Trigger that...

1) ... sets a field value in a newly created Lead record
2) ... creates a related record (e.g. Task) and therefore requires the Record Id of the new Lead (this part of the logic actually forces us to go for an After Trigger).

This code apparently will give us the notorious error message:
trigger leadTestTrigger on Lead (after insert) {
    for (Lead myLead : Trigger.new) {
        // We're inserting a value into a field of the initial record
        myLead.AnyField = 'Any Value';
        // Create a task related to the Lead
        Task myTask     = new Task();
        myTask.Subject  = 'Anything';
        myTask.WhoId    = myLead.Id;
        myTask.Priority = 'Normal';
        myTask.Status   = 'Not Started';
        insert myTask;       
    }
}

What's the most used technique to get out of this dilemma? How should the above code be amended?

Best,
David

Hi Folks,

I have two objects:
ParentObject__c (Parent record)
ChildObjetc__c (Child Record)

The relationship between them is master-detail.

I need to create a visualforce page to be able to create a child record, that is, when accessing the details of the parent record, have a custom button that will call the visualforcepage to be able to create a child record, with the parent record id.
Does anyone have any idea code to help me?

I've read everything I can on this error (subject line) but I think I AM querying the request field, so I need help. I have a custom object as the detail side of a Master-Detail relationship with Opportunity as the parent. II'm building a very simple Visualforce page which is placed on the Opportunity screen.
<apex:page standardController="Opportunity" extensions="opportunityListYoY"  sidebar="false" showHeader="false">
    <apex:form >
        <apex:pageBlock >
            <apex:pageMessages />
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!quicksave}"/>
            </apex:pageBlockButtons>
            
            <apex:pageBlockTable value="{!amounts}" var="x" id="list">
            
                <apex:column headerValue="Type">
                    <apex:inputField value="{!x.type__c}"/>
                </apex:column>
                 
                <apex:column headerValue="Opp">
                    <apex:inputField value="{!x.MonthlyRevenueAmounts__r.name}"/>
                </apex:column>
                
                <apex:column headerValue="Amount">
                    <apex:inputField value="{!x.Dollar_Amount__c}"/>
                </apex:column>

            </apex:pageBlockTable> 
        </apex:pageBlock>
    </apex:form>
</apex:page>
The controller extension is:
public class opportunityListYoY {

    private final Opportunity opp;

    public opportunityListYoY(ApexPages.StandardController stdController) {
        this.opp = (Opportunity)stdController.getRecord();
    }

    public ApexPages.StandardSetController setCon {
        get {
            if(setCon == null) {
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
                    [SELECT MonthlyRevenueAmounts__r.name , Dollar_Amount__c, type__c, Fiscal_Date__c, Show_On_Report__c 
                       FROM Revenue_Amount__c
                //    WHERE MonthlyRevenueAmounts__r.name = 'Mikes Opp'  ]));  <--- THIS LINE WORKS FINE
                      WHERE MonthlyRevenueAmounts__r.name = :opp.Name  ]));  <-- this line rasises the error
                    
            }
            return setCon;
        }
        set;
    }

    public List<Revenue_Amount__c> getAmounts() {
        return (List<Revenue_Amount__c>) setCon.getRecords();
    }
}
TIA,
Mike

 

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

 

I've created two custom fields for opportunities that are "Revenue Per Order" and "Yearly Revenue." 

I'd like to create a workflow that says "If Revenue Per Order" does not equal "Amount", modify Amount to equal Revenue Per Order. Revenue per Order is required, while Amount is not. I believe I've gotten the criteria correct, but cannot seem to find the correct immediate actions.

Any help would be greatly appreciated.
Both future methods and queueable apex are types of asynchronous apex. One of the differences between the two is that, future methods can only accept primitive data types parameters and not sObjects, and the reason for that is also justified that object state might change between when the method is called and when it is actually executed.
However we can pass sObjects to Queueable Apex. 

Please help me understand how is sObject state kept in sync in case of Queueable Apex.
Hey there, 

the System.FinalException: Record is read-only error is a well known error when talking about After Insert Triggers. I was wondering what's the most common workaround to resolve it.

Example scenario:

Let's say we want to write an After Insert Trigger that...

1) ... sets a field value in a newly created Lead record
2) ... creates a related record (e.g. Task) and therefore requires the Record Id of the new Lead (this part of the logic actually forces us to go for an After Trigger).

This code apparently will give us the notorious error message:
trigger leadTestTrigger on Lead (after insert) {
    for (Lead myLead : Trigger.new) {
        // We're inserting a value into a field of the initial record
        myLead.AnyField = 'Any Value';
        // Create a task related to the Lead
        Task myTask     = new Task();
        myTask.Subject  = 'Anything';
        myTask.WhoId    = myLead.Id;
        myTask.Priority = 'Normal';
        myTask.Status   = 'Not Started';
        insert myTask;       
    }
}

What's the most used technique to get out of this dilemma? How should the above code be amended?

Best,
David
public class QuoteHandler_PayTerms_GenerateDoc {
    Public void Documenttemplate(list<SBQQ__Quote__c> newlist){
        list<SBQQ__QuoteTemplate__c> qt1 = [select id,Name,SBQQ__Default__c  from SBQQ__QuoteTemplate__c WHERE name =:'Auto Renew'];
        list<SBQQ__QuoteTemplate__c> qt2 = [select id,Name,SBQQ__Default__c  from SBQQ__QuoteTemplate__c WHERE name =:'Auto Renew with Auto pay'];
        list<SBQQ__QuoteTemplate__c> qt3 = [select id,Name,SBQQ__Default__c  from SBQQ__QuoteTemplate__c WHERE name =:'Basic Template'];
        list<SBQQ__QuoteTemplate__c> qt4 = [select id,Name,SBQQ__Default__c  from SBQQ__QuoteTemplate__c WHERE name =:'Basic Template with Auto Pay Form'];
        list<SBQQ__QuoteTemplate__c> qt5 = [select id,Name,SBQQ__Default__c  from SBQQ__QuoteTemplate__c WHERE name =:'Auto Renew with 3% Annual Increment with Autopay'];
        list<SBQQ__QuoteTemplate__c> qt6 = [select id,Name,SBQQ__Default__c  from SBQQ__QuoteTemplate__c WHERE name =:'Auto Renew with 3% Annual Increment'];
        list<SBQQ__QuoteTemplate__c> list1 = new list<SBQQ__QuoteTemplate__c>();
            for(SBQQ__Quote__c ss : newlist)
            {
                if(ss.Document_Template__c=='Auto Renew' && ( ss.SBQQ__PaymentTerms__c=='Monthly' ||  ss.SBQQ__PaymentTerms__c=='Quarterly')   )
                {
                    for(SBQQ__QuoteTemplate__c qq2 : qt2)
                    {
                        for(SBQQ__QuoteTemplate__c qq1 :qt1)
                        {
                            for(SBQQ__QuoteTemplate__c qq3 :qt3)
                            {
                                for(SBQQ__QuoteTemplate__c qq4 :qt4)
                                {
                                    for(SBQQ__QuoteTemplate__c qq5 :qt5)
                                    {
                                        for(SBQQ__QuoteTemplate__c qq6 :qt6)
                                        {
                                    qq2.SBQQ__Default__c = true;
                                    qq1.SBQQ__Default__c = false;
                                    qq3.SBQQ__Default__c = false;
                                    qq4.SBQQ__Default__c = false;
                                    qq5.SBQQ__Default__c = false;
                                    qq6.SBQQ__Default__c = false;
                                    list1.add(qq1);
                                    list1.add(qq2);
                                    list1.add(qq3);
                                    list1.add(qq4);
                                    list1.add(qq5);
                                    list1.add(qq6);
                                    }
                                    }
                               }
                            }
                        }
                    }
                }
                if(ss.Document_Template__c=='Auto Renew' && ( ss.SBQQ__PaymentTerms__c=='Annual' ||  ss.SBQQ__PaymentTerms__c=='Semi-annual' || ss.SBQQ__PaymentTerms__c=='Upfront') )
                {
                    for(SBQQ__QuoteTemplate__c qq2 : qt2)
                    {
                        for(SBQQ__QuoteTemplate__c qq1 :qt1)
                        {
                            for(SBQQ__QuoteTemplate__c qq3 :qt3)
                            {
                                for(SBQQ__QuoteTemplate__c qq4 :qt4)
                                {
                                    for(SBQQ__QuoteTemplate__c qq5 :qt5)
                                    {
                                        for(SBQQ__QuoteTemplate__c qq6 :qt6)
                                        {
                                    qq2.SBQQ__Default__c = False;
                                    qq1.SBQQ__Default__c = True;
                                    qq3.SBQQ__Default__c = False;
                                    qq4.SBQQ__Default__c = False;
                                    qq5.SBQQ__Default__c = false;
                                    qq6.SBQQ__Default__c = false;
                                    list1.add(qq1);
                                    list1.add(qq2);
                                    list1.add(qq3);
                                    list1.add(qq4);
                                    list1.add(qq5);
                                    list1.add(qq6);
                                    }
                                    }
                               }
                            }
                        }
                    }
                }
                if(ss.Document_Template__c=='Auto Renew 3' && ( ss.SBQQ__PaymentTerms__c=='Quarterly' ||  ss.SBQQ__PaymentTerms__c=='Monthly') )
                {
                    for(SBQQ__QuoteTemplate__c qq2 : qt2)
                    {
                        for(SBQQ__QuoteTemplate__c qq1 :qt1)
                        {
                            for(SBQQ__QuoteTemplate__c qq3 :qt3)
                            {
                                for(SBQQ__QuoteTemplate__c qq4 :qt4)
                                {
                                    for(SBQQ__QuoteTemplate__c qq5 :qt5)
                                    {
                                        for(SBQQ__QuoteTemplate__c qq6 :qt6)
                                        {
                                    qq2.SBQQ__Default__c = False;
                                    qq1.SBQQ__Default__c = False;
                                    qq3.SBQQ__Default__c = False;
                                    qq4.SBQQ__Default__c = False;
                                    qq5.SBQQ__Default__c = True;
                                    qq6.SBQQ__Default__c = false;
                                    list1.add(qq1);
                                    list1.add(qq2);
                                    list1.add(qq3);
                                    list1.add(qq4);
                                    list1.add(qq5);
                                    list1.add(qq6);
                                    }
                                    }
                               }
                            }
                        }
                    update list1;
                    }
                }

 
  • July 07, 2019
  • Like
  • 0
Hi ALL,
I am trying to test class for the batch callout class and facing an error and unable to complete the code coverage can someone help me on this and help me get the code coverage.
global class VPS_LoginReminder_Batch_90days implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful {
    
    
    public string myLabel = System.Label.VPS_Inactive_90Days;
   	public integer myInt = Integer.valueOf(myLabel);  
    
    public string myLabel1 = System.Label.VPS_Inactive_180Days;
   	public integer myInt1 = Integer.valueOf(myLabel1); 

                Datetime myDateTime = system.now();
                Datetime inactivationReminder = myDateTime.addDays(myInt);
				Datetime myDateTime1 = system.now();
                Datetime inactivationReminder1 = myDateTime1.addDays(myInt1);
    
    global final List<User> UserList= new List<User>();
    String response;
    
    global Database.QueryLocator start(Database.BatchableContext BC) { 
        
       
        return Database.getQueryLocator([Select id, LastLoginDate, firstName, lastname, email, Contact.name,FederationIdentifier,VPS_AM_Username__c,Username,VPS_SL_60Days_Submitted__c,IsActive From User 
                                         where LastLoginDate!=null AND IsActive=true AND ((LastLoginDate<: inactivationReminder AND LastLoginDate>=:inactivationReminder1  AND VPS_SL_60Days_Submitted__c=false)) 
                                         AND (firstname like 'Sneha' or firstname like 'Vishnu'  or firstname like 'Tesa' or firstname like 'Nafeeza')]);
       
    }
     
    global void execute(Database.BatchableContext BC, List<User> usrList) {
      
        for(User user:usrList){
            UserList.add(user);
        }
        System.debug('userlist size'+userlist.size()+'userlist'+userlist);
        
       }    
     
    global void finish(Database.BatchableContext BC) {
         VPS_oauth_Authentications__c  VPS_oauth = VPS_oauth_Authentications__c.getOrgDefaults() ;
         Integer UserListSize= UserList.size();
         List<User> usrList=new List<user>();
         VPS_Json_ServiceLayer obj= new VPS_Json_ServiceLayer(UserList,VPS_oauth.VPS_Template_90days__c,VPS_oauth.VPS_APINotificationType_Bulk__c);
         String body= obj.returnJSON();
         system.debug('string body returned'+UserList);
        
       
         // Call Service layer
        HttpRequest req = new HttpRequest();
        req.setMethod(VPS_oauth.Address_API_Method__c);
        req.setHeader('apikey',VPS_oauth.VPS_SL_API_Key_for_BULK_RTM__c);
        req.setHeader('Content-Type',VPS_oauth.Address_Header_Content__c);
        req.setHeader('ENV',VPS_oauth.VPS_ENV__c);
        req.setHeader('CCNA',VPS_oauth.Address_Header_CCNA__c);
        req.setHeader('authType',VPS_oauth.Address_Header_AuthType__c);
        req.setEndpoint(VPS_oauth.VPS_Bulk_Email_API_EndPoint_SL__c);
        req.setClientCertificateName(VPS_oauth.ClientCertificateName__c);
        req.setBody(body);
        system.debug('body'+body);
        system.debug('req'+req);
        Http http = new Http();
        HTTPResponse res = http.send(req);
                                system.debug('res'+res);
            if(res.getStatusCode()==200){
                system.debug('success');
                if(UserList.size()>0){
                    for(User usr:UserList){
                    usr.VPS_SL_60Days_Submitted__c=true; 
                    usrList.add(usr);
                              }
                   }
                
               
                                                                
                VPS_Application_Exception_Log__c v= new VPS_Application_Exception_Log__c();
                v.VPS_LoginReminder_Status__c='SUCCESS';
                v.VPS_LoginReminder_TemplateName__c=VPS_oauth.VPS_Template_90days__c;
                v.VPS_LoginReminder_Date__c=System.now();
                v.VPS_LoginReminder_CountOfRecords__c=UserListSize;
                v.VPS_Apex_Class__c='VPS_LoginReminder_Batch_90days';
               v.VPS_Method__c='Batch Execute';
               insert v;
               update usrList;
              
                                } 
        
        else{
            
            if(UserList.size()>0){
                 system.debug('error');
                    for(User usr:UserList){
                    usr.VPS_SL_60Days_Submitted__c=false; 
                    usrList.add(usr);
                              }
                   }
                                               
               update usrList;
               VPS_Application_Exception_Log__c v= new VPS_Application_Exception_Log__c();
               v.VPS_LoginReminder_Status__c='FAILURE';
               v.VPS_LoginReminder_TemplateName__c=VPS_oauth.VPS_Template_90days__c;
               v.VPS_LoginReminder_ErrorMessage__c=res.getBody();
               v.VPS_LoginReminder_Date__c=System.now();
               v.VPS_LoginReminder_CountOfRecords__c=UserListSize;
               v.VPS_Apex_Class__c='VPS_LoginReminder_Batch_90days';
               v.VPS_Method__c='Batch Execute';
               Insert v; 
             } 
                                

}
}
 
Test class:
@isTest 
public class VPS_LoginReminder_Batch_90days_Test {

  public VPS_oauth_Authentications__c  VPS_oauth = VPS_oauth_Authentications__c.getOrgDefaults() ;    
    public static testMethod void setUp()	{ 
    
    Profile pro= [SELECT Id FROM Profile WHERE Name = 'System Administrator' limit 1];
    List<User> userlist = new List<User>();
    for(Integer i=0;i<20;i++){
        User usr = new User(Alias='Test'+i, LastName='User1'+i, email='dcopeland'+i+'@twcny.com', Username='User'+i+'@infosys.com',
                             TimeZoneSidKey = 'America/Los_Angeles', EmailEncodingKey = 'UTF-8', LanguageLocaleKey = 'en_US',
                             LocaleSidKey = 'en_US', ProfileId =pro.Id);
            userlist.add(usr);  
        SYSTEM.debug('userlistsize::'+userlist);
    }    
            insert userlist;
        SYSTEM.debug('userlistsize::'+userlist);
        List<User> usrlist=[select id,name,FirstName,LastName,email,VPS_AM_Username__c,FederationIdentifier,Username,ContactId,LastLoginDate,VPS_SL_60Days_Submitted__c,VPS_UserStatus__c from user LIMIT 100];
        	VPS_Json_ServiceLayer JsonseviceLayer1=new VPS_Json_ServiceLayer(usrList,'Template_90','BULK');
        	String body=JsonseviceLayer1.returnJSON();
        VPS_oauth_Authentications__c  VPS_oauth = new VPS_oauth_Authentications__c();
       		VPS_oauth.VPS_SL_API_Key_for_BULK_RTM__c='apikey';
            VPS_oauth.Address_Header_Content__c='application/json';
            VPS_oauth.VPS_ENV__c='UAT';
            VPS_oauth.Address_Header_CCNA__c='EPO';
            VPS_oauth.Address_Header_AuthType__c='2WAYSSL';
            VPS_oauth.VPS_Bulk_Email_API_EndPoint_SL__c='My end point i can disclose here ';
            VPS_oauth.ClientCertificateName__c='cxdigital';
        	insert VPS_oauth;   
        
        Test.startTest();
        Database.BatchableContext     bc;
        Test.setMock(HttpCalloutMock.class, new VPS_MockHttpResponseGenerator()); 
        VPS_LoginReminder_Batch_90days batch=new VPS_LoginReminder_Batch_90days();
        Database.executeBatch(batch);
        //callout method to performs the callout
        //batch.finish(bc);
        
        Test.stopTest();
   
    }
   

}
 
@isTest
global class VPS_MockHttpResponseGenerator implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
      List<User> usrlist=[select id,name,FirstName,LastName,email,VPS_PortalUserId__c,VPS_AM_Username__c,FederationIdentifier from user where LastLoginDate!=null AND IsActive=true limit 100];
      VPS_Json_ServiceLayer obj= new VPS_Json_ServiceLayer(usrlist,'CX_90_DAY','BULK');
        String body= obj.returnJSON();
         // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('ENDpoint URL', req.getEndpoint());
        System.assertEquals('POST', req.getMethod());
        
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{ "templateName":"CX_90_DAY","users":[{"firstName":"Abhishek","lastName":"Anand","userId":"ananab7","email":"Anand.Abhishek@gmail.com"},{"firstName":"Veera","lastName":"Kishore","userId":"kumave6","email":"Veera.Kishore@gmail.com"} ] }');
        res.setStatusCode(200);
        return res;
    }
}

 
Hi,
I'm completely new to development and I need to develop an integration between Salesforce and a third party service (BKSB). Salesforce needs to consume the REST API. 

I need to write a trigger that will make a callout when a status changes on the custom 'Placement__c' object from '8 - Offer Accepted' to '9 - Induction Booked'. I have the following code so far (asked another dev):
trigger PlacementTrigger on Placement (before update) {
 Map<Id,Placement__c> newPlacList1=new Map<Id,Placement__c>();
 Map<Id,Placement__c> oldPlacList2=new Map<Id,Placement__c>();
 List<Placement__c> newPlacementList=new List<Placement__c>();
 newPlacList1=trigger.new;
 oldPlacList2=trigger.old;
    if(Trigger.IsUpdate && Trigger.isbefore ){
 for(Id placId : newPlacList1.keySet()){
  if(oldPlacList2.get(placId).Status__c == '8 - Offer Accepted' &&
        newPlacList1.get(placId).Status__c == '9 - Induction Booked'){
  newPlacementList.add(placList1.get(placId));
  }
 }
  PlacementTriggerHandler.handlerFunction(newPlacementList); 
    }
}
To identify the correct user's data to GET from the BKSB, the unique identifier is the email address on the Salesforce record. How do I incorporate this so the correct record is chosen in BKSB?
And where do I go from the trigger?

ANY help is much appreciated!!
Many Thanks,
Natasha 
 

Hi Folks,

I have two objects:
ParentObject__c (Parent record)
ChildObjetc__c (Child Record)

The relationship between them is master-detail.

I need to create a visualforce page to be able to create a child record, that is, when accessing the details of the parent record, have a custom button that will call the visualforcepage to be able to create a child record, with the parent record id.
Does anyone have any idea code to help me?

I've read everything I can on this error (subject line) but I think I AM querying the request field, so I need help. I have a custom object as the detail side of a Master-Detail relationship with Opportunity as the parent. II'm building a very simple Visualforce page which is placed on the Opportunity screen.
<apex:page standardController="Opportunity" extensions="opportunityListYoY"  sidebar="false" showHeader="false">
    <apex:form >
        <apex:pageBlock >
            <apex:pageMessages />
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!quicksave}"/>
            </apex:pageBlockButtons>
            
            <apex:pageBlockTable value="{!amounts}" var="x" id="list">
            
                <apex:column headerValue="Type">
                    <apex:inputField value="{!x.type__c}"/>
                </apex:column>
                 
                <apex:column headerValue="Opp">
                    <apex:inputField value="{!x.MonthlyRevenueAmounts__r.name}"/>
                </apex:column>
                
                <apex:column headerValue="Amount">
                    <apex:inputField value="{!x.Dollar_Amount__c}"/>
                </apex:column>

            </apex:pageBlockTable> 
        </apex:pageBlock>
    </apex:form>
</apex:page>
The controller extension is:
public class opportunityListYoY {

    private final Opportunity opp;

    public opportunityListYoY(ApexPages.StandardController stdController) {
        this.opp = (Opportunity)stdController.getRecord();
    }

    public ApexPages.StandardSetController setCon {
        get {
            if(setCon == null) {
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
                    [SELECT MonthlyRevenueAmounts__r.name , Dollar_Amount__c, type__c, Fiscal_Date__c, Show_On_Report__c 
                       FROM Revenue_Amount__c
                //    WHERE MonthlyRevenueAmounts__r.name = 'Mikes Opp'  ]));  <--- THIS LINE WORKS FINE
                      WHERE MonthlyRevenueAmounts__r.name = :opp.Name  ]));  <-- this line rasises the error
                    
            }
            return setCon;
        }
        set;
    }

    public List<Revenue_Amount__c> getAmounts() {
        return (List<Revenue_Amount__c>) setCon.getRecords();
    }
}
TIA,
Mike

 

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

 

Hi Experts,

Below is the formula which flags the field based on the given condition but it is not working as expected. Could someone pls take a look and help to make the corrections.

In nutshell requirement is:
1.
update the flag to white whenever the status is set to Closed
2. Set the flag green if status is “In progress” or “Unread” and Created date time < 24 hrs
3. Set the flag green if status is “In Progress - Awaiting customer reply” or “Status ,"In Progress - Transferred off SF” or In Progress - Customer Replied
4. Set the flag red if status is “In progress” or “Unread” and Created date time > 24 hrs
5. when status “Reopened” and field Case_Age_including_re_open__c < 24hr, flag green and > 24 flag red.



//This will update the flag to white whenever the status is set to Closed
IF( 

(ISPICKVAL( Status ,"Closed - Resolved")) || 
(ISPICKVAL( Status ,"Closed - Spam")) || 
(ISPICKVAL( Status ,"Closed - Withdrawn")) || 
(ISPICKVAL( Status ,"Closed - Transferred off SF")) ,IMAGE("s.gif", "white", 15, 15), 


//Set the flag green if status is “In progress” or “Unread” and Created date time < 24 hrs
IF( 
OR((ISPICKVAL( Status ,"In Progress")), 
(ISPICKVAL( Status ,"Unread"))) && 
(FLOOR((NOW() - CreatedDate)*24) < 24), IMAGE("/img/samples/flag_green.gif", "green", 15, 15), 


// Set the flag green if status is “In Progress - Awaiting customer reply” or “Status ,"In Progress - Transferred off SF” or In Progress - Customer Replied
IF( 
OR((ISPICKVAL( Status ,"In Progress - Awaiting customer reply")), 
(ISPICKVAL( Status ,"In Progress - Transferred off SF")), 
(ISPICKVAL( Status ,"In Progress - Customer Replied"))), IMAGE("/img/samples/flag_green.gif", "green", 15, 15), 

// Set the flag red if status is “In progress” or “Unread” and Created date time > 24 hrs
IF( 
OR((ISPICKVAL( Status ,"In Progress")), 
(ISPICKVAL( Status ,"Unread"))) && 
(FLOOR((NOW() - CreatedDate)) > 24), IMAGE("/img/samples/flag_red.gif", "red", 15, 15), 



//when status “Reopened” and field Case_Age_including_re_open__c < 24hr, flag green
IF( (ISPICKVAL (Status, "Reopened"))&& 
(Case_Age_including_re_open__c)<24, IMAGE("/img/samples/flag_green.gif", "green", 15, 15), 

// when status “Reopened” and field Case_Age_including_re_open__c > 24hr, flag red
IF( (ISPICKVAL (Status, "Reopened"))&& 

(Case_Age_including_re_open__c)>24, IMAGE("/img/samples/flag_red.gif", "red", 15, 15), 
''))))))


TIA
Rahul
I have a Visualforce page using a StandardController with an extension.  Everything works fine but when there are more than 100 items, and I hit the Save (updateSave()) button, I initialliy received the  "Apex governor limit warning".  I then changed the updateSave() to what is below and I then received Too many future calls: 51.

VFP
<apex:page standardController="Asset" docType="html-5.0"   lightningStylesheets="true" recordSetVar="assets" extensions="AssetUpdateController" tabStyle="Asset">
  <!-- Begin Default Content REMOVE THIS -->
<apex:form >
    <apex:pageBlock >
      <apex:pageMessages />
      <center>
       <apex:selectList value="{!productVersionItem}"   size="1" id="typeSelect">               
                  <apex:selectOptions value="{!dropProductVersionItems}"/>
                   <apex:actionSupport event="onchange"  action="{!rePopulateAzzets}"  >
                   </apex:actionsupport>                   
                </apex:selectList>
                </center><br />
      <apex:pageBlockButtons >
        <apex:commandButton value="Mark Listed Items as Inactive" 
                            action="{!groupMarkInactive}"/>
                             <apex:commandButton id="saveBtn" value="Save" action="{!updateSave}" />

          <apex:commandButton id="cancelBtn" value="Cancel" action="{!cancel}" />

      </apex:pageBlockButtons>
      <apex:pageBlockTable value="{!azzets}" 
                           var="ass">
       
        <apex:column headerValue="Asset Name">
     
          <apex:outputField value="{!ass.Name}"/>
        </apex:column>
        <apex:column headerValue="Quantity">
          <apex:outputField value="{!ass.Quantity}"/>
        </apex:column>
        
         <apex:column headerValue="PakSize">
          <apex:outputField value="{!ass.PakSize__c}"/>
        </apex:column>
         <apex:column headerValue="Product Family">
          <apex:outputField value="{!ass.ProductFamily}"/>
        </apex:column>
         <apex:column headerValue="Serial Number">
          <apex:outputField value="{!ass.SerialNumber}"/>
        </apex:column>
         <apex:column headerValue="Satus">
          <apex:inputField value="{!ass.Status}"/>
        </apex:column>
         <apex:column headerValue="Price">
          <apex:outputField value="{!ass.Price}"/>
        </apex:column>
         <apex:column headerValue="Purchase Date">
          <apex:outputField value="{!ass.PurchaseDate}"/>
        </apex:column>
      </apex:pageBlockTable>      
    </apex:pageBlock>
  </apex:form>
  <!-- End Default Content REMOVE THIS -->
</apex:page>

Controller
public  class AssetUpdateController {
      // TestAssetUpdateController
    @AuraEnabled
    public List<Asset> azzets{get;set;}   
    public String AcctId {get;set;} 
    public String productFamilyId {get;set;} 
    Public String productVersionItem{get;set;}
    Public List<SelectOption> dropProductVersionItems {get;set;}
    
    public AssetUpdateController(ApexPages.StandardSetController controller) {
        AcctId = System.currentPageReference().getParameters().get('Id');
        productFamilyId= System.currentPageReference().getParameters().get('PFId');
        getAzzets();
        
    }
    
    
    public List<Asset> getAzzets() {
        
        azzets = [Select Name, PurchaseDate, Price, Status, SerialNumber, ProductFamily, PakSize__c, Quantity 
                  From Asset where Account.id = :AcctId order by ProductFamily ASC];  
        
        dropProductVersionItems = new List<SelectOption>();
        dropProductVersionItems.add(new SelectOption('Filter By Version','Filter By Version'));
        
        //  List <Asset> productFamily = [SELECT ProductFamily  From Asset where Account.id = :AcctId Group by ProductFamily order by ProductFamily DESC];
        
        
        integer i = 0;
        while(i <  azzets.size())
        { 
            if (i==0) {
                dropProductVersionItems.add(new SelectOption(azzets[i].ProductFamily,azzets[i].ProductFamily));
                
            }else{
                if( (azzets[i].ProductFamily != azzets[i-1].ProductFamily))
                {
                    dropProductVersionItems.add(new SelectOption(azzets[i].ProductFamily,azzets[i].ProductFamily));
                }
                
            }
            
            i++;
        }           
        return azzets;    
        
    }
    
    public void rePopulateAzzets() {
        
        azzets = [Select Name, PurchaseDate, Price, Status, SerialNumber, ProductFamily, PakSize__c, Quantity 
                  From Asset where Account.id = :AcctId and ProductFamily = :productVersionItem];  
        
        
        
    }
    
    public void groupMarkInactive() {
        
        Integer i =0;
        while(i <  azzets.size())
        {
            azzets[i].Status = 'Inactive';
            i++;
        }               
        
    }
    
    public Pagereference updateSave() {  
        PageReference newpage = new Pagereference('/lightning/r/'+AcctId + '/related/Assets/view');
        try{
           // new code to work around Govenor Limit
            for(List<Asset> azzetsList : azzets)
            {
                for(Asset aAsset : azzetsList)
                {

                }
                Database.update(azzets);
            }

         // end new code to eliminate Governor Limit

        // Code below works but will cause Governor limit error if too many 
            // azzets.save();
           
            
        }catch(exception e){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,e.getMessage()));
        }             
        
        newpage.setRedirect(true);        
        return newpage;
        
    }
    
    public Pagereference cancel(){
        
        PageReference newpage = new Pagereference('/'+AcctId);
        
        newpage.setRedirect(true);
        
        return newpage;
        
    }
}

​​​​​​​
Hi all,

I have a one date field named "Date__c" if user try to edit record after 7 days from the date which i am havng in field "Date__c"  he/she should not able to edit record.

i am not sure this will work with trigger or validation rule.

If any know help me
I've created two custom fields for opportunities that are "Revenue Per Order" and "Yearly Revenue." 

I'd like to create a workflow that says "If Revenue Per Order" does not equal "Amount", modify Amount to equal Revenue Per Order. Revenue per Order is required, while Amount is not. I believe I've gotten the criteria correct, but cannot seem to find the correct immediate actions.

Any help would be greatly appreciated.
Hi,
Could you please explain me how to bypass a validation rule in the below trigger. The validation rule is to restrict the users not to change the Status manually. The trigger changes the status from Engagement to Negotiation when the user upload the file on Engagement Status. Please see the below trigger and validation rule. I am getting the errors. Could someone please help.
Triiger:
trigger FileUploadonLead on ContentVersion (before insert, after insert, before update, after update) {
map <id,string> lmap = new map <id,string>();
    list<lead> leadlist = new list <lead>();
    
    //Add file upload logic to run this trigger
    //if(Fileupload)
    
    
        if(Trigger.isBefore)
        {
            for(contentversion cv : trigger.new)
            {
                 for(LeadRecord objL: [SELECT Id, Status FROM Lead Where Id = cv.FirstPublishLocationId AND Status = 'Engagement'])
                 {
              objL.On_and_Off__c = true;
                              }
             }
        }
    else
    {
        for(contentversion cv : trigger.new)
        {
            id x = cv.FirstPublishLocationId;
            if(string.valueof(x.getSobjecttype()) == 'lead' && cv.On_and_off__c == true)
            {
                lmap.put(cv.FirstPublishLocationId,'Negotiation');
            }
        }
        
        for(Lead l : [SELECT Id,Status FROM Lead Where Id IN : lmap.KeySet() AND Status = 'Engagement']){
        System.debug('lmap.get()'+ lmap.get(l.id) );
            l.status = lmap.get(l.id);
            leadlist.add(l);
        }
        
        if(leadlist.size()>0){
            system.debug('leadlist' + leadlist);
            update leadlist;
        }
    }
  
    
}

Validation Rule:

OR( 
IF(On_and_Off__c=FALSE, TRUE, FALSE), 
ISCHANGED(Status), 
AND( 
NOT(ISPICKVAL(Status,"Negotiation Lost")), 
OR( 
$Profile.Name <> "System Administrator"
)))
Both future methods and queueable apex are types of asynchronous apex. One of the differences between the two is that, future methods can only accept primitive data types parameters and not sObjects, and the reason for that is also justified that object state might change between when the method is called and when it is actually executed.
However we can pass sObjects to Queueable Apex. 

Please help me understand how is sObject state kept in sync in case of Queueable Apex.
String level ='Top';
String query='select id,Custompicklist__c  from Contact';

 if(Roleslist.size() >0){
        for(Integer i =0; i<roles.size();i++){
            if(i==0){
             query +=' where account.Active__c=true and custompicklistfield__c=:level and roles__c INCLUDES (\''+roleslist[0]+'\'';    
            }else{
            query += ',\''+roleslist[i]+'\'';
            }
           } 
                query += ')' limit 3;     
        }
        c=database.query(query);


THIS BRINGS CONTACT IDs of CONTACTS WHOSE LEVEL IS SET TO HIGH. BUT WHEN the field is set to a null or different value, then the query goes wrong and fetches 0 records.

 
I have a custom formula field called Way__c in custom object(Abc__c) . On UI this field is displayed as a hyperlink.When u click on this link it takes you to a particular folder in Sharepoint. Now i want to send an email to the user using apex code(without using email template) including this field as hyperlink in the body of my email. so that user can click on the hyperlink which navigates to the folder directly in sharepoint. Here is my code...

I am actually getting the path(folder path to sharepoint) here in apex class in variable called Path. Now i have to make this path a hyperlink so that users can click and directly go to sharepoint.

Can someone please help me with this.

if(emailslist.size()>0){
            
                 for(string s: foldermap.keyset())
                 {
                     
                    Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();

                    message.toAddresses = emailslist;
                    message.subject = 'Alert';
                    message.plainTextBody = 'Dear User\n';
                  
                    message.plaintextbody+= '\n\n'+foldermap.get(s)+'\n\n';
                    message.plainTextBody+= '\nPlease click the following URL which directs you to sharepoint folder and take appropriate action \n';
                    message.plainTextBody+= '\nThanks\n';

Thanks,
Kiran