• Abdul Khatri
  • PRO
  • 3033 Points
  • Member since 2015

  • Chatter
    Feed
  • 99
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 926
    Replies
We need to simulate running monthly scheduled batch apex jobs over multilple months/year to see mutiple records instances being recaluculed over time.

I can see that there are some comments from 2011 saying that this is not possible but just wanted to check in 2019? I am guessing not but just thought to ask.
Hello.
I can get user and public groups from public groups this SOQL,
but public groups add role, can not get add role.
How to get role from public groups?
[SELECT Id, DeveloperName, (SELECT UserOrGroupId FROM GroupMembers)
FROM Group WHERE DeveloperName IN :xxxxxx]
Have a picklist with 10 values, when it is picklist option 2 or 3, i want to check to see if a number field is not null.

NOT ( OR ( ISPICKVAL ( FieldName__c , "Option 2" ), ( ISPICKVAL ( FieldName__c , "Option 3" ) ) ) && NOT ( ISNULL ( NumberField__c ) = true ) )

It validates, but no matter what option 2 or 3 I pick, i can also put numbers in the number field and nothing seems to be stopping me from doing anything....
Hi,

When a Campaign Member is removed from a campaign, it updates the IsDeleted flag, but does anyone know if this also updates the Last Modified date on the Campaign Member?

Thanks,

Kam
I am having trouble with a valdiation formula that checks two sets of criteria.
Criteria 1 - Field A = Yes AND Field B's number field is greater than 0.
Criteria 2 - Field A = Yes AND Field B's number field is greater than 0 AND Field C = Yes AND Field D not equal to BLANK

The first and second criteria reference the same elements but should be independent of each other. My formula "seems" to workfor Criteria 2 but not 1.

AND( NOT(ISPICKVAL(Furniture_Delivered_Model_Setup__c, 'No')), Attachment_Added__c>0, OR( AND( NOT(ISPICKVAL(Virtual_Tour__c, 'No')), NOT(ISBLANK(Model_Promo_Virtual_Tour__c)), NOT(ISPICKVAL(Furniture_Delivered_Model_Setup__c, 'No')), Attachment_Added__c>0) ))

Any help is greatly appreciated
  • February 20, 2019
  • Like
  • 0
Hello - How can I return a lead list called 'returnedLead' from a class to a trigger. Any assistance would be greatly appreciated. 

Trigger:
if(Trigger.isUpdate){
                   //Passing Trigger.new and Trigger.old to LeadOwnerAssignment class
                    LeadOwnerAssignment.leadChanges(Trigger.new, Trigger.old);
}

Class: 
public class LeadOwnerAssignment {
    
    public static void leadChanges(List<Lead> newLead, List<Lead> oldLead){
        
        List<Lead> returnedLead = new List<Lead>();
        
        //Old Lead Map
        Map<String, String> mapOfOldAffinityType = new Map<String, String>();
        
        for(lead oldLds : oldLead) {
            mapOfOldAffinityType.put(oldLds.Affinity_Type__c, oldLds.LastNameStreetAndZipCode__c);
        }

        for(Lead ld : newLead) {
            if(ld.Affinity_Type__c != mapOfOldAffinityType.get(ld.Affinity_Type__c)){
                returnedLead.add(ld);     
            }
        }  
    }            
}

I have turned on "Associate a Contact with Multiple Accounts".  I use a visualforce page to display my accounts and I'm trying to figure out the name of the related list to use.  

I used AccountContactRoles but I'm not getting the right page layout or buttons as expected.  thanks!!! 
 

Fred

  • February 20, 2019
  • Like
  • 0
Apex Class
/*
Having the Utilities of the Askiiris Integration
*/
public without Sharing class Integration_Util {
    Public Static FINAL String DML_ERROR='Error Occured While Saving Record To database';
    /*
Method to log the integration trace in notes
*/
    Public Static void InsertNote(id parentId,string body,string title,boolean isPrivate,boolean ExceptionOccured){
        note resp = new note();
        resp.parentId = parentId; 
        resp.body =body; 
        resp.title = title; 
        resp.isPrivate = isPrivate; 
        database.insert(resp,false); 
    }
     /*
Method to send the Exception Email to CMSO-PS
*/
    public static void sendExceptionEmail(String[] emailId,String subject,String emailBody){
        Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
        semail.setToAddresses(emailId); 
        semail.setSubject(subject); 
        semail.setHtmlBody(emailBody); 
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {semail}); 
    } 
    /*
Method to get the Integration Credentials
*/
    Public Static CredentialsWrapper getCredetials( String credentialDevName){
        Integration_Credentials_Mapping__mdt mdt=[select id,Production_End_point_URI__c,Sanbox_End_point_URI__c,
                                                  Sandbox_password__c,Sandbox_user_name__c,Production_password__c,
                                                  Production_user_name__c,security_hns__c,Suffix_URL_1__c,Suffix_URL_2__c,
                                                  Sandbox_Auth_URI__c,Production_Auth_URI__c
                                                  From Integration_Credentials_Mapping__mdt 
                                                  where DeveloperName=:credentialDevName LIMIT 100];
        
        boolean isSandbox=[SELECT issandbox from organization LIMIT 1].isSandbox;
        CredentialsWrapper credwrap=new CredentialsWrapper();
        if(isSandbox){
            credwrap.enpointUrl=mdt.Sanbox_End_point_URI__c;
            credwrap.username =mdt.Sandbox_user_name__c;
            credwrap.password =mdt.Sandbox_password__c;
            credwrap.authTokenUrl =mdt.Sandbox_Auth_URI__c; 
        }else{
            credwrap.enpointUrl=mdt.Production_End_point_URI__c;
            credwrap.username=mdt.Production_user_name__c;
            credwrap.password=mdt.Production_password__c;
            credwrap.authTokenUrl =mdt.Production_Auth_URI__c; 
        }
        credwrap.hnsUrl=mdt.security_hns__c;
        credwrap.isSandbox=isSandbox;
        credwrap.suffixUrl1=mdt.Suffix_URL_1__c;
        credwrap.suffixUrl2=mdt.Suffix_URL_2__c;
        
        return credwrap;
    } 
    /*
Wrapper class used wrap the Integration Credentials
*/
    Public without sharing class CredentialsWrapper{
        Public String username;
        Public String password;
        Public String enpointUrl;
        Public String hnsUrl;
        public Boolean isSandbox;
        Public String suffixUrl1;
        public String suffixUrl2;
        Public String authTokenUrl;
        
    }
    
}

My Test Class

@isTest
public class Integration_Util_UT {

    private static testmethod void InsertNote() {
    Integration_Util.InsertNote('00300000003T2PGAA0','hello','hello',True,True);
     }                    
                    
    private static testmethod void sendExceptionEmail() {
        Integration_Util.sendExceptionEmail('fdgd@df.com','hello','hello');
       }                
                    
    private static testmethod void getCredetials() {
        Integration_Util.getCredetials('hello');
        }                    
}                

My error : "Method does not exist or incorrect signature: void sendExceptionEmail(String, String, String) from the type Integration_Util"
Also the current code coverage is 31%, please hep me to get code coverage 
Thanks in advance
I seem to be stuck on this trailhead module or write negative tests unit, while I have 93 percent code coverage, I can't seem to get the code coverage to hit 100 percent at the "returnValue" piece doesn't seem to hit.
My code is as follows.

Calculator Class
 
public class Calculator {
 public class CalculatorException extends Exception{}

  public static Integer addition(Integer a, Integer b){
   return a + b;
    }

   public static Integer subtraction(Integer a, Integer b){
    return a - b;
    }

 public static Integer multiply(Integer a, Integer b){
  if(b==0 || a==0){
  throw new CalculatorException('It doesn\'t make sense to multiply by 
   zero');
  }
  return a * b;
  }

 public static Decimal divide(Integer numerator, Integer denominator){
  if(denominator == 0){
  throw new CalculatorException('you still can\'t divide by zero');
   }
 Decimal returnValue = numerator / denominator;
  if(returnValue < 0){
    throw new CalculatorException('Division returned a negative value.' + 
 returnValue);
 }
   return returnValue;
  }


 }

And my test class as follows
 
@isTest
   public class Calculator_Tests {

@isTest
 public static void addition() {
    Calculator.addition(1, 0);
   }
@isTest
  public static void subtraction() {
    Calculator.subtraction(1, 0);
   }

@isTest
 public static void divide_throws_exception_for_division_by_zero() {
 Boolean caught = false;
 try {
    Calculator.divide(1, 0);
  } catch (Calculator.CalculatorException e) {
    System.assertEquals('you still can\'t divide by zero', e.getMessage(), 
  'caught the right exception');
    caught = true;
   }
   System.assert(caught, 'threw expected exception');
   }

  @isTest
 public static void divide_throws_exception_for_division_by_two() {
 Boolean caught = true;
 try {
    Calculator.divide(1, 2);
 } catch (Calculator.CalculatorException e) {
    System.assertEquals('you still can\'t divide by zero', e.getMessage(), 
  'caught the right exception');
    caught = true;
   }
   System.assert(caught, 'threw expected exception');
 }


@isTest
public static void multiply_by_one() {
  Boolean caught = false;
  try {
    Calculator.multiply(1, 0);
    } catch (Calculator.CalculatorException e) {
    System.assertEquals('It doesn\'t make sense to multiply by zero', 
    e.getMessage(), 'caught the right exception');
     caught = true;
    }
    System.assert(caught, 'threw expected exception');
  }

@isTest
 public static void multiply_by_two() {
  Boolean caught = true;
  try {
     Calculator.multiply(1, 2);
   } catch (Calculator.CalculatorException e) {
    System.assertEquals('It doesn\'t make sense to multiply by zero', 
  e.getMessage(), 'caught the right exception');
    caught = true;
   }
   System.assert(caught, 'threw expected exception');
}   
}

 
Hello All,
I am very new to writing code and am having a hard time getting assignment rules to fire once a lead is entered into a visualforce page. I ahve found a few examples out there where folks suggest DML code, however I am not sure if I can put on the Visual Force page or if I should create a seperate class (or if I should create a trigger to fire after the lead is created). Salesfroce suggested I create a class and gave me the following code:
public Lead sample {get; set;}
    public AssignLeadsUsingAssignmentRules(ApexPages.StandardController controller) 
               {
        sample = new Lead();        
    }
   public void LeadAssign()     {             
        Database.DMLOptions dmo = new Database.DMLOptions();             
        dmo.assignmentRuleHeader.assignmentRuleId= '01Q0m0000006EH9';                     
        sample.setOptions(dmo); 
        insert sample; 
    } 
Below is my Visual Force page:
<apex:page standardController="Lead" showHeader="false" sidebar="true" extensions="AssignLeadsUsingAssignmentRules">
<apex:form >
     <apex:pageBlock title="Lead Information">
       <apex:pageBlockSection >
           <apex:pageBlockSection >
           <apex:inputField value="{!Lead.Lead_Referred_By__c}" required="True"/> 
           <apex:inputField value="{!Lead.Club2__c}" required="True"/>
           <apex:inputField value="{!Lead.company}" required="True"/>
           <apex:inputField value="{!Lead.NumberOfEmployees}" required="True"/>
           <apex:inputField value="{!Lead.FirstName}" required="True"/>
           <apex:inputField value="{!Lead.LastName}" required="True"/>
           <apex:inputField value="{!Lead.Phone}" required="True"/>
           <apex:inputField value="{!Lead.Email}" required="False"/>
           <apex:inputField value="{!Lead.Title}" required="True"/>
           <apex:inputField value="{!Lead.Additional_Comments__c}"/>
           </apex:pageBlockSection>
       </apex:pageBlockSection>  
            <apex:pageBlockButtons >
            <apex:commandButton action="{!save}" value="Save"/>
                </apex:pageBlockButtons>
</apex:pageBlock>
 </apex:form>
</apex:page>

My issue is that the CLub2__c field is used to dirive a Territory filed on the lead, the assignemnt rules fires off of the Territory field. Any code, tips , suggestions, prayers are greatly appreciated.
I have three for loops in my controller and when I run the test, I get code coverage everywhere except inside of the three for loops. Can someone point me in the right direction?
 
public with sharing class applyPayments_Controller {
    public List<InvoiceWrapper> searched_invoices {get;set;}
    public List<gii__OrderInvoice__c> selectedInvoices {get;set;}
    public string accountName {get;set;}
    public boolean viewTable;
    public date paymentDate {get;set;}
    public string paymentMethod {get;set;}
    public string reference {get;set;}
    public decimal amount {get;set;}
    public string comments {get;set;}
    
    public Boolean getViewTable()
    {
        return this.viewTable;
    }
    
    public applyPayments_Controller()
    {
        viewTable=false;
        searched_invoices = new List<InvoiceWrapper>();
    }
    
    public void searchInvoices()
    {   
        string likeAccountName = '%' + accountName + '%';
        searched_invoices.clear();
        for(gii__OrderInvoice__c i: [select Id, Name, Total_Invoice__c, gii__BalanceAmount__c, Past_Due__c, Account_Name__c, gii__Status__c from gii__OrderInvoice__c 
                                     where (Account_Name__c LIKE :likeAccountName AND gii__Status__c != 'Cancelled' AND Past_Due__c != 'PAID')
                                     order by Account_name__c, Name])
        {
            searched_invoices.add(new InvoiceWrapper(i));
        }
        
        viewTable = true;
    }
    
    public PageReference Next()
    {
        selectedInvoices = new List<gii__OrderInvoice__c>();
        selectedInvoices.clear();
        for (InvoiceWrapper wrapInvoiceObj : searched_invoices)
        {
            if(wrapInvoiceObj.selected == true)
            {
                selectedInvoices.add(wrapInvoiceObj.inv);
            }
        }
        
        paymentDate = System.Today();
        PageReference applyPaymentsVF_2 = new PageReference('/apex/applyPaymentsVF_2');
        return applyPaymentsVF_2;
    }
    
    public void applyPayment()
    {
        for(gii__OrderInvoice__c inv : selectedInvoices)
        {
            gii__ARInvoicePayment__c payment = new gii__ARInvoicePayment__c();
            payment.gii__Invoice__c = inv.id;
            payment.gii__Reference__c = reference;
            payment.gii__Comments__c = comments;
            payment.gii__PaymentMethod__c = paymentMethod;
            payment.gii__PaymentDate__c = paymentDate;
            payment.gii__PaidAmount__c = inv.gii__BalanceAmount__c;
            insert payment;
        }    
    }
    
    //This is wrapper/container class
    public class InvoiceWrapper
    {
        public String accName {get;set;}
        public String invName {get;set;}
        public decimal total {get;set;}
        public decimal balance {get;set;}
        public String status {get;set;}
        public gii__OrderInvoice__c inv {get;set;}
        public Boolean selected {get;set;}
        public InvoiceWrapper(gii__OrderInvoice__c i)
        {
            inv = i;
            selected = false;
            accName = i.Account_Name__c;
            invName = i.Name;
            total = i.Total_Invoice__c;
            balance = i.gii__BalanceAmount__c;
            status = i.Past_Due__c;
        }
    } 
}
 
@isTest
public class applyPayments_ControllerTest {
    public static testMethod void testMyController()
    {  
        gii__SalesOrder__c so = new gii__SalesOrder__c();
        Id RecordTypeIdSO = Schema.SObjectType.gii__SalesOrder__c.getRecordTypeInfosByName().get('Service Call Order').getRecordTypeId();
        so.RecordTypeId = RecordTypeIdSO;
        so.gii__OrderType__c = 'Standard';
        insert so;
        
        gii__OrderInvoice__c inv = new gii__OrderInvoice__c();
        inv.gii__SalesOrder__c = so.Id;
        insert inv;
        
        applyPayments_Controller controller = new applyPayments_Controller();
        applyPayments_Controller.InvoiceWrapper wrp = new applyPayments_Controller.InvoiceWrapper(inv);
        controller.searchInvoices();
        controller.getViewTable();
        controller.Next();
        controller.applyPayment();
    }
}

 
Hello,
I have an Apex Trigger that I needs to perform the following:
  • prevent duplicate lead from being inserted during an import
  • add task to existing Lead that was found within SF
The trigger belows does meet my requiremtns except that it also adds a task to the newly inserted Lead.  The Newly inserted Lead does not exsit in Salesforce so I am not sure why a task is being added.
trigger LeadPreventDuplicate on Lead (after insert,after update) {

    Map<String, Lead> leadMap = new Map<String, Lead>();

      for (Lead lead : System.Trigger.new) 
      { 

       if ((lead.Email != null) && (System.Trigger.isInsert ||
            (lead.Email != System.Trigger.oldMap.get(lead.Id).Email))) 
            {
              leadMap.put(lead.Email, lead);
            }
      }

      List<task> addtask=New List<task>();
     
      for (Lead lead : [SELECT Email FROM Lead WHERE Email IN :leadMap.KeySet()]) 
      {
        Lead newLead = leadMap.get(lead.Email);
        addtask.add(new Task(
        WhoID =lead.id, 
        Status = 'Active',
        Subject = 'Test Task',
        ActivityDate = system.today()));
      
       } 
       insert addtask; 
      
       Lead[] dupes = new Lead[0];
          Set<String> email = new Set<String>(), dupEmail = new Set<String>();
              for(Lead record: Trigger.new)
              email.add(record.email);
              email.remove(null);
              for(Lead record: [SELECT Id, Email FROM Lead WHERE Email IN :email])
                    if(!Trigger.newMap.containsKey(record.id))
                    dupEmail.add(record.Email);
              for(Lead record: Trigger.new)
        if(dupEmail.contains(record.Email))
            dupes.add(record.clone(true));
        else
            dupEmail.add(record.Email);
    delete dupes;
}

Thanks for the assistance.
M
 
I'm trying to pull a few fields into an IF formula and I'm not receiving a syntax error but the formula isn't calculating.  What am I missing?

Monthly Revenue at End of Contract
IF(((Contract_Term_Yrs__c * 12) < Months_to_sign_existing_clients__c),((Contract_Term_Yrs__c * 12) * New_Monthly_Revenue_Existing__c),(Months_to_sign_existing_clients__c * New_Monthly_Revenue_Existing__c))
Contract_Term_Yrs__c =  Number Field
Months_to_sign_existing_clients__c = Formula Field(Number)
New_Monthly_Revenue_Existing__c = Formula Field(Currency) 



 
the trigger should be on account to check the assets and if ALL Assets where product family = "bla bla "  and their status was "Canceled" the trigger should update bla bla Account stage (API Name = Account_Status__c )  to "Cancel".
Hello
I have requirement to calculate today hours for the current week. 
We have custom object Tracker__C and field Hours__C. Hours__C is user entered field. Next to the user entered field we wanted to show the users total hours he has entered thus far this week. 
For example  (Day of the week - Hours entered - Total hours this week)
Monday - 4 - 4
Tuesday - 6 - 10
Wednesday - 2 - 12
Thursday - 8 - 20
Friday - 8 - 28

All help appreciated
Thanks
Dinesh
  • January 14, 2019
  • Like
  • 0
trigger populate on project__c (before insert , before update){
 
    
    
     MAP<ID , user> mapCon = new MAP<ID , user>([Select id ,name,city
                                                 from user 
]);
     for(project__c  obj : trigger.new)
       {
        if(obj.delivery_location__c == null)
          {
           user u  = mapcon.get(obj.ownerid);
              if (u.city != null)
              
             obj.Delivery_location__c=u.city;
              else {
                   obj.Delivery_location__c = 'NA';
              }
          }
       
       }
       
       }
When I run this 

List<ObjectPermissions> objPermList = new List<ObjectPermissions>();
List<FieldPermissions> fieldPermList = new List<FieldPermissions>();
//get the object permisisons for a given profile – source
List<ObjectPermissions> objPermissionList = [SELECT Id, SobjectType, PermissionsCreate, PermissionsRead, PermissionsEdit, PermissionsDelete,
PermissionsModifyAllRecords,PermissionsViewAllRecords FROM ObjectPermissions
where ParentId in (select id from PermissionSet where profile.name = ‘System Administrator’)];
//get the field permissions for a given profile – source
List<FieldPermissions> fldPermissionList = [SELECT Id, ParentId, SobjectType, Field, PermissionsEdit, PermissionsRead FROM FieldPermissions
where ParentId in(select id from PermissionSet where profile.name = ‘System Administrator’)];
//destination permisison set
List<PermissionSet> permissionSetList = [select id from PermissionSet where name = ‘System_Administrator’];
PermissionSet permissionSet = permissionSetList.get(0);
//set object permissions
for(ObjectPermissions oP : objPermissionList)
{
ObjectPermissions objPerm = new ObjectPermissions();
objPerm.ParentId = permissionSet.id;
objPerm.SobjectType = oP.SobjectType;
objPerm.PermissionsCreate = true;
objPerm.PermissionsDelete = true;
objPerm.PermissionsEdit = true;
objPerm.PermissionsModifyAllRecords = true;
objPerm.PermissionsRead = true;
objPerm.PermissionsViewAllRecords = true;
objPermList.add(objPerm);
}
Database.upsert(objPermList, false);
//set field permissions
for(FieldPermissions fp : fldPermissionList)
{
FieldPermissions fldPerm = new FieldPermissions();
fldPerm.ParentId = permissionSet.id;
fldPerm.SobjectType = fp.SobjectType;
fldPerm.Field = fp.Field;
fldPerm.PermissionsEdit = true;
fldPerm.PermissionsRead = true;
fieldPermList.add(fldPerm);
}
Database.upsert(fieldPermList, false);

I get the following error message
Line: 7, Column: 70
Invalid identifier '‘System'. Apex identifiers must start with an ASCII letter (a-z or A-Z) followed by any number of ASCII letters (a-z or A-Z), digits (0 - 9), '$', '_'.

What could be wrong in this 
Hi ,
I have created a trigger on Task that updates last activity date whenever a task is created on a Lead / contact / Opp. 

The trigger works fine when I create a single task or recurrence when the recurrence date is only for one day(Recurrence Start & Recurrence End are on same day). But when the recurrence is created for two or more days (Recurrence Start & Recurrence End are on different days Ex: Start = 01/01/2019 & End=01/02/2019) then it is throwing an error.  

Here is the error message

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger UpdateLastActivityDate caused an unexpected exception, contact your administrator: UpdateLastActivityDate: execution of AfterInsert caused by: System.ListException: Duplicate id in list: 003c000001G7hkTAAR: Trigger.UpdateLastActivityDate: line 37, column 1

Here is the Trigger Code along with lines mentioned error in bold
trigger UpdateLastActivityDate on Task (after insert) {

    //updating Last_sales_activity__c on lead, contact and opportunity for new activities
    
     if( trigger.isAfter && trigger.isInsert  )
    {
        List<Contact> lstContactsToUpdate=new List<contact>();
        List<Lead> lstLeadsToUpdate=new List<Lead>();
        List<Opportunity> lstOpportunitiesToUpdate=new List<Opportunity>();
        
        Profile p = [ Select Id, Name from Profile where Id =: UserInfo.getProfileId() ];
        if( p.Name.equalsIgnoreCase( 'Standard Sales User' ) )
        {    
            for( Task t : trigger.new )
        {    system.debug('t whatId..'+t.WhatId);
             system.debug('t whoId..'+t.WhoId);
              if( t.WhoId != null && String.valueOf( t.WhoId ).startsWith( '003' ))//003 =contact
                {
                    contact c=new contact(Id=t.WhoId);
                    c.Last_sales_activity__c=system.today();
                    lstContactsToUpdate.add(c);
                }else if( t.WhatId != null && String.valueOf( t.WhatId ).startsWith( '006' ))//006 =opportunity
                {system.debug('t----006---');
                    Opportunity c=new Opportunity(Id=t.WhatId);
                    c.Last_sales_activity__c=system.today();
                    lstOpportunitiesToUpdate.add(c);
                }else if( t.WhoId != null && String.valueOf( t.WhoId ).startsWith( '00Q' ))//00Q =Lead
                {
                    Lead c=new Lead(Id=t.WhoId);
                    c.Last_sales_activity__c=system.today();
                    lstLeadsToUpdate.add(c); 
                }
            
            
        }
            if(lstContactsToUpdate.size()>0){
                update lstContactsToUpdate;
            }
            if(lstOpportunitiesToUpdate.size()>0){
                update lstOpportunitiesToUpdate;
            }
            if(lstLeadsToUpdate.size()>0){
                update lstLeadsToUpdate;
            }
            
        }
        
   }

 }

I could not figure what I am missing here.

Let me know what changes I need to do to overcome this error.

Thanks
Rao
  • January 10, 2019
  • Like
  • 0

Hello,
I'm an admin that has just written my first integration. The code makes a call to an external service, receives some json, and then parses it and places it into a custom object. The json could either contain new records or update an existing record from a previous run...this is being done with upsert dml statement.  This process runs on a schedule. 

My question is regarding testing. There are no problems with testing the insert of new records. There is a test method that sets up all of the needed test data and a json string that makes use of that test data. The method returns that string and is used as a mockHTTPResponse. This tests everything except for the branch of code that updates existing records. This is where I'm challenged...I don't see how I can make another json string that uses first set of test data. 

So, I'm hoping that someone out there has been through this before and can offers some suggestions. 

Hello friends, I want to add Multiple email address for sending the email in To: input box, but it doesnot accept more than one. Do anyone know how to solve this.
Please find the code below

public class sendemailtestcontroller {

    public sendemailtestcontroller() {

    }





    public String toEmail {get;set;}
    public String subject {get;set;}
    public String body {get;set;}
    
    
    private final Lead MyLead;
    public sendemailtestcontroller(ApexPages.StandardController controller)
    
   
    {
        this.MyLead=(Lead)controller.getRecord();
    } 
   
             
    public void sendEmail() {
        
        //create a mail object to send email 
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        
        String[] toaddress = (new String[]{toEmail});
        
        //email properties
        mail.setToAddresses(toaddress);
        mail.setSubject(subject);
        mail.setUseSignature(true);
        mail.setPlainTextBody(body); 
               
        // send the email
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
     }   
   

}

Vf :
<apex:page standardcontroller="Lead" extensions="sendemailtestcontroller">
  <apex:pageBlock title="EMAIL TEST">
        <apex:form >
        <br />
            <apex:outputLabel value="To" for="To"/>:<br/>
            <apex:inputText value="{!toEmail}" id="email"/><br/><br/>
                        
            <apex:outputLabel value="Subject" for="Subject"/>:<br />     
            <apex:inputTextarea value="{!subject}" id="Subject" cols="80" /><br/><br/>
                        
            <apex:outputLabel value="Body" for="Body"/>:<br />     
            <apex:inputTextarea value="{!body}" id="Body" rows="10" cols="80"/><br/><br/>      
            <br /><br />
                        
            <apex:commandButton value="Send Email" action="{!sendEmail}"  />
            <apex:commandButton value="Cancel" action="{!cancel}"/> 
        
        </apex:form>
    </apex:pageBlock>
</apex:page>

User-added image
Hi,

I am looking to see the best approach for Salesforce CI. I have gone through many forum and blogs but haven't been able to grasp them. I tried to setup CI for the entire org but facing a lot of challeges which I guess you guys quite aware of.

What I am looking to do incremental deployment based on the git diff, dynamically generate package.xml based on the metadata committed which I think would be manageable something like sfdc-git-package https://www.npmjs.com/package/sfdc-git-package. I am having a hard time implementing this.

Please someone help
Can someone help me to show how I can change the Sales Console Lightning Layout. Currently it is showing as shown in the screen shot below as 3 Column layout. I wanted to change the layout to show the highlight panel on top. I am finding no help from Salesforce help section or trailhead for this. Please bear in mind I am talking about Lightning Sales Console and not Classic. I did the Edit Page and takes me but doesn't allow me to change the layout. 

User-added image
Is there a way to hide "Save & New" Button from the Task page Layout?

User-added image

I looked at everywhere and couldn't find the solution. I do want to give them Create/Edit Permission so no option there to remove that.

Please help
Custom URL for the cast creating inline headers and side bar. I tried the following addition things

            urlConcat += '&inline=0';
            urlConcat += '&isdtp=lt';
            urlConcat += '&isdtp=nv';
            urlConcat += '&isdtp=vw';

the only one that work is '&isdtp=nv' but after saving the activity, the hyperlink in the related list doesn't work. I have attached a screen shot 

User-added image

Anyone can help?

 
Hi,

I am looking to see the best approach for Salesforce CI. I have gone through many forum and blogs but haven't been able to grasp them. I tried to setup CI for the entire org but facing a lot of challeges which I guess you guys quite aware of.

What I am looking to do incremental deployment based on the git diff, dynamically generate package.xml based on the metadata committed which I think would be manageable something like sfdc-git-package https://www.npmjs.com/package/sfdc-git-package. I am having a hard time implementing this.

Please someone help
We need to simulate running monthly scheduled batch apex jobs over multilple months/year to see mutiple records instances being recaluculed over time.

I can see that there are some comments from 2011 saying that this is not possible but just wanted to check in 2019? I am guessing not but just thought to ask.
I am having two issues with the Calendar functionality in Lightning.

First, when accessing the Calendar page itself, even using a system admin account I get an error that states: "You don't have access to this record. Ask your administrator for help or to request access." I see this was reported as a bug that was fixed in Winter 19, (see here (https://success.salesforce.com/issues_view?id=a1p3A000000JX6QQAW&title=you-don-t-have-access-to-this-record-ask-your-administrator-for-help-or-to-request-access-appears-when-searching-after-accessing-calendar)) but we're on Winter 19 and it's still occurring.

Second, when I try to add a public calendar in Lightning, I get an error stating: "You no longer have access to fields or filters defined in this calendar. Either your Salesforce admin changed your field access, or a Salesforce user removed your filter." This seems to occur on any public calendar we add. We're able to view these public calendars just fine in classic mode so it's not clear why this error is occurring.

Any ideas on how we can fix this? Thanks much!
I want to be able to direct the user to a visualforce form before closing an Opportunity. Upon completing this form, I want the opp to complete its closing.
 
I'm relatively new to salesforce and salesforce development, but one alternative I considered is a validation rule that requires them to submit my form (and add a related custom object) before they are able to close the opp. This left me to add the form as part of a page layout or as a custom quick action. However, this is not ideal because I want the flow to be seamless for closing the opp. I want the form to be part of closing.

Is there a way to accomplish this?
I have successfully been able to add an emailMessage to SF via the API.  I will need to do one of the two options:
  1. Not have SF send the email to the recipient once added.  This is because we have already sent the email and just placing a copy in SF for our records
  2. Have the ability to change the fromAddress via the API.  If we remove the email sent from our website and only have the SF one to be sent, we will need to change the from email address.  I have added the email to the Organization-Wide Email addresses and associated it to the correct profile, however, I don't know where to switch it.
 
SingleEmailMessage emailMessage = new SingleEmailMessage();
            if (!string.IsNullOrEmpty(templateid))
            {
                emailMessage.templateId = templateid;
            }
            else
            {
                emailMessage.subject = subject;
                emailMessage.htmlBody = Server.UrlDecode(body) ;
            }

            emailMessage.toAddresses = new String[] { email };
            emailMessage.saveAsActivity = true;
            emailMessage.targetObjectId = contactId;

            SingleEmailMessage[] messages = { emailMessage };
            SendEmailResult[] results = binding.sendEmail(messages);

            if (results[0].success)
            {
                // Console.WriteLine("The email was sent successfully.");
            }
            else
            {
                SendEmail("xxxxxx@xxx.com", "Error SingleEmailMessage add", "The email failed to send: " + results[0].errors[0].message);

            }


            sflogout();

 
I would like to create an If-Then rule where if the account owner = x then the account representative(custom field) equals x. If account representative equals x, then account manager equals a, b, or c
Hello.
I can get user and public groups from public groups this SOQL,
but public groups add role, can not get add role.
How to get role from public groups?
[SELECT Id, DeveloperName, (SELECT UserOrGroupId FROM GroupMembers)
FROM Group WHERE DeveloperName IN :xxxxxx]
Have a picklist with 10 values, when it is picklist option 2 or 3, i want to check to see if a number field is not null.

NOT ( OR ( ISPICKVAL ( FieldName__c , "Option 2" ), ( ISPICKVAL ( FieldName__c , "Option 3" ) ) ) && NOT ( ISNULL ( NumberField__c ) = true ) )

It validates, but no matter what option 2 or 3 I pick, i can also put numbers in the number field and nothing seems to be stopping me from doing anything....
Hi ,

This is my test class for insert a record

Parent Object :Album__c
Child object :Track__c(which has loopup relation with Album__C)

I have written the class and the test class for inserting a record in the child object...but both are giving me error....

In main program
----------------------

public class instrack 
{
track__c al = new track__c(); 
public track__c merch(String name,string name1)  
{
al.Name=name;                             
al.Album__c=name1;
insert al;                 
system.debug('the inserted record is:'+name);
return al;
}
}

Executed as :

instrack mc=new instrack();
mc.merch('Container','GullyBoy');

Error as: Method does not exist  or incorrect signature :void merch(string) from the type instrack....

Test class
-------------
@istest
public class instracktest
{
static testmethod void testmerch()
{
track__c al = new track__c(Name='Surgical'); 
 insert al;   
 Test.startTest();
         al = new track__c (Name = 'Surgical',Album__c='GullyBoy');
         Database.SaveResult result = Database.insert(al, false);
         System.assert(result.getErrors()[0].getMessage().contains('Track already exist with this'));
        Test.stopTest();              

}
}

Error as : System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Album__c]: [Album__c]

Kindly help out on the issue..Thanks in advance...

I hate having giant IF blocks as much as the next person but I am running into an issue here where they are causing time outs and I am looking to find a way to condense this brick of statments into something more eligant.

What I am doing here is when a new Case is created it spawns items called Compliance__c, these pull in information from a lot of different places to assemble, i need to compare an identical list of checkboxs on two seperate items and if there is a pair up of TRUE TRUE then change the status on the Compliance__c.

I only need this to be done on creation of the record, but creating a case makes about 600 Compliance__c records so running to much code for them on creation times out easily.

Here is the curent brick of statments

IF((Regulation_Library__r.Infant__c ==true && Provider_Case__r.Account__r.Infant__c ==true)||
(Regulation_Library__r.Staff__c ==true && Provider_Case__r.Account__r.Staff__c ==true)||
(Regulation_Library__r.Screen_Time__c ==true && Provider_Case__r.Account__r.Screen_Time__c ==true)||
(Regulation_Library__r.Private_Well__c ==true && Provider_Case__r.Account__r.Private_Well__c ==true)||
(Regulation_Library__r.Overnight_Care__c ==true && Provider_Case__r.Account__r.Overnight_Care__c ==true)||
(Regulation_Library__r.Off_Site_Laundry__c ==true && Provider_Case__r.Account__r.Off_Site_Laundry__c ==true)||
(Regulation_Library__r.Diapering__c ==true && Provider_Case__r.Account__r.Diapering__c ==true)||
(Regulation_Library__r.Bottle_Feed__c ==true && Provider_Case__r.Account__r.Bottle_Feed__c ==true)||
(Regulation_Library__r.Infant_Only__c==true && Provider_Case__r.Account__r.Infant_Only__c==true)||
(Regulation_Library__r.Gardens__c==true && Provider_Case__r.Account__r.Gardens__c==true)||
(Regulation_Library__r.Outdoor_Playspace__c==true && Provider_Case__r.Account__r.Outdoor_Playspace__c==true)||
(Regulation_Library__r.Infant_&&_Toddler__c==true && Provider_Case__r.Account__r.Infant_&&_Toddler__c==true)||
(Regulation_Library__r.Pets__c==true && Provider_Case__r.Account__r.Pets__c==true)||
(Regulation_Library__r.H&&made_Equipment__c==true && Provider_Case__r.Account__r.H&&made_Equipment__c==true)||
(Regulation_Library__r.Swimming_Pool__c==true && Provider_Case__r.Account__r.Swimming_Pool__c==true)||
(Regulation_Library__r.Septic__c==true && Provider_Case__r.Account__r.Septic__c==true)||
(Regulation_Library__r.Meals_Not_Provided_by_Provider__c==true && Provider_Case__r.Account__r.Meals_Not_Provided_by_Provider__c==true)||
(Regulation_Library__r.Food_Allergies__c==true && Provider_Case__r.Account__r.Food_Allergies__c==true)||
(Regulation_Library__r.Water_Activities__c==true && Provider_Case__r.Account__r.Water_Activities__c==true)||
(Regulation_Library__r.Special_Need_Services__c==true && Provider_Case__r.Account__r.Special_Need_Services__c==true)||
(Regulation_Library__r.Mixed_Age_Groups__c==true && Provider_Case__r.Account__r.Mixed_Age_Groups__c==true)||
(Regulation_Library__r.Transportation__c==true && Provider_Case__r.Account__r.Transportation__c==true), Compliance_Status__c = "Not Applicable",)
Hello Team,

While doing the trailhead for Quick Start - Apex Coding for Admins - Create a Trigger, while I am creating the candidate Nina Simone, and update the ZIP Code field as "20008", system gives me an error message stating as - Candidate Zip Code does not exist in specified State.

Kindly advise where I am going incorrect.

Thanks
Vinay Kumar Salve

Hi awesome developers!

I need to "classify" an incoming Record A based on several related fields on records B,C,D,.. etc. Therefore I need a trigger that is triggering (:D) on this new record and check more then 5 lookup relationships for the content of specific fields in the related records B,C,D ...
Following https://developer.salesforce.com/page/Apex_Code_Best_Practices #2 I should not put the query for the related records in the foreach loop on record "A" Also I need to bulkify this, so it could handle the max load of 200 records entering the trigger at once.
What would be the most efficient way to query those related records for each incoming record and classify "A" according to the values in the related records?

 

If you could help me out here or point me in the right direction that would be really great!

Thanks,

Markus

  • February 24, 2019
  • Like
  • 0