• Sarvani
  • SMARTIE
  • 1555 Points
  • Member since 2018

  • Chatter
    Feed
  • 53
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 0
    Questions
  • 200
    Replies
I want to query those record which have only specific type of picklist value.
Example: suppose we have an object called Company and in this company we have a record SF, AB, DC.
SF has picklist value x
AB has picklist value x,y
DC has picklist value  x there are many record like this....
and some reord has not picklist value.

so i want to query only those record which has picklist value only x. Can anyone help on this.
Hi,

I'm not sure if this is a valid question but I have a request to find out the List of fields that update the last modified date on change of field value in each entity for some custom objects in my org.
 
Below is the trigger  update a field on an attachment or file insert , can some one suggest a test class for this trigger?

Can some one please help in writing a  @isTest class for below trigger to achieve 100 % code completion 
 
trigger ContentDocumentLinkTrigger on ContentDocumentLink (after insert) {
    if(trigger.isAfter) {
        if(trigger.isInsert) {
            ContentDocumentLinkTriggerHandler.onAfterInsert(trigger.new);
        }
    }
}

here is the class
public  class ContentDocumentLinkTriggerHandler {
   
public static void onAfterInsert(list<ContentDocumentLink> lstCntLinks) {
set<Id> setTaskIds = new set<Id>();
list<task> lstTask=new list<task>();
Id recordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('Task_Record_Type').getRecordTypeId();

for(ContentDocumentLink clIterator : lstCntLinks) {  
     setTaskIds.add(clIterator.LinkedEntityId);//Set all task id            
 }

if(!setTaskIds.isEmpty()) {
                lstTask= [SELECT Id, Name,Attachment_Indicator__c  FROM task WHERE Id IN :setTaskIds and recordtypeid=: recordTypeId ]; //Get all the task 
            }

for(task varTsk:  lstTask){
varTsk.Attachment_Indicator__c=true;//Set Attachment Indicator Flag true

}
if(lstTask.size()>0){
update lstTask; //update task
         }
    }
}

Thanks in Advance,
Carolyn
Hi,

Could you please help me in writing test class for below mentioned controller:

Visualforce Page:
<apex:page controller="ServiceTest">
 <style type="text/css">
  #title {
  font-size: 150%;
  margin-left: 30%;
  }
 </style>
  
  <h2 id="title">Update Emp Records</h2><br/><br/>
    <apex:form >
     <apex:pageBlock >
       <apex:pageBlockSection >
       <apex:inputField value="{!emps.Name}"/>
        <apex:outputField value="{!emps.Name}"/>
       <apex:inputField value="{!emps.Start_Date__c}"/>
        <apex:outputField value="{!emps.Start_Date__c}"/>
       <apex:inputField value="{!emps.End_Date__c}"/>
        <apex:outputField value="{!emps.End_Date__c}"/>
      
       </apex:pageBlockSection>
       <apex:pageBlockButtons >
       <apex:commandButton value="Update" action="{!UpdateRecord}"/>
       </apex:pageBlockButtons>
    
         <apex:pageMessage rendered="{!status}" severity="error" />
         <apex:pageMessages />
    
    </apex:pageBlock>
    </apex:form> 
         
</apex:page>




Controller:

public class ServiceTest {
 
  public Employee__c emps {get;set;}
    public boolean status {get;set;}
 
    
    public ServiceTest ()
    {
           status= false;
      emps = [select Name, Start_Date__c, End_Date__c from Employee__c LIMIT 1];   
    }

    
 
    public PageReference updateRecord(){      
        if(emps.Start_Date__c > emps.End_Date__c){          
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Start Date should not be less than End Date'));
            status= true;
        }
        else{
            update emps;
            }
            return null;
            
    
    }    
}


Thanks in Advance.

Regards,

Pavan.
This used to work at one point, and now it does not.  I've observed that the VisualForce page still lists accounts correctly, but when published to a "Site" homepage, it does not.  This suggests a permissions problem, but I don't see anything standing out as incorrect.

This entire process of producing the accounts seems to consist of: a user, a user profile, a visualForce page, a custom Apex class that sets the page size to 2000, and the site page itself.
  • For the custom Apex class, I've verified that the user profile is enabled for it in the security settings.
  • For the Visualforce page, it works perfectly, listing out all the accounts.
  • For the user profile, I've verified that the object settings includes Read permission on the Accounts object, and possesses the Apex Class Access to the custom Apex class.
  • For the site page, editing public access settings takes me to the same user profile that possesses Read permission on the Accounts object.
  • For the user itself, it possesses the guest license and uses the profile with the Read permission on the accounts object.
I've not done much work with Salesforce, so perhaps its something silly and obvious that I am missing.  So, does anyone know what I might be missing, here?  I've tried toggling things that look like they might be associated with reading accounts, such as system permissions to access the Salesforce API or to access the Apex REST API, with no luck.
global class AccountIdGeneration implements Database.Batchable<sObject>,Database.Stateful{
    global String query ;
    List<Account> accountList = new List<Account>();
    global AccountIdGeneration(){
        query = 'Select id, Name, website from account where website != null';
    }
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<account> scope){
        List<account> lstAccount = new List<account>(); 
        for(account acc : scope){
           lstAccount.add(acc);
            
        }
        accountList.addAll(lstAccount);
    }
    global void finish(Database.BatchableContext BC){
        String finalString = 'Generated Id, website, Account Id, Name \n';
        System.debug('--accountList Size---'+accountList.size());
        /*-------------------- Forming Excel String ---------------*/
        for(account acc : accountList){
            Blob cryptoKey = Blob.valueOf('abcdefghijklmnopqrstuvwxyzabcdef');
            // Converting website to blob
            Blob data = Blob.valueOf(acc.website);
            Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoKey, data);
            String encryptedDataStr = EncodingUtil.base64Encode(encryptedData); 
            String key = encryptedDataStr.replaceAll('[^a-zA-Z\\s]', '');
            String str = acc.website.SubStringBefore('.');
            String finalID = '';
            if(str.length() >= 4 ){ finalID = str.substring(0, 4).toUppercase()+key.substring(30, 32).toUppercase(); }
            else if(str.length() < 4 && str.length() == 3){ finalID = str.substring(0, 3).toUppercase() +key.substring(29, 32).toUppercase();} 
            else if (str.length() < 4 && str.length() == 2){ finalID = str.substring(0, 2).toUppercase()+key.substring(28, 32).toUppercase();} 
            else if (str.length() < 4 && str.length() == 1){ finalID = str.substring(0, 1).toUppercase()+key.substring(27, 32).toUppercase();} 
            String recordString = finalID+','+acc.website+','+ acc.id+','+acc.Name+'\n';
            finalString  =  finalString + recordString;    
            
        }
        System.debug('--finalString-'+finalString);
        /*-------------------- Forming Email ---------------*/
        
        Messaging.EmailFileAttachment attachmentFile = new Messaging.EmailFileAttachment();
        blob accountList = Blob.valueOf(finalString);
        string csvname= 'accListFile.csv';
        attachmentFile.setFileName(csvname);
        attachmentFile.setBody(accountList);
        Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
        String email1 = 'test@gmail.com';
        String[] toAddresses = new list<string> {email1};
            String subject ='Account Generated Id List';
        email.setSubject(subject);
        email.setToAddresses( toAddresses );
        email.setPlainTextBody('');
        email.setFileAttachments(new Messaging.EmailFileAttachment[]{attachmentFile});
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
}
We are using this code for generating a 6-bit id for an account. When executing, the Finish method is not sending any email. logs showing batch apex status as "Ending position out of Bounds: 32".

Note: I am processing more than 10k records.

Please help me with this. Thanks in advance.
 
I am 12-years into Salesforce BUT new to APEX coding and am writing a class to simply trigger an update on all records on Budget__c in order to fire some declarative workflow rules (if anyone has ideas on how to improve the class, please suggest).

The main probem is I am getting an Execute Anonymous Error Line 1 Column 1 Invalid Type: batchBudgetMonthlyUpdate. But this did work and not it doesn't. I don't think I changed anything but maybe I did. The only thing I can think of is I tested it, it worked, then I logged out of sandbox and into production. When I logged back into sandbox, is when it stopped working. I tried checking environment but cannot figure out if this is related or not.
 
// Batch Job for updating all Budget records on the 1st of each month
// 23 April 2020 by Tom Barber cloudconsulting, LLC
global class BudgetMonthlyUpdate implements Database.Batchable<sObject> {
    global String [] email = new String[] {'tbarber@cloudconsultingllc.com'};
   // Email address is used below to send batch job status messages
   
   // Start Method
   global Database.Querylocator start (Database.BatchableContext BC) {
      return Database.getQueryLocator('SELECT id FROM Budget__c');
      // Query to get all the Budget__c object record IDs from all the Budget__c records--no WHERE statement
   }
   
   // Execute method
   global void execute (Database.BatchableContext BC, List<Budget__c> scope) {
       for(Budget__c a : scope)
       {a.Id = a.Id;
       }
     
      if (scope != null && scope.size()>0) {
         // Check if List is empty or not
         Database.update(scope); System.debug('List Size'
            + scope.size());
         // Update the Budget records-doesn't change the value of any record. Basically is a trigger to update all
      }
}
 
   // Finish Method
   global void finish(Database.BatchableContext BC) {
      Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
      
      // The code below will fetch the job Id
      AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors,
      a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById,
      a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];//get the job Id
      System.debug('$$$ Jobid is '+BC.getJobId());
       String APEXjobID = null;
       APEXjobID = +BC.getJobId();
          
      // the code below will send an email to User about the job status
      mail.setToAddresses(email);
      mail.setReplyTo('tbarber@cloudconsultingllc.com'); //Add your email address here
      mail.setSenderDisplayName('RLG Salesforce Apex Batch Processing');
      mail.setSubject('Monthly Budget Update Batch Processing: '+a.Status);
      mail.setPlainTextBody('Apex job ' + APEXjobID +' | Monthly Budget Update completed' + a.CompletedDate + 'with status: ' + a.ExtendedStatus
                            + '\n' + 'This job runs on the 1st of each month and updates all the Budget records on the object so the current month (and year) checkboxes are checked.'
                            + '\n' + a.TotalJobItems+ ' batches with '+a.NumberOfErrors+' failures.'
                            + '\n' + 'Job Items processed:' +a.JobItemsProcessed);
      Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail});
   }
}
Thanks in advance for any help or advice.
 
Hello, I need to delete all files (content document links?) created by a specific user. How would I write that SOQL query? 
Hi there,

'Projects' in our world is a created object. I'm trying to put in place a validation rule to prevent users (with the exception of a few, of course) from changing the status a project out of 'In Execution'. The below code, is an attempt to prevent the status from being changed from 'In Execution' to 'Lead'. The syntax is ok. But the code does not work. I'm seeking help to fix it. Thanks a ton!

AND(
ISCHANGED(Status__c),
(PRIORVALUE(Status__c) = "In Execution"),
(ISPICKVAL (Status__c,"Lead")),
$Profile.Name <> "System Administrator",
$Profile.Name <> "Integration Profile" ,
$Profile.Name <> "Jobscience Administrator",
$UserRole.Name <>"Contract Team"
)
Hello, I need some help assigning the owner of Contact records because of the way in which I am creating these records in the first place. We have an integration built which automatically creates Leads. Now, we have a Trigger (on Lead) that picks up information in some custom Lead fields, and based on those creates new Contact records. 

I want the owner of the Contact record to ALWAYS be the same as the owner of the Lead record. The reason this is complicated is because immediately when Leads are generated by our integration, they are at first (in the first milisecond) owned by the person's account who built the integration. Then, we have a Lead Process Builder that changes the Lead owner based on certain criteria. However, since  in our scenario, the Contact records are being generated from a Lead trigger (which comes before Process Builder in the order of execution), the owner of the Contact keeps being assigned to the ORIGINAL lead owner (the account of the integration builders.) I tried using Contact Process Builder to assign the owner of the contact based on the parent Lead's owner, but that doesn't seem to be working.  What would you advise? 
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
Hello All,

I have written a sample batch to update the field and its working but i'm nt able to cover the code coverage. I'm getting System.QueryException: unexpected token:  '2020-03-10' ...
please find the snippet below.
global class batchAccountUpdateSLA implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
      
      Date d = system.today();
        String query = 'SELECT Id,Name FROM Account where After1day__c =:' + d;
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext BC, List<Account> scope) {
         for(Account a : scope)
         {
             a.SLA__c= 'Gold';            
         }
         update scope;
    }   
    
    global void finish(Database.BatchableContext BC) {
    }
}

Test Class:
 
@isTest
 public class batchAccountUpdateSLA_Test{
 Static testmethod void batchAccountUpdateSLA_TestMethod(){
 
 Date d = system.today().addDays(3);
     Account acc = new Account();
     acc.name = 'Test';
     acc.Fax = '12345';
     insert acc;
      Test.StartTest(); 
      batchAccountUpdateSLA bacth = new batchAccountUpdateSLA ();
      ID batchprocessid = database.Executebatch(bacth ); 
      Test.StopTest();
    }
  }

Regards,
VSK98
  • March 10, 2020
  • Like
  • 0
Hello Everyone,
Need help in creation of validation rule.

When Lead Owner is Call Center Agent and Inbound Call checkbox is false you(Call Center Agent) cannot edit Source, Lead Source, Channel Source Fields.

Lead Owner Role: Call Center Agent
Lead Field : Inbound_Call__c
Lead Fields not to get update when Inbound_Call__c is false and Owner Role is Call Center Agent.


Lead Fields not to get update.

Channel :    Channel__c(Picklist) 
Source :      Source__c(Picklist) Dependent on Channel.
Campaign Source: DC_Campaign_Source__c(Picklist)Dependent on Source
Lead Source :   DC_Lead_Source__c(Picklist) Dependent on                                          Campaign Source


Validation Rule is required to show a message that
if
Lead Owner role is Call Center Agent
Field Inbound_Call__c is false
then you(Call Center Agent) cant update these fields.


Please help me for this Validation rule.

Thanks and Regards,
Azar Khasim.
 
Hello,
I have a class that updates a field on the Acocunt object when a Note is inserted or updated.  I am having an issue on Delete. 
If a Note is deleted I want to grab the remining Note with the most recent LastModifiedDate.  I would use the body in this note to update the field on the Accoun the record.   But I am not able to get that record.  I just keep querying the record that is being deleted.  So the Account field is never updated.  And if there are no remaining noted I want the Account field to be null.  
Thanks,
P
The trigger should relate the Contact to the Account record.  I have tried the following code.  I am getting an error message on the line, "WhatID = acc.ID;"

trigger CreateContact on Account (after insert) {
    for (Account acc : Trigger.new){
        Contact c = new Contact();
        c.FirstName = 'Jo Jo';
        c.LastName = 'Murphy';
        WhatID = acc.ID;
        insert c;        
    }

}
My use case is that I have a picklist on a custom object, and one of the values on the picklist is "files uploaded". So I need to build an 'after insert' trigger that when a file is uploaded to this object (not any other objects), the value of that picklist automatically gets updated to "files uploaded". So 2 questions:
1. What Object should the trigger be built on?
2. How would the SOQL query be written to say that it's only for files related to this one specific custom object's records?

Any help is greatly appreciated. 
Hello all,
I have a trigger to update a field on the Account when a note is created but I having trouble converting my trigger into a Class.
trigger UpdateAccWithLastNote on Note (before insert) {

  /*  List<Account> actLstToUpdate=new List<Account>();
    if(Trigger.isInsert){
        for(Note nt : Trigger.new){
            if(String.valueOf(nt.parentId).startsWith('001')){
                Account acc = new Account(Id=nt.parentId,Last_Note__c=nt.Body); 
               actLstToUpdate.add(acc);
           }   
        }
    }
 
    if(!actLstToUpdate.isEmpty()){
        try{
            update actLstToUpdate;
        }catch(DmlException de ){
            System.debug(de);
        }
    } */
}

 
i am writing a test Class to detect duplicate based on 3 custom fields called User__c, Quater_Year__c,Month__c , i have written the bulkified code and invoked the class from a trigger, how do i cover 100%

Handler class
 
public class ContactTriggerHandler {

    public static void dupContactError (List <Contact> newTrigCon) {
        
            Id recordTypeId = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('Contact').getRecordTypeId();
        
    //List of all Contact Records currently in the database    
    List <Contact> allCon = [SELECT ID, Name, User__c, Quater_Year__c,RecordTypeId, Month__c FROM Contact where RecordTypeId=:recordTypeId];
        
        //Iterate through new potential records
        for (Contact oneConTrig : newTrigCon) {
            
            //Needed to iterate through all existing records which is contained in the allCon List
            for (Integer i = 0; i < allCon.size(); i++)
            
            //If all conditions are met, there is a duplicate and thus, returns an error.
            if (oneContrig.User__c == allCon[i].User__c 
                && oneContrig.Quater_Year__c == allCon[i].Quater_Year__c 
                && oneConTrig.Month__c == allCon[i].Month__c
                && oneConTrig.RecordTypeId == allCon[i].RecordTypeId) {

                    oneConTrig.addError('Duplicate Contact Error! This record already exists.');
 
           }
        }      
    }
}

Trigger
 
trigger ContactTrigger on Contact (before insert, before update) {

    ContactTriggerHandler.dupContactError(Trigger.new);
    
}

My Test class with 50% code coverage
 
@isTest
public class ContactTriggerHandlerTestClass {
    
    static testmethod void Duplication(){
        
        List<Contact> Contacts = new list <Contact>();
        Id RecordTypeIdLead = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Contact').getRecordTypeId();
        
        Account testAccount = new Account();
        testAccount.Name='DCCL' ;
        insert testAccount;
        
        contact con = new contact();
        con.FirstName='Julian';
        con.LastName='Rogers';
        con.Month__c = 'march';
        con.Quater_Year__c = '2020';
        con.AccountId = testAccount.id;
        con.Email = 'hello123@gmail.com';
        Contacts.add(con);
        insert con;
    }
    
}

​​​​​​​
Hi All,

Can anyone please help me. I am new to Salesforce.
I am getting Record read-only error while trying to update a field in Account object in a before trigger. 
Created a new field as Previous_Type__c which will store the Previous value of Account Type.
Trigger: 
trigger AccountTypeUpdate on Account (before update) {
    
    if(Trigger.isBefore && Trigger.isUpdate){
        if(AccountTypeUpdateClass.isTriggerExecuted){
                   AccountTypeUpdateClass.isTriggerExecuted = false;
        
                for(Account Acc: Trigger.old){
                    AccountTypeUpdateClass.ChangeType(Acc);   
                }  
        }
    }
}
Apex Class:
public class AccountTypeUpdateClass {
    public static boolean isTriggerExecuted = True;  
        public static void ChangeType(Account obj)
        {
                obj.Previous_Type__c = obj.Type;
        } 
}

Error Message:
AccountTypeUpdate: execution of BeforeUpdate caused by: System.FinalException: Record is read-only Class.AccountTypeUpdateClass.ChangeType: line 5, column 1 Trigger.AccountTypeUpdate: line 8, column 1
I am looking for a way to copy the emails from a calendar event and returning just the email string, rather than the name and email string. 

Ideally it would look like: john@esource.com,nick@esource.com

I have been playing around with the TRIM and SUBSTITUTE functions but have been struggling to get it just right. 

Any help would be greatly appreciated. 

Thanks!
Tasia
I want to query those record which have only specific type of picklist value.
Example: suppose we have an object called Company and in this company we have a record SF, AB, DC.
SF has picklist value x
AB has picklist value x,y
DC has picklist value  x there are many record like this....
and some reord has not picklist value.

so i want to query only those record which has picklist value only x. Can anyone help on this.
Hi,

I'm not sure if this is a valid question but I have a request to find out the List of fields that update the last modified date on change of field value in each entity for some custom objects in my org.
 
Below is the trigger  update a field on an attachment or file insert , can some one suggest a test class for this trigger?

Can some one please help in writing a  @isTest class for below trigger to achieve 100 % code completion 
 
trigger ContentDocumentLinkTrigger on ContentDocumentLink (after insert) {
    if(trigger.isAfter) {
        if(trigger.isInsert) {
            ContentDocumentLinkTriggerHandler.onAfterInsert(trigger.new);
        }
    }
}

here is the class
public  class ContentDocumentLinkTriggerHandler {
   
public static void onAfterInsert(list<ContentDocumentLink> lstCntLinks) {
set<Id> setTaskIds = new set<Id>();
list<task> lstTask=new list<task>();
Id recordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('Task_Record_Type').getRecordTypeId();

for(ContentDocumentLink clIterator : lstCntLinks) {  
     setTaskIds.add(clIterator.LinkedEntityId);//Set all task id            
 }

if(!setTaskIds.isEmpty()) {
                lstTask= [SELECT Id, Name,Attachment_Indicator__c  FROM task WHERE Id IN :setTaskIds and recordtypeid=: recordTypeId ]; //Get all the task 
            }

for(task varTsk:  lstTask){
varTsk.Attachment_Indicator__c=true;//Set Attachment Indicator Flag true

}
if(lstTask.size()>0){
update lstTask; //update task
         }
    }
}

Thanks in Advance,
Carolyn
I have created a date/time field that I would like to be updated to the date/time any time a note is created on an opportunity. I have no experience with Apex Triggers, so I wanted to use process builder, but it doesn't allow processes to be created for the notes object. After reading a few similar posts, I wrote the following trigger, but it doesn't seem to work. If anybody can explain why and how to fix it, I would greatly appreciate it. Thank you in advance. Trigger:

trigger SetOppDate on Note (after insert) {

List<Opportunity> oppsToUpdate = new List<Opportunity>();
    for (Note nRecord : trigger.new) {
        //Check if the note is related to an opportunity
        String parentIdString = String.valueof(nRecord.parentid);
        if (parentIdString.substring(0,3) == '006'){
            //Set the Last_Note__c field on the opportunity
            Opportunity opp = new Opportunity(Id = nRecord.ParentId, Last_Note__c= Date.TODAY());
            oppsToUpdate.add(opp);
       }
    }
    update oppsToUpdate;

}
Hi,

Could you please help me in writing test class for below mentioned controller:

Visualforce Page:
<apex:page controller="ServiceTest">
 <style type="text/css">
  #title {
  font-size: 150%;
  margin-left: 30%;
  }
 </style>
  
  <h2 id="title">Update Emp Records</h2><br/><br/>
    <apex:form >
     <apex:pageBlock >
       <apex:pageBlockSection >
       <apex:inputField value="{!emps.Name}"/>
        <apex:outputField value="{!emps.Name}"/>
       <apex:inputField value="{!emps.Start_Date__c}"/>
        <apex:outputField value="{!emps.Start_Date__c}"/>
       <apex:inputField value="{!emps.End_Date__c}"/>
        <apex:outputField value="{!emps.End_Date__c}"/>
      
       </apex:pageBlockSection>
       <apex:pageBlockButtons >
       <apex:commandButton value="Update" action="{!UpdateRecord}"/>
       </apex:pageBlockButtons>
    
         <apex:pageMessage rendered="{!status}" severity="error" />
         <apex:pageMessages />
    
    </apex:pageBlock>
    </apex:form> 
         
</apex:page>




Controller:

public class ServiceTest {
 
  public Employee__c emps {get;set;}
    public boolean status {get;set;}
 
    
    public ServiceTest ()
    {
           status= false;
      emps = [select Name, Start_Date__c, End_Date__c from Employee__c LIMIT 1];   
    }

    
 
    public PageReference updateRecord(){      
        if(emps.Start_Date__c > emps.End_Date__c){          
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Start Date should not be less than End Date'));
            status= true;
        }
        else{
            update emps;
            }
            return null;
            
    
    }    
}


Thanks in Advance.

Regards,

Pavan.
trigger UpdateRecordMap on Update(after Update)
{
  Set<Id>accid = new Set<Id>();
    for(Account a : trigger.new)
    {
          accid.add(a.Id);
    }
    List<Contact>listcon = new List<Contact>();
    Map<Id, Account>mapacc = new Map<Id, Account>
    ([Select Id, BillingCity,
                            (Select Id, MailingState From Contacts) 
                    From Account Where Id In :accid]);
   for(Account a : trigger.new)
    {
             Contact con = new Contact();
             con.MailingState = a.BillingCity;
             listcon.add(con);
    }
    if(listcon.size()>0)
    {
        update listcon;
    }

}
Not Update the Record
This used to work at one point, and now it does not.  I've observed that the VisualForce page still lists accounts correctly, but when published to a "Site" homepage, it does not.  This suggests a permissions problem, but I don't see anything standing out as incorrect.

This entire process of producing the accounts seems to consist of: a user, a user profile, a visualForce page, a custom Apex class that sets the page size to 2000, and the site page itself.
  • For the custom Apex class, I've verified that the user profile is enabled for it in the security settings.
  • For the Visualforce page, it works perfectly, listing out all the accounts.
  • For the user profile, I've verified that the object settings includes Read permission on the Accounts object, and possesses the Apex Class Access to the custom Apex class.
  • For the site page, editing public access settings takes me to the same user profile that possesses Read permission on the Accounts object.
  • For the user itself, it possesses the guest license and uses the profile with the Read permission on the accounts object.
I've not done much work with Salesforce, so perhaps its something silly and obvious that I am missing.  So, does anyone know what I might be missing, here?  I've tried toggling things that look like they might be associated with reading accounts, such as system permissions to access the Salesforce API or to access the Apex REST API, with no luck.
I am trying to write Apex code for the following:

Covid 19 Info

Area-Holds info about all covid19 patients in an area
Patient - A person infected with covid 19.  It has a field called state (mild/critical/cured/fatal)

Area and Patient share a lookup relationship

Find out-
1. Avg days to recover in that area (Cured date - CreatedDate)
2. Avg days of fatality (Fatal data - CreatedDate)

Trigger and helper class are below.  I don't have any errors with the code, but I can't get it working.  Any help would be appreciated.  Thank you.
 
trigger CoronaCountyTrigger on Patient__c (after insert, after update, after delete) {

    if (Trigger.isInsert || Trigger.isAfter || Trigger.isDelete) {
        if (Trigger.isAfter) {
            CoronaCountyHelper.avgFatal();
        }
    }
}
 
public with sharing class CoronaCountyHelper {
    public static void avgFatal() {
        Set<Id> countyIds = new Set<Id>();
        List<County__c> countyList = new List<County__c>();
        List<Patient__c> patientList = Trigger.isInsert || Trigger.isUpdate ? Trigger.new : Trigger.old;
        for (Patient__c pat1 : patientList) {
            countyIds.add(pat1.County__c);
        }

        for (AggregateResult ag : [
                SELECT County__c, AVG(Days_Until_Fatal__c) avg1
                FROM Patient__c
                GROUP BY County__c
        ]) {
            countyList.add(new County__c(
                    Id = (Id) ag.get('County__c'),
                    AVG_Days_Until_Fatal__c = (Integer) ag.get('avg1')));
        }

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

 
Hi All,

I am new in apex coding, I am trying to write trigger and this is my code.

My requirement is whenever I am creating new visitor record in the system( when I select multiselect picklist value which is 'Feve' and 'Dry Cough') new patient record should create under patient record.

My code is working fine, but patient record creates with ID, not name.

When I select only 1 value from the mutli-select picklist, then patient record creates with name.
trigger VisitorChangedIntoPatient on Visitor__c (after insert) {

    List<Patient__c> pat = new List<Patient__c>();
    
    for(Visitor__c visitor : Trigger.New)
    {
         Patient__c p = new Patient__c();
        
        if(trigger.isInsert && Visitor.Covid_19_Symtomp__c=='Fever' && Visitor.Covid_19_Symtomp__c=='DryCough')
        {
            p.id=visitor.id;
            p.Name=visitor.Name+'SQC';
            p.IsInfected__c=TRUE;
        }
        pat.add(p);
       
    }
    
    insert pat;
    
    
}
global class AccountIdGeneration implements Database.Batchable<sObject>,Database.Stateful{
    global String query ;
    List<Account> accountList = new List<Account>();
    global AccountIdGeneration(){
        query = 'Select id, Name, website from account where website != null';
    }
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<account> scope){
        List<account> lstAccount = new List<account>(); 
        for(account acc : scope){
           lstAccount.add(acc);
            
        }
        accountList.addAll(lstAccount);
    }
    global void finish(Database.BatchableContext BC){
        String finalString = 'Generated Id, website, Account Id, Name \n';
        System.debug('--accountList Size---'+accountList.size());
        /*-------------------- Forming Excel String ---------------*/
        for(account acc : accountList){
            Blob cryptoKey = Blob.valueOf('abcdefghijklmnopqrstuvwxyzabcdef');
            // Converting website to blob
            Blob data = Blob.valueOf(acc.website);
            Blob encryptedData = Crypto.encryptWithManagedIV('AES256', cryptoKey, data);
            String encryptedDataStr = EncodingUtil.base64Encode(encryptedData); 
            String key = encryptedDataStr.replaceAll('[^a-zA-Z\\s]', '');
            String str = acc.website.SubStringBefore('.');
            String finalID = '';
            if(str.length() >= 4 ){ finalID = str.substring(0, 4).toUppercase()+key.substring(30, 32).toUppercase(); }
            else if(str.length() < 4 && str.length() == 3){ finalID = str.substring(0, 3).toUppercase() +key.substring(29, 32).toUppercase();} 
            else if (str.length() < 4 && str.length() == 2){ finalID = str.substring(0, 2).toUppercase()+key.substring(28, 32).toUppercase();} 
            else if (str.length() < 4 && str.length() == 1){ finalID = str.substring(0, 1).toUppercase()+key.substring(27, 32).toUppercase();} 
            String recordString = finalID+','+acc.website+','+ acc.id+','+acc.Name+'\n';
            finalString  =  finalString + recordString;    
            
        }
        System.debug('--finalString-'+finalString);
        /*-------------------- Forming Email ---------------*/
        
        Messaging.EmailFileAttachment attachmentFile = new Messaging.EmailFileAttachment();
        blob accountList = Blob.valueOf(finalString);
        string csvname= 'accListFile.csv';
        attachmentFile.setFileName(csvname);
        attachmentFile.setBody(accountList);
        Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
        String email1 = 'test@gmail.com';
        String[] toAddresses = new list<string> {email1};
            String subject ='Account Generated Id List';
        email.setSubject(subject);
        email.setToAddresses( toAddresses );
        email.setPlainTextBody('');
        email.setFileAttachments(new Messaging.EmailFileAttachment[]{attachmentFile});
        Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
}
We are using this code for generating a 6-bit id for an account. When executing, the Finish method is not sending any email. logs showing batch apex status as "Ending position out of Bounds: 32".

Note: I am processing more than 10k records.

Please help me with this. Thanks in advance.
 
Hi,
I have a custom object with two custom fields. 
Both fields are DateTime. They are: Actual_Stop_Time__c and
Actual_Start_Time__c

I want to populate another field with the time in minutes between these two fields. I have tried a text field and a number field with a formula. (Actual_Stop_Time__c - Actual_Start_Time__c)*24*60

I am receiving this error: Error: Field Actual_Stop_Time__c may not be used in this type of formula

What am I missing? Thanks!
 
I am 12-years into Salesforce BUT new to APEX coding and am writing a class to simply trigger an update on all records on Budget__c in order to fire some declarative workflow rules (if anyone has ideas on how to improve the class, please suggest).

The main probem is I am getting an Execute Anonymous Error Line 1 Column 1 Invalid Type: batchBudgetMonthlyUpdate. But this did work and not it doesn't. I don't think I changed anything but maybe I did. The only thing I can think of is I tested it, it worked, then I logged out of sandbox and into production. When I logged back into sandbox, is when it stopped working. I tried checking environment but cannot figure out if this is related or not.
 
// Batch Job for updating all Budget records on the 1st of each month
// 23 April 2020 by Tom Barber cloudconsulting, LLC
global class BudgetMonthlyUpdate implements Database.Batchable<sObject> {
    global String [] email = new String[] {'tbarber@cloudconsultingllc.com'};
   // Email address is used below to send batch job status messages
   
   // Start Method
   global Database.Querylocator start (Database.BatchableContext BC) {
      return Database.getQueryLocator('SELECT id FROM Budget__c');
      // Query to get all the Budget__c object record IDs from all the Budget__c records--no WHERE statement
   }
   
   // Execute method
   global void execute (Database.BatchableContext BC, List<Budget__c> scope) {
       for(Budget__c a : scope)
       {a.Id = a.Id;
       }
     
      if (scope != null && scope.size()>0) {
         // Check if List is empty or not
         Database.update(scope); System.debug('List Size'
            + scope.size());
         // Update the Budget records-doesn't change the value of any record. Basically is a trigger to update all
      }
}
 
   // Finish Method
   global void finish(Database.BatchableContext BC) {
      Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
      
      // The code below will fetch the job Id
      AsyncApexJob a = [Select a.TotalJobItems, a.Status, a.NumberOfErrors,
      a.JobType, a.JobItemsProcessed, a.ExtendedStatus, a.CreatedById,
      a.CompletedDate From AsyncApexJob a WHERE id = :BC.getJobId()];//get the job Id
      System.debug('$$$ Jobid is '+BC.getJobId());
       String APEXjobID = null;
       APEXjobID = +BC.getJobId();
          
      // the code below will send an email to User about the job status
      mail.setToAddresses(email);
      mail.setReplyTo('tbarber@cloudconsultingllc.com'); //Add your email address here
      mail.setSenderDisplayName('RLG Salesforce Apex Batch Processing');
      mail.setSubject('Monthly Budget Update Batch Processing: '+a.Status);
      mail.setPlainTextBody('Apex job ' + APEXjobID +' | Monthly Budget Update completed' + a.CompletedDate + 'with status: ' + a.ExtendedStatus
                            + '\n' + 'This job runs on the 1st of each month and updates all the Budget records on the object so the current month (and year) checkboxes are checked.'
                            + '\n' + a.TotalJobItems+ ' batches with '+a.NumberOfErrors+' failures.'
                            + '\n' + 'Job Items processed:' +a.JobItemsProcessed);
      Messaging.sendEmail(new Messaging.Singleemailmessage [] {mail});
   }
}
Thanks in advance for any help or advice.
 
I'm using a javascript button to create a partner user account.
I'm getting the below error when i click the button.
'Cannot read property 'success' of undefined.

{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")}
 if("{! Contact.Partner_User_Enabled__c}" == true )
{
alert( "Partner user already exists" );
}
else
{
var result = sforce.apex.execute("EnablePartnerPortal","createUser",{"partnerContact":'{!Contact.Id}'});
if(result[0].success == 'false')
{
alert("Account is not partner");
}
   
}
 window.location.href="/{!Contact.Id}";
Hi,
I am new to Web components and When ever i am trying to insert a record in Contact Object it was saving with only FirstName,Lastname,Physical Attributes but i am getting Input of all other fields  in Js but in debug Logs it was showing only data of FirstName,Lastname, not Physical Attributes in ApexClass why?? Can i Know the  reason Why??

.HTML:

<template>
    <lightning-card title="Insert Contact" icon-name="standard:contact">
            <div class="slds-p-around_x-small">
                <lightning-input label="FirstName" value={rec.FirstName} onchange={handleFirstNameChange}></lightning-input>
                <lightning-input label="LastName" value={rec.LastName} onchange={handleLastNameChange}></lightning-input>
                <lightning-input type="text" label="PhysicalAttributes" value={rec.PhysicalAttributes} onchange={handlePhysicalAttributesChange}></lightning-input><br/>
                <lightning-button label="Save" onclick={handleClick}></lightning-button>
            </div>
        </lightning-card>
</template>

Js File:

import { LightningElement,track } from 'lwc';
import createContact from '@salesforce/apex/insertContactApexWeb.saveContactRecord';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
import FIRSTNAME_FIELD from '@salesforce/schema/Contact.FirstName__c';
import LASTNAME_FIELD from '@salesforce/schema/Contact.LastName__c';
import PHYSICALATTRIBUTES_FIELD from '@salesforce/schema/Contact.Physical_Attributes__c';
export default class InsertContact extends LightningElement {
    @track firstname = FIRSTNAME_FIELD;
    @track lastname = LASTNAME_FIELD;
    @track physicalattributes = PHYSICALATTRIBUTES_FIELD;
    rec = {
        FirstName : this.firstname,
        LastName : this.lastname,
        PhysicalAttributes : this.physicalattributes
    }
    handleFirstNameChange(event) {
        this.rec.FirstName = event.target.value;
        window.console.log("FirstName", this.rec.FirstName);
    }
    
    handleLastNameChange(event) {
        this.rec.LastName = event.target.value;
        window.console.log("LastName", this.rec.LastName);
    }
    
    handlePhysicalAttributesChange(event) {
        this.rec.PhysicalAttributes = event.target.value;
        window.console.log("PhysicalAttributes", this.rec.PhysicalAttributes);
    }
    handleClick() {
        createContact({ con : this.rec })
            .then(result => {
                this.message = result;
                this.error = undefined;
                if(this.message !== undefined) {
                    this.rec.Name = '';
                    this.rec.Industry = '';
                    this.rec.Phone = '';
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Success',
                            message: 'Account created',
                            variant: 'success',
                        }),
                    );
                }
                
                window.console.log(JSON.stringify(result));
                window.console.log("result", this.message);
            })
            .catch(error => {
                this.message = undefined;
                this.error = error;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error',
                    }),
                );
                window.console.log("error", JSON.stringify(this.error));
            });
    }
    
}

Apex Class:

public with sharing class insertContactApexWeb {
   
    @AuraEnabled
    public static void saveContactRecord(Contact con){
        System.debug('acc--'+con);
        try{
            insert con;
        }
        catch(Exception ex) {
            throw new AuraHandledException(ex.getMessage());
        }
    }
}