• Abdul Khatri
  • ALL STAR
  • 5153 Points
  • Member since 2015


  • Chatter
    Feed
  • 164
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 1384
    Replies
Hello, so i want to connect my visualforce page to a class that get something from an api. And that to be shown on the home page.

here my class code
 
public class CatFactsDaily {
    
     public String catFact3{get;set;}
    
    public void toGetFacts() {
        String requestEndPoint = 'https://catfact.ninja/fact';
        
        Http http=new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(requestEndPoint);
        request.setMethod('GET');
        HttpResponse response=http.send(request);
        
        if(response.getStatusCode()==200){
            
            Map<String, Object> results=(Map<String, Object>) JSON.deserializeUntyped(response.getBody());
             catFact3=String.valueOf(results.get('fact'));           
            
        }
        
        else {
            ApexPages.Message myMsg=new ApexPages.Message(ApexPages.Severity.ERROR, 'There was an error in reading Data');
            ApexPages.addMessage(myMsg);
        }
        
    }

}

here is my visualforce code
 
<apex:page controller="CatFactsDaily" >
    
     <apex:pageBlock title="Cat Fact of the day!!">
        
        <apex:pageBlockSection >
            
            <apex:pageMessages ></apex:pageMessages>
            
            <apex:outputText label="CatFact" value="{!catFact3}"></apex:outputText>
        
        </apex:pageBlockSection>
    
    </apex:pageBlock>
    
</apex:page>

and this is what i get

User-added imageI ve tried this same api with for and account, and it works, but i cannot make it work for the home page​​​​​​​
Hello,

I previously created this VR and it was working fine until (at a later date) a 5th value was added to the picklist at which time I adjusted the numbers and values in the VR, but only the first picklist value was firing. 

AND( 
CASE( PICKLIST_FIELD__ c, 
"Value 1",1, 
"Value 2",2, 
"Value 3",3, 
"Value 4",4, 
"Value 5",5, 
0 ) = 1, 
ISBLANK( TEXT_FIELD__c )  
)

As a quick workaround I created five VRs, but would like to fix the above VR and remove the five VRs. Here's one of five VRs that's working:

AND( 
ISPICKVAL( PICKLIST_FIELD__ c , "Value 1") , 
ISBLANK( TEXT_FIELD__c ) 
)

I'd appreciate any guidance! Thank you in advance! :)
Schedule returning error message - assistance needed please:
*/
@isTest
public class NightlyDepositBatchTest {
public static String CRON_EXP = '0 0 0 15 3 ? 2022';
@testSetup
static void setup() {
List donations = new List();
for (Integer i=0;i donList = [SELECT Id, Donation_Use__c, Tributee__c, Gift_Type__c, Amount__c, GL_Code__c FROM Donations__c];
for(Donations__c donation: donList){
Test.setCreatedDate(donation.id, Datetime.newInstance(date.today(), Time.newInstance(0,0,0,0)).addDays(-1));
}
update donList;

}
@isTest static void test() {
Test.startTest();
NightlyDepositBatch uca = new NightlyDepositBatch(Date.today());
Id batchId = Database.executeBatch(uca);
Test.stopTest();
// after the testing stops, assert records were created properly
List depositLines = [SELECT Id,SUM(Amount__c) FROM QB_Deposit_Line__c GROUP BY Id LIMIT 1];
System.assertEquals(100, (Decimal)depositLines[0].get('expr0'));
}
@isTest static void test2() {
Test.startTest();
String jobId = System.schedule('ScheduledApexTest',
CRON_EXP,
new NightlyDepositSchedule());
Test.stopTest();
}
}
Unit test now returning error when deploying new test cases for other development being done and this test case not firing the scheduled test job. I have been searching for how to fix the test case and am not finding how to best resolve in the sandbox to update this and get any coverage listed for the Nightly Batch Schedule job in production.

With this above issue not able to get code coverage on this job -
global class NightlyDepositSchedule implements Schedulable{

global void execute(SchedulableContext sc) {
NightlyDepositBatch n1 = new NightlyDepositBatch(Date.today());
ID batchprocessid = Database.executeBatch(n1,Test.isRunningTest() ? 3 : 1);
}
}
The below is the code in my callout class with keys left out. I have tested in postman and the JSON quote like: '{"User": {"account_expires" : "2022-11-18"}}' works perfectly to update when making the call. However, when I run from Salesforce using this callout class, in debug logs, I can see debug statement looks like: 
11:01:27.11 (14669480)|USER_DEBUG|[29]|DEBUG|{"User": {"account_expires" : "2022-11-18"}}
but it seems variable assignment actually looks lke:
11:01:27.11 (14553531)|VARIABLE_ASSIGNMENT|[27]|body|"{\"User\": {\"account_e (24 more) ..."
I am thinking I need to deseralize the JSON maybe by using another class but am having trouble with this. At the moment, the response I am receiving is:
11:01:28.153 (1172417713)|CALLOUT_RESPONSE|[34]|System.HttpResponse[Status=Not Found, StatusCode=404]
11:01:28.153 (1172459328)|HEAP_ALLOCATE|[34]|Bytes:90
11:01:28.153 (1172492874)|VARIABLE_SCOPE_BEGIN|[34]|response|System.HttpResponse|true|false
11:01:28.153 (1172567949)|VARIABLE_ASSIGNMENT|[34]|response|"System.HttpResponse[Status=Not Found, StatusCode=404]"|0x733b55dd

Does anyone have an idea to help me edit the below code so that I can receive the successful response?

Thanks!
 
public class LearnUponCalloutClass {
    	
    	 @future(callout=true)
   		 public static void makeCallout(Integer UserId) {
            
            //declare variables 
		String username = 'XYZ';
    		String password = 'XYZ';
    		
            //prepare request 
                HTTP h = new HTTP();
                HTTPRequest r = new HTTPRequest();
            
            //set endpoint and authorize 
                r.setEndpoint('https://dphie.learnupon.com/api/v1/users/' + UserId);
            
                Blob headerValue = Blob.valueOf(username + ':' + password);

		String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);

		r.setHeader('Authorization', authorizationHeader);
		r.setMethod('PUT');
          
                String body = '{"User": {"account_expires" : "2022-11-18"}}';
         
		System.debug(body);
            
                r.setBody(body);
             
              //send request
			HTTPResponse response = h.send(r);
      
}

 
I have a list of permission sets (PS1-10) and one profile. Below are the steps which I need to execute:
  • First I need to find the users who have this particular profile and PS7
  • Then I need to check if the users having PS7 and this profile have all the permission sets (PS1-10) assigned to them. 
  • If there are less permission sets assigned, then return Missing, if there are more permission sets assigned, return Additional, else return No Change. I need to implement this using either Flow or Apex. 
  • The final output should give me the userID, the permission sets assigned to them and Missing/Additional/No change
Till now I have been doing this manually by querying the PermissionSetAssignment object, then retrieving the Assignee details and the permission sets assigned to the assignee, then manually checking.
 
Thank you
I am new to apex and am trying to use Maps to figure out total Open and Closed cases for a Contact record. 

The following is not working, please suggest what is wrong. 
// Trigger should update contact with total tickets : closed and Opened

trigger Prac_caseUtil on Case (after insert, after delete, after update) {
map<id,List<case>> caseMap = new map<id,list<case>>();
    for(case caseObject : trigger.new){
        if(caseObject.accountid !=NULL && caseMap.get(caseObject.accountid)==NULL){
            caseMap.put(caseObject.accountid,new LIST<case>());            
            caseMap.get(caseObject.AccountId).add(caseObject); 
        }
    }
    // SOQL 
    LIST<contact> conListToUpdateOpen = [SELECT Id,Total_Open_Tickets__c,Total_Closed_Tickets__c,(SELECT ID FROM Cases WHERE IsClosed=FALSE) 
                                     FROM CONTACT 
                                     WHERE ID IN:caseMap.keySet()];
    
   LIST<contact> conListToUpdateClosed = [SELECT Id,Total_Open_Tickets__c,Total_Closed_Tickets__c,(SELECT ID FROM Cases WHERE IsClosed=TRUE) 
                                     FROM CONTACT 
                                     WHERE ID IN:caseMap.keySet()];
    
    for(contact c:conListToUpdateOpen){
        c.Total_Open_Tickets__c = caseMap.get(c.id).size();
        system.debug('###### open tickets' + caseMap.get(c.id).size());
    }

    for(contact c:conListToUpdateClosed){
        c.Total_Closed_Tickets__c = caseMap.get(c.id).size();
        system.debug('###### closed tickets' + caseMap.get(c.id).size());
    }
    update conListToUpdateOpen;
    update conListToUpdateClosed;
}

 
we have a requirement that when if a Conga transaction record has 'Sent' status , it should not allow the user to create a new conga transaction record. I created a trigger and apex handler class.

trigger congatransaction on APXT_CongaSign__Transaction__c (before INSERT) {
    
   congatransactionHandler.congatransactionMethod(Trigger.NewMap,Trigger.OldMap);
   
   }


public class congatransactionHandler {
    
    public static void congatransactionMethod(Map<Id,APXT_CongaSign__Transaction__c> newconMap, Map<Id,APXT_CongaSign__Transaction__c> oldconMap){
        Set<Id> conIds = New Set<Id>();
        List<APXT_CongaSign__Transaction__c> conList = New List<APXT_CongaSign__Transaction__c>();
        
        for(APXT_CongaSign__Transaction__c con : newconMap.values()){
               APXT_CongaSign__Transaction__c oldcontranmap = oldconMap.get(con.Id);
             if(oldconMap!=null && oldconMap.size()>0)
    // Trigger.new records are conveniently the "new" versions!
{        //Boolean oldcontransactionmap = oldcontranmap.APXT_CongaSign__Status__c.equals('SENT'); 
            if((newconMap.get(con.Id).Parent_a29__c== oldcontranmap.Parent_a29__c) && oldcontranmap.APXT_CongaSign__Status__c.equals('SENT')){


          con.adderror('You have already sent the conga transaction');
            }
        }
          
    }
}
}
        
1. Write a method that takes in a list of Account Ids.  The method should have the return type: map<Id, map<Id, list<OpportunityLineItem>>>. Each account Id passed in should be mapped to a map of its opportunities mapped to the list of their respective opportunity line items.  Only opportunities with an amount of 500,000 or more should be included in the return.  There is a custom boolean field on the opportunity line item with API name Export_Ignore__c.  If this field is true, the account should be removed from the return map.


2. Write a SOSL statement that returns any leads or contacts where either the first or last name contains ‘cha’.  Both lead and contact results should contain the email address, first name, and last name.  Contacts should also include the account Id.

3. Write a SOQL statement that returns the Id of 10 accounts and all of the opportunity names associated with each account.
I have a formula that currently works. Basically, if Investment Name is XYZ, then filling in the Total Size is required.
AND(ISBLANK(TEXT(Total_Size_c)), ISPICKVAL(Investment_Name_c,"XYZ"))

I want to add additional consideration for another picklist field. I want the above to kick in only if Type_c field is equal to “Addition”  OR  “New Investment”.  

I am not sure how to add this. Can anyone help?
 
Hi all,
Im getting a null pointer exception butwhen when i debug it everyone argument has a value but still it is throwing null pointer exxeption . can anyone please guide me User-added image
I keep receiving a "Missing ) Error"

IF(Acq_Comm_Calc__c CONTAINS $500),Estimated_Net_Profit_Retail_Renovation__c+500,
IF(AND Acq_Comm_Calc__c CONTAINS 8%),Estimated_Net_Profit_Retail_Renovation__c*0.08,
IF(AND Acq_Comm_Calc__c CONTAINS 10%),Estimated_Net_Profit_Retail_Renovation__c*0.1,
IF(AND Acq_Comm_Calc__c CONTAINS 12%),Estimated_Net_Profit_Retail_Renovation__c*0.12,
IF(AND Acq_Comm_Calc__c CONTAINS 15%),Estimated_Net_Profit_Retail_Renovation__c*0.15,
IF(Acq_Comm_Calc__c CONTAINS $7000),Estimated_Net_Profit_Retail_Renovation__c+7000,)
)
)
)
)

)
Trigger:
trigger PDFGenrate on Opportunity (after insert, after update) {
	 
   Set<Id> OppIds= new Set<Id>();
    
    for(Opportunity opp: trigger.new){        
        if(opp.StageName=='Closed Won'){            
         OppIds.add(Opp.Id);             
        } 
       }OpportunityPdfController.pdfGenration(OppIds);      
}

Trigger Handler: 
public class OpportunityPdfController {
    
    @future(callout=true)
    public static void pdfGenration(Set<Id> OppIds){
        List<Sobject> attachmentlist = new List<Sobject>();
        List<Sobject> ContentDocLink = new List<Sobject>();
        for(Id OppId: OppIds){

            Blob body;
            
                    PageReference pdf = new  PageReference('/apex/PrintPDF');
                    pdf.getParameters().put('Id',OppId);     
                  
                    ContentVersion cv=new ContentVersion();            
                    try{                
                        body=pdf.getContentAsPDF();
                    }catch (Exception e) {
                        body = Blob.valueOf('Text');
                        system.debug(e.getMessage());
                    }                     
                    cv.PathOnClient= 'Invoice'+'.pdf';            	
                    cv.Title= 'Invoice';
                    cv.IsMajorVersion = true;  
            		cv.VersionData=body;
                    attachmentlist.add(cv);     
            
        //   }     
     
     //  if(attachmentlist.size()>0){
            insert  attachmentlist;              
            
            
            Id conDocId = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:cv.Id].ContentDocumentId;
            system.debug(conDocId);
            ContentDocumentLink cdl = New ContentDocumentLink();

            cdl.LinkedEntityId = OppId;
            
            cdl.ContentDocumentId = conDocId;
            
            cdl.shareType = 'V';
            
        ContentDocLink.add(cdl);
            insert ContentDocLink;
            
        }
        
    }
}

 
  • August 03, 2022
  • Like
  • 0
Hey guys, I need to do the following, check if the banco__c fields
 and digito_da_conta return null and if they do I have a method that updates this field directly from another object
if(opp.Conta__c = null && opp.Banco__c = null && opp.Agencia__c = null ){
            CheckBankDataOfTheOpportunity(ssi,opp);
        }

   
private void CheckBankDataOfTheOpportunity(SelfSignIn__c ssi, Opportunity opp){
        opp.Agencia__c = ssi.Agencia__c;
        opp.Banco__c = ssi.Banco__c;
        opp.Conta__c = ssi.Conta__c;
    }

 
UseCase In Account Object:

Created a Trigger when the ParentAccount is selected in account object ,need to copy  the phone number and name and insert the record.
how can i add the Trigger in the Apex Class and Write Test Class...
 
trigger CopyAccountTriggerTest on Account (before insert) {
  
   
    if(checkRecursiveTest.runOnce()) {
        Set<Id> accountIds = new Set<Id>();
        for (Account acc : Trigger.new) {
            if (acc.ParentId != null){
                accountIds.add(acc.ParentId);
            }
            if(accountIds.size() > 0){  
                  List<Account> accounts = [select id,Name,Phone from account where id in :accountIds ];
                
                for (Account acc2 : Trigger.new) {
                    if (acc2.ParentId != null){
                        acc2.Name = 'Duplicate'+accounts[0].Name;
                        acc2.Phone= 'Duplicate'+accounts[0].Phone;
                    }
                }
            }
        }
 }

  
 
    
}



Apex Class:
=========
 
public class checkRecursiveTest {
    private static boolean run = true;
    public static boolean runOnce(){
     if(run){
     run=false;
     return true;
    }else{
        return run;
    }
    }
}

 
trigger CopyAccountTriggerTest on Account (before insert) {
  
   
    if(checkRecursiveTest.runOnce()) {
        Set<Id> accountIds = new Set<Id>();
        for (Account acc : Trigger.new) {
            if (acc.ParentId != null){
                accountIds.add(acc.ParentId);
            }
            if(accountIds.size() > 0){  
                  List<Account> accounts = [select id,Name,Phone from account where id in :accountIds ];
                
                for (Account acc2 : Trigger.new) {
                    if (acc2.ParentId != null){
                        acc2.Name = 'Duplicate'+accounts[0].Name;
                        acc2.Phone= 'Duplicate'+accounts[0].Phone;
                    }
                }
            }
        }
 }

  
 
    
}

ApexClass:
 
public class checkRecursiveTest {
    private static boolean run = true;
    public static boolean runOnce(){
     if(run){
     run=false;
     return true;
    }else{
        return run;
    }
    }
}

UseCase In Account Object:

Created a Trigger when the ParentAccount is selected in account object ,need to copy  the phone number and name and insert the record.
how can i add the Trigger in the Apex Class and Write Test Class...

Thanks 
Samantha
 
Hi - basic beginner apex question but struggling. 

The list TR2 will have duplicate values for Supplier__c. I want to end up with map with count of records for each Supplier__c.

What needs to go in the for loop to get this ? Thanks 
 
List<Trading_Relationship__c> Tr2 = [SELECT Supplier__c FROM Trading_Relationship__c WHERE Supplier__c IN :AccIds ORDER By Supplier__c ASC];

Map<ID, Integer> Map1 = new Map<ID, Integer>();
        
 for (Trading_Relationship__c eachTr : Tr2){   
            
            
        }
I can't figure out why the insert function isn't working. Can anyone help me? Thank you so much.

CONTROLLER:

public class ApartmentMapLister {

    public Map_Lead__c MapLead {get;set;}
    public Map_Point__c MapPoint {get;set;}
    public Map<Integer, Map_Point__c> ApartmentMap {get;set;}
    Public List<Wrapper> Wrapperlist {get;set;}

    public ApartmentMapLister() {
        MapLead = [SELECT ID, NAME, First_Name__c, Last_Name__c FROM Map_Lead__c WHERE ID=:ApexPages.currentPage().getParameters().get('id')];
    }    

    public Map<Integer, Map_Point__c> getonebedadmin() {

       Wrapperlist = new List<Wrapper>();
       
       ApartmentMap = new Map<Integer, Map_Point__c>();
       List<Map_Point__c> ApartmentList = [SELECT Id, Name, IsSelected__c FROM Map_Point__c Order By Name];

        for(Map_Point__c mp: ApartmentMap.values()) {
            Wrapper wrap = new Wrapper();
            wrap.mappoint = mp;
            Wrapperlist.add(wrap);
            }
                    
       for(Integer index = 0 ; index < ApartmentList.size() ; index++) {
           ApartmentMap.put(index, ApartmentList[index]);
       }
       return ApartmentMap;
    }

    public class Wrapper{
    
        public boolean isSelected {get;set;}
        public Map_Point__c mappoint {get;set;}
               
    }
    
    public void InsertApartment(){
        
        for(Wrapper wr : Wrapperlist){
        
            if(wr.mappoint.isSelected__c == true){
                
        Map_List__c ml = new Map_List__c();
            ml.Map_Lead__c=ApexPages.currentPage().getParameters().get('id');
            ml.Map_Point__c=wr.mappoint.ID;
            ml.Unique__c=(MapLead.NAME + wr.mappoint.AIMid__c);
            insert ml;
            }
        }
    }
    

      public PageReference SaveRecords(){
    
        List<Map_Point__c> records = new List<Map_Point__c>();
        for(Map_Point__c df : ApartmentMap.values()) {
            records.add(df);
        }
        // Bulk update with one DML call
        update records;
        return null;
      }
}


VISUALFORCE PAGE:
<apex:page sidebar="false" showHeader="false" cache="true" id="page" docType="HTML" readOnly="false" controller="ApartmentMapLister">
<apex:form >
    {!MapLead.First_Name__c} {!MapLead.Last_Name__c}
    
    <apex:pageBlock >
       <apex:pageBlockButtons location="top">
           <apex:commandButton value="Save" action="{!InsertApartment}"/>
       </apex:pageBlockButtons>
       <apex:pageBlockTable value="{!onebedadmin}" var="Map_Point__c">
            <apex:column >
                <apex:inputField value="{!onebedadmin[Map_Point__c].IsSelected__c}"/>
            </apex:column>
            <apex:column >
                <apex:inputField value="{!onebedadmin[Map_Point__c].Name}"/>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:form>
</apex:page>
I wrote this. But its not wokrking if one of the fields is blank(but working if both are blank). what changes should i make ?
IF(
AND(NOT(ISBLANK( abc__c )) , NOT(ISBLANK( xyz__c ))) ,


IMAGE("/servlet/servlet.ImageServer?id=0150R000001JUkT&oid="+$Organization.Id, "icon" ,24, 128),
""
)

 
I have a Visualforce Page, with some input text fields. (There is NO standard or custom object associated with this Page). There is a button 'Generate PDF'. On click of this button, PDF needs to be generated having all the input text values.
How do we send the input text values to the PDF? (PDF is getting generated having only labels, no values) Please let me know!
  • October 25, 2021
  • Like
  • 0
Hope this is the right area to post this.  I am logged into SalesForce Lightning and can move around normally with our data. When I open up a new tab and access Workbench, the objects I run a query against are not ours.  For example, our Account object has 26 records in it currently.  But in Workbench, a count against the Account object indicates there are over 200,000 records.  Also the custom fields are not listed. I havent logged in a little over a month but up until my last login, everything was fine.  Any help and/or ideas?
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
I have some instances of two email addresses being entered in the Email field in Salesforce. What would a SOQL query look like that querys any Email field value that contains two or more @ symbols?
I have a flow that is creating email to case records and I have currently 4 verified email service addresss, but when I select more than one service address on To Address for email to case it's creating multiple records with the the same owner and record type how I can prevent this?
I am writing a trigger where I am bringing in a Date/Field field from case. It has a letter in it 2023-02-10T16:15:35.000+0000 and when I try to subtract it with "DateTime.now()" I get an error "Date/time expressions must use Integer or Double or Decimal ".

This is my code 
trigger CaseTrigger on Case (before update) {
     for(Case cases: Trigger.new){ 
         if(cases.stopped_time__c != null){
             cases.Total_amount_of_time_in_Hours__c= (DateTime.now()-cases.stopped_time__c );
         } 
    }
}
Hello,
I have a simple use case.
I need to update a text field "Contact id" after increment it by 1 whenever a new contact is created.
below is ss for reference. I want to update contact id as 172 for new contact creation.
Please help me how can I update a text field by 1 .

field label : contact id
api name :Contact_ids__c


User-added image 
My code is :- 

@RestResource(URLMapping='/SendEmailForOTP/*')
global class WordpressIntegrationForEmail {
    
    @HTTPPOST
    global static FinalReturnWrapper SendEmailMsg(string email , string otp,string mob,boolean send_otp_if_exists)
    {
        
        FinalReturnWrapper returnResponse = new FinalReturnWrapper(); 
        cls_data objData = new cls_data();
        
        Integer otpSize = otp.length();
        if(otpSize == 5)
        {
            
            list<contact> conList = [Select id,Do_Not_Mail__c,Email_Verification_Status__c, Email_Verification_Status_Date__c,LastName from contact where email =: email Limit 1];
            
            if(conList.size() > 0 )  // If the email id is exist then ...
            {
                objData.contact_exists = true;
                
                for(contact c : conList)
                {
                    objData.contact_id =c.id;
                    objData.name=c.LastName;
                    if(c.Do_Not_Mail__c == false && c.Email_Verification_Status__c == null && c.Email_Verification_Status_Date__c == null)
                    {
                        
                        OtpViaEmail.sendEmail(email,otp);  //Sending Email 
                        objData.otp_sms_sent = true; 
                        objData.otp_email_sent = true;
                        
                    }else 
                    {
                        objData.bounced_email=true;
                    }
                    
                }
                returnResponse.obj = objData;
                System.debug('returnResponse:'+returnResponse);
                return returnResponse;
                
            }
            else    // If the email id not exist then...
            {
                if(send_otp_if_exists==false)
                {
                    objData.contact_exists = false;
                    objData.contact_id =null;
                    OtpViaEmail.sendEmail(email,otp);    //Sending Email 
                    objData.otp_sms_sent = true; 
                    objData.otp_email_sent = true;
                    returnResponse.obj =objData;
                    System.debug('returnResponse:'+returnResponse);
                    return returnResponse;
                }
                
                objData.contact_exists = null;
                objData.contact_id =null;
                objData.otp_sms_sent = false; 
                objData.otp_email_sent = false;
                objData.name=null;
                returnResponse.obj = objData;
                System.debug('returnResponse:'+returnResponse);
                return returnResponse;         
                
            }
            
        }
        objData.contact_exists = null;
        objData.contact_id =null;
        objData.otp_sms_sent = false; 
        objData.otp_email_sent = false;
        objData.name=null;
        returnResponse.obj = objData;
        System.debug('returnResponse:'+returnResponse);
        return returnResponse; 
        
        
        
    }
    
    global class FinalReturnWrapper {
        
        public cls_data obj ;
        
        
    }
    public class cls_data {
        
        public boolean contact_exists;
        public boolean otp_sms_sent;
        public boolean otp_email_sent;
        public string contact_id;
        public boolean bounced_email;     
        public string name;
    }
    
}
__________________________________
ANd here is the test class :- 

@IsTest
public class WordpressIntegrationForEmailTest {
    
    
    public static testMethod void  testPostRestService(){
        
        
        contact c = new contact ();
        c.LastName = 'Pav';
        c.Email = 'pavan@intuitiolabs.com';
        c.Do_Not_Mail__c=false;
        c.Email_Verification_Status__c=null;
        c.Email_Verification_Status_Date__c=null;
        insert c;
        
        Test.startTest();        
        
        string email = 'pavan1@intuitiolabs.com';
        string otp='11223';
        string mob='987654321';
        boolean send_otp_if_exists = false;
        
        
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();
        
        req.requestURI = '/services/apexrest/WordpressIntegrationForEmail';  //Request URL
        req.httpMethod = 'POST';//HTTP Request Type
        req.requestBody = Blob.valueof('TestMsg');
        req.addParameter(name, value)
        RestContext.request = req;
        RestContext.response= res;
        
        WordpressIntegrationForEmail.SendEmailMsg(email,otp,mob,send_otp_if_exists);
        
        Test.stopTest();
    }
    
}

The error I am facing is below :- System.NullPointerException: Argument cannot be null.
We are seeing scenarios where we believe Bulk API V2 query endpoint is returning duplicate records.  Has anyone ever seen this, and if so, any recommendations for how to avoid?
Hello, so i want to connect my visualforce page to a class that get something from an api. And that to be shown on the home page.

here my class code
 
public class CatFactsDaily {
    
     public String catFact3{get;set;}
    
    public void toGetFacts() {
        String requestEndPoint = 'https://catfact.ninja/fact';
        
        Http http=new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(requestEndPoint);
        request.setMethod('GET');
        HttpResponse response=http.send(request);
        
        if(response.getStatusCode()==200){
            
            Map<String, Object> results=(Map<String, Object>) JSON.deserializeUntyped(response.getBody());
             catFact3=String.valueOf(results.get('fact'));           
            
        }
        
        else {
            ApexPages.Message myMsg=new ApexPages.Message(ApexPages.Severity.ERROR, 'There was an error in reading Data');
            ApexPages.addMessage(myMsg);
        }
        
    }

}

here is my visualforce code
 
<apex:page controller="CatFactsDaily" >
    
     <apex:pageBlock title="Cat Fact of the day!!">
        
        <apex:pageBlockSection >
            
            <apex:pageMessages ></apex:pageMessages>
            
            <apex:outputText label="CatFact" value="{!catFact3}"></apex:outputText>
        
        </apex:pageBlockSection>
    
    </apex:pageBlock>
    
</apex:page>

and this is what i get

User-added imageI ve tried this same api with for and account, and it works, but i cannot make it work for the home page​​​​​​​
Can somebody assist me with formatting this correctly:

{!IF(ISPICKVAL(Event.Affiliate_Location__c, "New York"), "address 1", !IF(ISPICKVAL(Event.Affiliate_Location__c, "Denver"), "address 2", "address 3"))}

I keep getting: ArgumentError: Incorrect parameter type for function 'ISPICKVAL()'. Expected Picklist, received Text
  • December 07, 2022
  • Like
  • 0
Im using a tool to write SOQL queries - very simple like
select * from contact

Is there a simple SOQL query I could use to get email domain in that query like
select email,[split email as domain] from contact
  • December 04, 2022
  • Like
  • 0
Hi Team , 
Can anyone help this simple one. I tried but couldnt succeed. 
I have a quick action button Named "Customer" placed on Account record.
1. On click of customer i want the Account name to be displayed on  the look up. but i am getting id as shown in screenshot . (Need some code fix )

i have highlighted the code in lookup cmp JS , were i am passing in the record id. may i know how to get the account name 

Customer.html
<template>
    <lightning-card>
      <header class="slds-modal__header" data-aura-rendered-by="142:2755;a">
        <h2 class="slds-modal__title" data-aura-rendered-by="143:2755;a"><b>Customer</b></h2>
        </header>
        <div class="slds-m-around--xx-large ">
  
    <div class="form-group">
         <c-custom-Lookup-Lwc>icon-name="standard:account"
            s-object-api-name="Account"
            label="Account Name "
            onlookupupdate={lookupRecord}
            placeholder="Search Account here..."></c-custom-Lookup-Lwc>
    </div>    
    
   
        
      <footer class="slds-modal__footer" data-aura-rendered-by="145:2889;a">
        <div>
          <lightning-button variant="neutral" label="Cancel" onclick={closeAction} ></lightning-button>
          <lightning-button variant="brand" label="Save" onclick={closeAction} ></lightning-button>
        </div>
      </footer>
    
      </div>
    </lightning-card>
  </template>
  
  ===========
  import { LightningElement,wire,api,track} from 'lwc';
import { CloseActionScreenEvent } from 'lightning/actions';

export default class Customer extends LightningElement {
    lookupRecord(event){
        alert('Selected Record Value on Parent Component is ' +  JSON.stringify(event.detail.selectedRecord));
    }

    closeAction(){
        this.dispatchEvent(new CloseActionScreenEvent());
    }

}
===================================
lookup component or child component:

<template>
    <div class="slds-form-element" onmouseleave={toggleResult}  data-source="lookupContainer">      
        <div class="slds-combobox_container slds-has-selection">
          <label class="slds-form-element__label" for="combobox-id-1">{label}</label>
          <div class="lookupInputContainer slds-combobox slds-dropdown-trigger slds-dropdown-trigger_click" aria-expanded="false" aria-haspopup="listbox" role="combobox"> 
           <div class="slds-combobox__form-element slds-input-has-icon slds-input-has-icon_left-right" role="none">
              <div class="searchBoxWrapper slds-show">
                <!--Lookup Input Field-->
                <lightning-input                   
                   type="search"
                   data-source="searchInputField"
                   onclick={toggleResult}
                   onchange={handleKeyChange}
                   is-loading={isSearchLoading}
                   value={searchKey}
                   variant="label-hidden"
                   placeholder={placeholder}
               ></lightning-input>  
              </div>
              
            <!--Lookup Selected record pill container start-->  
            <div class="pillDiv slds-hide">        
              <span class="slds-icon_container slds-combobox__input-entity-icon">
                <lightning-icon icon-name={iconName} size="x-small" alternative-text="icon"></lightning-icon>  
              </span>
              <input type="text"
                     id="combobox-id-1"
                     value={selectedRecord.Name}       
                     class="slds-input slds-combobox__input slds-combobox__input-value"
                     readonly
                     />
              <button class="slds-button slds-button_icon slds-input__icon slds-input__icon_right" title="Remove selected option">
              <lightning-icon icon-name="utility:close" size="x-small" alternative-text="close icon" onclick={handleRemove}></lightning-icon> 
             </button>
            </div>  
            </div>
        
            <!-- lookup search result part start-->
            <div style="margin-top:0px" id="listbox-id-5" class="slds-dropdown slds-dropdown_length-with-icon-7 slds-dropdown_fluid" role="listbox">
              <ul class="slds-listbox slds-listbox_vertical" role="presentation">
                <template for:each={lstResult} for:item="obj">
                <li key={obj.Id} role="presentation" class="slds-listbox__item">
                  <div data-recid={obj.Id} onclick={handelSelectedRecord} class="slds-media slds-listbox__option slds-listbox__option_entity slds-listbox__option_has-meta" role="option">
                    <span style="pointer-events: none;" class="slds-media__figure slds-listbox__option-icon" >
                      <span class="slds-icon_container" >
                          <lightning-icon icon-name={iconName} size="small" alternative-text="icon" ></lightning-icon>  
                      </span>
                    </span>
                    <span style="pointer-events: none;" class="slds-media__body" >
                      <span  class="slds-listbox__option-text slds-listbox__option-text_entity">{obj.Name}</span>
                    </span>
                  </div>
                </li>
                </template>
                <!--ERROR msg, if there is no records..-->
                <template if:false={hasRecords}>
                  <li class="slds-listbox__item" style="text-align: center; font-weight: bold;">No Records Found....</li>
                </template>
              </ul>
             
            </div>
          </div>
        </div>
      </div>
  </template>

=============
/* https://lwcfactory.com/custom-lookup-salesforce-lwc/
API : 50
Source : lwcFactory.com
*/
import { LightningElement,api,wire} from 'lwc';
// import apex method from salesforce module 
import fetchLookupData from '@salesforce/apex/CustomLookupLwcController.fetchLookupData';
import fetchDefaultRecord from '@salesforce/apex/CustomLookupLwcController.fetchDefaultRecord';
import { CurrentPageReference } from 'lightning/navigation';

const DELAY = 300; // dealy apex callout timing in miliseconds  

export default class CustomLookupLwc extends LightningElement {
    // public properties with initial default values 
    @api label = 'custom lookup label';
    @api placeholder = 'search...Acc...'; 
    @api iconName = 'standard:account';
    @api sObjectApiName = 'Account';
    @api defaultRecordId = '';
    @api recordId;
    
    // private properties 
    lstResult = []; // to store list of returned records   
    hasRecords = true; 
  //  searchKey=''; // to store input field value   
     searchKey=''; 
    isSearchLoading = false; // to control loading spinner  
    delayTimeout;
    selectedRecord = {}; // to store selected lookup record in object formate 

    @wire(CurrentPageReference)
    getStateParameters(currentPageReference) {
        if (currentPageReference) {
            this.recordId = currentPageReference.state.recordId;
            console.log('this.recordId==35==='+this.recordId);
            this.searchKey= this.recordId;
        }
    }


    // initial function to populate default selected lookup record if defaultRecordId provided  
    connectedCallback(){
     console.log('this.defaultRecordId====='+this.defaultRecordId);
     console.log('this.recordId==CCB==='+this.recordId);
     
      if(this.defaultRecordId != ''){
            fetchDefaultRecord({ recordId: this.defaultRecordId , 'sObjectApiName' : this.sObjectApiName })
            .then((result) => {
                if(result != null){
                    this.selectedRecord = result;
                    this.handelSelectRecordHelper(); // helper function to show/hide lookup result container on UI
                }
            })
            .catch((error) => {
                this.error = error;
                this.selectedRecord = {};
            });
         }
    }

    // wire function property to fetch search record based on user input
    @wire(fetchLookupData, { searchKey: '$searchKey' , sObjectApiName : '$sObjectApiName' })
     searchResult(value) {
        const { data, error } = value; // destructure the provisioned value
        this.isSearchLoading = false;
        if (data) {
             this.hasRecords = data.length == 0 ? false : true; 
             this.lstResult = JSON.parse(JSON.stringify(data)); 
         }
        else if (error) {
            console.log('(error---> ' + JSON.stringify(error));
         }
    };
       
  // update searchKey property on input field change  
    handleKeyChange(event) {
        // Debouncing this method: Do not update the reactive property as long as this function is
        // being called within a delay of DELAY. This is to avoid a very large number of Apex method calls.
        this.isSearchLoading = true;
        window.clearTimeout(this.delayTimeout);
        const searchKey = event.target.value;
        this.delayTimeout = setTimeout(() => {
        this.searchKey = searchKey;
        }, DELAY);
    }


    // method to toggle lookup result section on UI 
    toggleResult(event){
        const lookupInputContainer = this.template.querySelector('.lookupInputContainer');
        const clsList = lookupInputContainer.classList;
        const whichEvent = event.target.getAttribute('data-source');
        switch(whichEvent) {
            case 'searchInputField':
                clsList.add('slds-is-open');
               break;
            case 'lookupContainer':
                clsList.remove('slds-is-open');    
            break;                    
           }
    }

   // method to clear selected lookup record  
   handleRemove(){
    this.searchKey = '';    
    this.selectedRecord = {};
    this.lookupUpdatehandler(undefined); // update value on parent component as well from helper function 
    
    // remove selected pill and display input field again 
    const searchBoxWrapper = this.template.querySelector('.searchBoxWrapper');
     searchBoxWrapper.classList.remove('slds-hide');
     searchBoxWrapper.classList.add('slds-show');

     const pillDiv = this.template.querySelector('.pillDiv');
     pillDiv.classList.remove('slds-show');
     pillDiv.classList.add('slds-hide');
  }

  // method to update selected record from search result 
handelSelectedRecord(event){   
     var objId = event.target.getAttribute('data-recid'); // get selected record Id 
     this.selectedRecord = this.lstResult.find(data => data.Id === objId); // find selected record from list 
     this.lookupUpdatehandler(this.selectedRecord); // update value on parent component as well from helper function 
     this.handelSelectRecordHelper(); // helper function to show/hide lookup result container on UI
}

/*COMMON HELPER METHOD STARTED*/

handelSelectRecordHelper(){
    this.template.querySelector('.lookupInputContainer').classList.remove('slds-is-open');

     const searchBoxWrapper = this.template.querySelector('.searchBoxWrapper');
     searchBoxWrapper.classList.remove('slds-show');
     searchBoxWrapper.classList.add('slds-hide');

     const pillDiv = this.template.querySelector('.pillDiv');
     pillDiv.classList.remove('slds-hide');
     pillDiv.classList.add('slds-show');     
}

// send selected lookup record to parent component using custom event
lookupUpdatehandler(value){    
    const oEvent = new CustomEvent('lookupupdate',
    {
        'detail': {selectedRecord: value}
    }
);
this.dispatchEvent(oEvent);
}


}
HI all,

Account which don’t have opty for more than 2 years, all need to move to Lead.

please help with write batch apex

Any one please suggest 
on Lead creation and updation if lead status is qualified or unqualified want current date . i have written below trigger but its not working

trigger LeadTrigger on Lead (before insert,Before update) {
   if(trigger.isBefore && trigger.isUpdate){
LeadTriggerHandler.befUpdt(trigger.new , trigger.oldMap);
   }

}
------------------------------------------------------------------------------------
public class LeadTriggerHandler {
    
    public static void befUpdt(List<Lead> newLd, map<Id,Lead> oldMapLd){
        
        for(Lead ld : newLd){
           if (oldMapLd != Null && ld.status != oldMapLd.get(ld.Id).status ){
                if(ld.status == 'qualified' && ld.status ==' unqualified'){
                    ld.CreatedDate = system.now() ;
                }
            }
        }
        
    }

}

thank you,
snehal