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

  • Chatter
    Feed
  • 106
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 1000
    Replies
Hi!

I have the query below in the controller of one of my visualforce pages:
 
SELECT Id, Name, Title, Company, Country, CreatedDate, Status FROM Lead WHERE Status='New' AND OwnerId= :UserInfo.getUserID() ORDER BY CreatedDate DESC

What I would like to do some kind of outer join to check if the Lead.Company field exists as a Account.Name so I can show this on the Visualforce page.

Any ideas on how to do this?
I'm attempting to create a note for an opportunity via the REST API.  I'm finding several examples for the SOAP API, but nothing that works using REST.  Using this API I am able to create a note, but can find no way to associate it with an opportunity ID:

https://developer.salesforce.com/docs/api-explorer/sobject/Note

Any help would be greatly appreciated.

Hi Guys,

I am triggering a POST request via process builder and it works but can you please tell me how can I capture the HTTP response I get back? The external system will send me a string I would like to store on the record which started the process. 
 

@future(callout=true)

        public static void calloutmethod(String name){
                Http http = new Http();
                HttpRequest request = new HttpRequest();
                request.setEndpoint('XXX');
                request.setMethod('POST');
                request.setHeader('Content-Type', 'application/json;charset=UTF-8');
                request.setHeader('accept', 'application/json');
                request.setBody(name);
                
                response = http.send(request);
        }

Thanks a lot.

Krisz
Hi,

I am having a massive confusion,

We have a database of 400,000 records.. which calls for duplication.

I want to check if alternate phone number of any of the account matches with the Primary phone number of any of the account, If it does, there is a checkbox  called "Marked For deletion"  m that checkbox should get selected and primary phone number of that account should become the alternate phone number of the acount against which it has matched 

So lets say ,

Accoount : A  Primary No : 1234  Secondary No : 5678

Accoount : B  Primary No : 9241  Secondary No : 1234 

Accoount : C  Primary No : 9241  Secondary No :  1234

Account B and Account C should have marked for deletion checked.
and Account B's primary phone number should become Secondary phone number of Account A. 

Please help me in achieving this 
 
I need to update the Account Name (Account_Name__c) custom field in the Task tab, with the Account Name (AccountId). My current code is:

trigger Account_Name on Task (before insert, before update) {
    for(Task a : trigger.new) {        
        task.Account_Name__c = a.AccountId;
    }
}


I keep receiving an error that says: A value cannot be stored to Account_Name__c in type task. What am I doing wrong?
I have been asked to make a custom weighting option for one of the smaller businesses in our org. 

If the sales manager picks one of the following picklist options during his opportunity creation, the formula should calculate as appropriate:

Custom Opp Weighting Picklist
Existing client, existing product =  divide opportunity amount by 2
Existing client, new product = divide opportunity amount by 3
New client, existing product = divide opportunity amount by 5
New client, new product = divide opportunity amount by 10

Is there an esy way I can I achive this via a picklist? 

Would really appreciate any 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.
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....
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,

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) 



 
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
Hi all,

The Lead object has some custom fields and when it's converting to a Contact I have to set the values of these fields to the custom fields of the Contact.

There are two options 1 - a new Contact and 2 - the already existing Contact.

For the second option I need to set the values only if they were not set previously (do not overwrite the previously set values)

I've created the Trigger:

trigger AACopyLeadFields on Lead (after update) {
Map<Id,Lead> leadStatus = new Map<Id,Lead>(); // Map of the converted Contact ID and the Lead Status

for(Lead lead : Trigger.new) {
if (lead.IsConverted) {
leadStatus.put(lead.ConvertedContactId,lead);
}
}

List<Contact> conContacts = new List<Contact>();

for ( Contact c : [select Id, LeadSource, CreatedDate, Converted_from_Lead__c from Contact WHERE Contact.Id IN :leadStatus.keySet()]) {
Lead lead = leadStatus.get(c.Id);
if(c.Converted_from_Lead__c == null) {
c.LeadSource = lead.LeadSource;
c.Lead_Source_Ext__c = lead.Lead_Source_Ext__c;
c.FirmwareEmail__c = lead.FirmwareEmail__c;
c.NewsletterEmail__c = lead.NewsletterEmail__c;
c.SoftwareEmail__c = lead.SoftwareEmail__c;
c.TrainingEventsEmail__c = lead.TrainingEventsEmail__c;
c.Converter_from_Lead__c = lead.Id;
conContacts.add(c);
}
}

if(conContacts.size() > 0) update conContacts;
}

When I convert a Lead into a new Contact (contact.CreatedDate == lead.LastModifiedDate) it works fine, but when I convert a Lead into already existed Contact it shows the error:

"
There was an error converting the lead. Please resolve the following error and try again: AACopyLeadFields: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 0037F00001BJtnnQAD; first error: UNKNOWN_EXCEPTION, java.lang.NullPointerException: [] Trigger.AACopyLeadFields: line 27, column 1
"

There is no any issue in the Partial Copy Sandbox.

Did someone have the same issue?



Thank you.

Regards, Michael Novozhilov
 
Hi Team,

I have 2 classes,
public class SelectMultiple{    
    @auraenabled public String label {get; set;}
    @auraenabled public String value {get; set;}
    @auraenabled public boolean selected {get; set;}
    @auraenabled public boolean disabled {get; set;}
}

public class Chroma_Detail {

    @auraenabled public List<SelectMultiple> Sprint {get; set;}  
}
How do I create Test Class to get 100% code coverage for this?
public class DuplicatePanCheck {
    public static void duplicatePanNo(List<Consultant__c> cons){
        for(Consultant__c c: cons){
                if(c.Pan_Number__c!= null){ 
                List<Consultant__c> con = [select id,Pan_Number__c,Phone__c,Email__c from Consultant__c where Pan_Number__c =: c.Pan_Number__c];  //checking the duplicate record based on the pan number
                        if(con.size()>1){
                        for(Consultant__c cn : con){   //if duplicate records found, updating phone, email fields in the old records 
                            cn.Phone__c = c.Phone__c;
                            cn.Email__c = c.Email__c;
                        }
                    update con;
                }
            }
        }
    }
}

trigger Trigg_DuplicatePanCheck on Consultant__c (after insert) {
    DuplicatePanCheck.duplicatePanNo(Trigger.new);
}
 
I have a custom boolean field that I've added to Files that I'm now trying to use in a SOQL query to pull all Files that are linked to a specific record where this custom field is set to TRUE. Here's my SOQL query:

SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityID = 'a00f400000RaXnDAAV' AND ContentDocumentId IN (SELECT ContentDocumentId FROM ContentVersion WHERE Send_to_Angeion__c = TRUE)

What's odd is that this query: 

SELECT ContentDocumentId FROM ContentVersion WHERE Send_to_Angeion__c = TRUE

Never returns any results, even when I've marked the Send_to_Angeion__c as TRUE on some records. And even more interestingly, this query 

SELECT ContentDocumentId, Send_to_Angeion__c FROM ContentVersion WHERE ContentDocumentID = '069f400000Azta2AAB'

will return results and lists the value in the Send_to_Angeion__c as "true" Any ideas on how I can fix this? 

TIA
In case object there is one custom text field type_c
case has record with any subject, and if we create another record with same subject, type_c field should be populated as 'duplicate'.
and this newly created case should b displayed in related list of previus case record.
APEX CLASS
public with sharing class ccController {
    public String firstName {get; set;}
    public String lastName {get; set;}
    public String email {get; set;}
    public String password {get; set {password = value == null ? value : value.trim(); } }
    public String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } }
    public String communityNickname {get; set { communityNickname = value == null ? value : value.trim(); } }    
    public ccController() {}    
    private boolean isValidPassword() {
        return password == confirmPassword;
    }
    public PageReference registerUser() {    
           // it's okay if password is null - we'll send the user a random password in that case
        if (!isValidPassword()) {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, Label.site.passwords_dont_match);
            ApexPages.addMessage(msg);
            return null;
        }    
        String profileId = null; // To be filled in by customer.
        String roleEnum = null; // To be filled in by customer.
        String accountId = ''; // To be filled in by customer.        
        String userName = email;
        User u = new User();
        u.Username = userName;
        u.Email = email;
        u.FirstName = firstName;
        u.LastName = lastName;
        u.CommunityNickname = communityNickname;
        u.ProfileId = profileId;        
        String userId = Site.createPortalUser(u, accountId, password);     
        if (userId != null) { 
            if (password != null && password.length() > 1) {
                return Site.login(userName, password, ApexPages.currentPage().getParameters().get('startURL'));
            }
            else {
                PageReference page = System.Page.ccPage;
                page.setRedirect(true);
                return page;

            }
        }
        return null;
    }
}

TEST CLASS

/**
* An apex page controller that supports self registration of users in communities that allow self registration
*/
@IsTest
public with sharing class ccControllerTEst {
    
    static testmethod void testCCController() {
        Account acc = new Account(Name = 'Test');
        insert acc;
        
        Profile p = [select id from profile where name='System Administrator'];
        User u = new User(alias = 'standt', email = 'standarduser@testorg.com', emailencodingkey = 'UTF-8', lastname = 'Testing', languagelocalekey = 'en_US',
                          localesidkey = 'en_US', profileid = p.Id, timezonesidkey = 'America/Los_Angeles',
                          username = 'testclassuser@testorg.com');
        insert u;
        
        ccController controller = new ccController();
        controller.firstName = 'FirstName';
        controller.lastName = 'LastName';
        controller.email = 'test@force.com';
        controller.communityNickname = 'test';
        // registerUser will always return null when the page isn't accessed as a guest user
        System.assert(controller.registerUser() == null); 
        
        controller.password = 'abcd1234';
        controller.confirmPassword = 'abcd123';
        System.assert(controller.registerUser() == null); 
        //String userId = Site.createPortalUser(u, acc.Id, controller.password);
        
    } 
}
  • August 06, 2019
  • Like
  • 0
I have a batch apex job that basically goes through all invoices and totals the amounts for each sales person for each month and year.  The job works as expected in the sandbox environment with the test data I created.  But when I moved the job to production, it runs without errors, but does not update the fields with the monthly invoice sum totals like it does in sandbox.  In reviewing the logs I found one for example that found totals and shows that it updated the fields for the months.  Then in the very next log that did not find any invoices with totals, it updated the fields with null values for the very same records as in the prior log.  The Forecast and Forecast detail objects were created from scratch for this batch job and have no other triggers or processes running against them to udpate any fields.  My code is below, can anyone see why it is not updating the sum fields properly?

global with sharing class Forecast_Batch implements Database.Batchable<sObject>, Database.Stateful{

        global Database.QueryLocator start(Database.BatchableContext BC)
        {
            return Database.getQueryLocator([SELECT Id,OwnerId FROM Account]); //Query all accounts for ID and OwnerId
        }

    global void execute(Database.BatchableContext BC, List<SObject> scope)
    {        
        Map<Id, Map<String,Decimal>> accountAmountMap = new Map<Id,Map<String,Decimal>>();

        List<Id> accountOwnerIds = new List<Id>();
        Set<Id> accountIds = new Set<Id>();
        
        system.debug('+++ SCOPE SIZE ' + scope.size());
        
        for (SObject s : scope) {
            
            Account acc = (Account)s;
            if(!accountIds.contains(acc.Id)){
                accountIds.add(acc.Id);
            }
            
        }
        
        for (Account acc : [SELECT OwnerId,(SELECT Amount__c,InvoiceDate__c,OwnerDetails__c,Inv_Yr__c FROM Invoice__r ) FROM Account WHERE Id in : accountIds]) {
            
            Map<String, Decimal> amountMap = new Map<String, Decimal>();
            
            for (Invoice__c inv : acc.Invoice__r) {
                 
                Decimal amount = amountMap.get(inv.OwnerDetails__c);
                if (amount != null) {
                    amountMap.put(inv.OwnerDetails__c, inv.Amount__c + amount); 
                } else {
                    amountMap.put(inv.OwnerDetails__c, inv.Amount__c); 
                }
            }
            accountAmountMap.put(acc.Id, amountMap);
            accountOwnerIds.add(acc.OwnerID);
            
        }
        System.debug(accountOwnerIds);

         // Query list of forecast details record based on Account's owner Id

        List<Forecast_Details__c> forecastdetails = [SELECT ID,Name,Month_Total__c,OwnerID__c,FDOwnerDets__c from Forecast_Details__c where OwnerID__c IN : accountOwnerIds];

        // Iterate accounts in for loop
        // iterate forecast details record
        // get invoice amount based on account id and forcast month.
        // update in forecast detail record.

        for (SObject s : scope) {
            Account acc = (Account)s;
            Map<String, Decimal> amountMap = accountAmountMap.get(acc.Id);
            for (Forecast_Details__c forecastDet : forecastdetails) {
                if (forecastDet.OwnerID__c == acc.OwnerId)
                    
                {
                    Decimal amount  = amountMap.get(forecastDet.FDOwnerDets__c);  
                    forecastDet.Month_Total__c = amount;
                    System.debug('match');
                    System.debug(amount);
                }
            }
        }
        System.debug(forecastdetails);
        update forecastdetails;
    }  

    global void finish(Database.BatchableContext BC){}



I really appreciate any assistance that anyone can provide!
Hi!

I have the query below in the controller of one of my visualforce pages:
 
SELECT Id, Name, Title, Company, Country, CreatedDate, Status FROM Lead WHERE Status='New' AND OwnerId= :UserInfo.getUserID() ORDER BY CreatedDate DESC

What I would like to do some kind of outer join to check if the Lead.Company field exists as a Account.Name so I can show this on the Visualforce page.

Any ideas on how to do this?
I am new in Apex, please help me to write trigger that should check the length of the Description field; if the field is longer than 200 characters, you need to trim it to 197 characters and add a three-dot at the end of the line.
I'm attempting to create a note for an opportunity via the REST API.  I'm finding several examples for the SOAP API, but nothing that works using REST.  Using this API I am able to create a note, but can find no way to associate it with an opportunity ID:

https://developer.salesforce.com/docs/api-explorer/sobject/Note

Any help would be greatly appreciated.
I properly installed CLI. In a command window, I enter:

sfdx force:auth:web:login -d -a DevHub

in order to log in to the trial Dev Hub that I created. The aforementioned command opens the Salesforce login page in the web browser, so I log in using my Developer Hub Trial Org credentials and click Allow. After that, web browser show me an error: "This site can't be reached. localhost took too long to respond".

This is the URL that Salesforce use after I authenticate in the browser: http://localhost:1717/OauthRedirect?code=aPrxbOND3gL_2LbSR7rKPdvD0XBVk2YpErl3pphY2f3xvZ1wf5SSPJByDleRLPMtzCQWnNGAdg%3D%3D&state=f2f8254fac23

I don't know what happen.

User-added image

User-added image

User-added image