• Bilal 25
  • NEWBIE
  • 20 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 7
    Questions
  • 8
    Replies
Dear Folks,

How are you?

I have a scenario to build a page in lightning to show in community to insert a record from custom object with different upload screen. I know this can be achievable in flow but for our current requirement i have to build in aura/lwc. If someone can help what's the issue in the code.User-added image
 
<template>  
   <div class="slds-box slds-theme_default">  
     <div class="slds-m-around_medium">  
       <lightning-input type="text" label="Name" onchange={onNameChange}></lightning-input>  
       <lightning-input type="tel" label="Phone" onchange={onPhoneChange}></lightning-input>  
       <lightning-input type="email" label="Email" onchange={onEmailChange}></lightning-input>  
       <lightning-textarea name="input3" label="Description" onchange={onDescriptionChange}  
         placeholder="type here..."></lightning-textarea>  
       <lightning-input type="file" onchange={onFileUpload} required name="uploadFile" label="Upload File">  
       </lightning-input>
				 <lightning-input type="file" onchange={onFileUpload1} required name="uploadFile" label="Upload File">  
       </lightning-input>
     </div>  
     <div class="slds-align_absolute-center">    
       <lightning-button label="Save" onclick={saveContact}>  
       </lightning-button>  
     </div>  
   </div>  
 </template>
 
import { LightningElement, track } from 'lwc';  
 import saveRecord from '@salesforce/apex/ContactController123.saveContact';  
 import { NavigationMixin } from 'lightning/navigation';  
 import { ShowToastEvent } from 'lightning/platformShowToastEvent';  
 const MAX_FILE_SIZE = 100000000; //10mb  
 export default class NewRecordWithFileUpload extends NavigationMixin(LightningElement) {  
   @track name;  
   @track phone;  
   @track email;  
   @track description;  
   uploadedFiles = []; file; fileContents; fileReader; content; fileName  
   onNameChange(event) {  
     this.name = event.detail.value;  
   }
		 uploadedFiles1 = []; file; fileContents; fileReader; content; fileName  
   onNameChange(event) {  
     this.name = event.detail.value;  
   }
   onPhoneChange(event) {  
     this.phone = event.detail.value;  
   }  
   onEmailChange(event) {  
     this.email = event.detail.value;  
   }  
   onDescriptionChange(event) {  
     this.description = event.detail.value;  
   }  
   onFileUpload(event) {  
     if (event.target.files.length > 0) {  
       this.uploadedFiles = event.target.files;  
       this.fileName = event.target.files[0].name;  
       this.file = this.uploadedFiles[0];  
       if (this.file.size > this.MAX_FILE_SIZE) {  
         alert("File Size Can not exceed" + MAX_FILE_SIZE);  
       }  
     } }
			 onFileUpload1(event) {  
     if (event.target.files.length > 0) {  
       this.uploadedFiles1 = event.target.files;  
       this.fileName = event.target.files[1].name;  
       this.file = this.uploadedFiles1[1];  
       if (this.file.size > this.MAX_FILE_SIZE) {  
         alert("File Size Can not exceed" + MAX_FILE_SIZE);  
       }  
     } 
   }  
   saveContact() {  
     this.fileReader = new FileReader();  
     this.fileReader.onloadend = (() => {  
       this.fileContents = this.fileReader.result;  
       let base64 = 'base64,';  
       this.content = this.fileContents.indexOf(base64) + base64.length;  
       this.fileContents = this.fileContents.substring(this.content);  
       this.saveRecord();  
     });  
     this.fileReader.readAsDataURL(this.file);  
   }  
   saveRecord() {  
     var con = {  
       'sobjectType': 'Contact',  
       'LastName': this.name,  
       'Email': this.email,  
       'Phone': this.phone,  
       'Description': this.description  
     }  
     saveRecord({  
       contactRec: con,  
       file: encodeURIComponent(this.fileContents),  
       fileName: this.fileName  
     })  
       .then(conId => {  
         if (conId) {  
           this.dispatchEvent(  
             new ShowToastEvent({  
               title: 'Success',  
               variant: 'success',  
               message: 'Contact Successfully created',  
             }),  
           );  
           this[NavigationMixin.Navigate]({  
             type: 'standard__recordPage',  
             attributes: {  
               recordId: conId,  
               objectApiName: 'Contact',  
               actionName: 'view'  
             },  
           });  
         }  
       }).catch(error => {  
         console.log('error ', error);  
       });  
   }  
 }

 
Dear Folks,

How are you?

I have a scenario to build a page in lightning to show in community to insert a record from custom object with different upload screen. I know that can achievable in flow but for our current requirement i have to build in aura/lwc. If someone can help how to achieve this.

Thank in advanceUser-added image
<template>  
   <div class="slds-box slds-theme_default">  
     <div class="slds-m-around_medium">  
       <lightning-input type="text" label="Name" onchange={onNameChange}></lightning-input>  
       <lightning-input type="tel" label="Phone" onchange={onPhoneChange}></lightning-input>  
       <lightning-input type="email" label="Email" onchange={onEmailChange}></lightning-input>  
       <lightning-textarea name="input3" label="Description" onchange={onDescriptionChange}  
         placeholder="type here..."></lightning-textarea>  
       <lightning-input type="file" onchange={onFileUpload} required name="uploadFile" label="Upload File">  
       </lightning-input>
				 <lightning-input type="file" onchange={onFileUpload1} required name="uploadFile" label="Upload File">  
       </lightning-input>
     </div>  
     <div class="slds-align_absolute-center">    
       <lightning-button label="Save" onclick={saveContact}>  
       </lightning-button>  
     </div>  
   </div>  
 </template>
import { LightningElement, track } from 'lwc';  
 import saveRecord from '@salesforce/apex/ContactController123.saveContact';  
 import { NavigationMixin } from 'lightning/navigation';  
 import { ShowToastEvent } from 'lightning/platformShowToastEvent';  
 const MAX_FILE_SIZE = 100000000; //10mb  
 export default class NewRecordWithFileUpload extends NavigationMixin(LightningElement) {  
   @track name;  
   @track phone;  
   @track email;  
   @track description;  
   uploadedFiles = []; file; fileContents; fileReader; content; fileName  
   onNameChange(event) {  
     this.name = event.detail.value;  
   }
		 uploadedFiles1 = []; file; fileContents; fileReader; content; fileName  
   onNameChange(event) {  
     this.name = event.detail.value;  
   }
   onPhoneChange(event) {  
     this.phone = event.detail.value;  
   }  
   onEmailChange(event) {  
     this.email = event.detail.value;  
   }  
   onDescriptionChange(event) {  
     this.description = event.detail.value;  
   }  
   onFileUpload(event) {  
     if (event.target.files.length > 0) {  
       this.uploadedFiles = event.target.files;  
       this.fileName = event.target.files[0].name;  
       this.file = this.uploadedFiles[0];  
       if (this.file.size > this.MAX_FILE_SIZE) {  
         alert("File Size Can not exceed" + MAX_FILE_SIZE);  
       }  
     } }
			 onFileUpload1(event) {  
     if (event.target.files.length > 0) {  
       this.uploadedFiles1 = event.target.files;  
       this.fileName = event.target.files[1].name;  
       this.file = this.uploadedFiles1[1];  
       if (this.file.size > this.MAX_FILE_SIZE) {  
         alert("File Size Can not exceed" + MAX_FILE_SIZE);  
       }  
     } 
   }  
   saveContact() {  
     this.fileReader = new FileReader();  
     this.fileReader.onloadend = (() => {  
       this.fileContents = this.fileReader.result;  
       let base64 = 'base64,';  
       this.content = this.fileContents.indexOf(base64) + base64.length;  
       this.fileContents = this.fileContents.substring(this.content);  
       this.saveRecord();  
     });  
     this.fileReader.readAsDataURL(this.file);  
   }  
   saveRecord() {  
     var con = {  
       'sobjectType': 'Contact',  
       'LastName': this.name,  
       'Email': this.email,  
       'Phone': this.phone,  
       'Description': this.description  
     }  
     saveRecord({  
       contactRec: con,  
       file: encodeURIComponent(this.fileContents),  
       fileName: this.fileName  
     })  
       .then(conId => {  
         if (conId) {  
           this.dispatchEvent(  
             new ShowToastEvent({  
               title: 'Success',  
               variant: 'success',  
               message: 'Contact Successfully created',  
             }),  
           );  
           this[NavigationMixin.Navigate]({  
             type: 'standard__recordPage',  
             attributes: {  
               recordId: conId,  
               objectApiName: 'Contact',  
               actionName: 'view'  
             },  
           });  
         }  
       }).catch(error => {  
         console.log('error ', error);  
       });  
   }  
 }


 
Dear Folks,

I need your kind help to link task to related object. 

My problem here is task is created when new service tracker is created but it wont link can someone help.

Thanks in Advance
trigger PROServiceTracker on PRO_Service_Tracker__c (before insert, before update) {

    for(PRO_Service_Tracker__c PRO : trigger.new){ 
     
        List<PRO_Service_Tracker__c > PROList = 
            [SELECT id FROM PRO_Service_Tracker__c WHERE 
             (status__C = 'Booked' OR status__C = 'confirmed')   AND Assigned_PRO__c = :PRO.Assigned_PRO__c AND 
             (Start_Date_Time__c = :PRO.Start_Date_Time__c) AND id != :PRO.id];
        
        if(PROList.size() >0 && PRO.status__C != 'cancelled'){
            
            PRO.addError('PRO is already booked on your requested time. ');
     
     
   Id PRORecordTypeId = Schema.SObjectType.Task.getRecordTypeInfosById().get('0124L0000008TaH').getRecordTypeId();
   
   System.debug('PRORecordTypeId'+ PRORecordTypeId); 
    
    List<Task> lTask = new List<Task>();

      if(Trigger.isBefore && trigger.isInsert) {
           for(PRO_Service_Tracker__c PS: Trigger.new) {

               if(PS.Status__c == 'Booked' ){
                // if(lead_rt.get(PS.RecordTypeID).getName() != 'PRO_Service_Task') continue;
                 task t = new Task( 
                 whatID = PS.Id,
                 //whoID = PS.Id,
                 recordtypeId = PRORecordTypeId,
                 Subject = 'PRO Task',
                 Priority = 'High',
                 Status = 'Not Started',
                 ActivityDate = PS.Start_Date__c,
                 Start_Time__c = PS.Start_Time__c,
                 ownerID = PS.Assigned_PRO__c
                 );
                 lTask.add(t);   
               }
            }
          system.debug('Before insert Task'+ lTask);
        insert lTask;
          system.debug('After insert Task'+ lTask);
      }
    
}
           }
      
    }

 
Class
 
@RestResource(urlMapping='/referralplatformopportunity/*')
global with sharing class ReferralOpportunity {
  
    @HttpGet
    global static Opportunity doGet() {
        
        RestRequest request = RestContext.request;
        String oppId = request.requestURI.substring(request.requestURI.lastIndexOf('/')+1);
       /* opportunity result = [SELECT name,stagename,New_Referral_Reward__c,Lead_Id__c,Account_Type__c,Payment_Journal_Reference_Date__c,Product_Family__c,Submission_Opportunity__c,Approval_Opportunity__c,Commission_Opportunity__c FROM opportunity WHERE Lead_Id__c = :oppId LIMIT 1];
        if(result != null)
            return result; */
        Opportunity lateAccount = null;
        List<opportunity> results = [SELECT name,stagename,New_Referral_Reward__c,Lead_Id__c,Account_Type__c,Payment_Journal_Reference_Date__c,Product_Family__c,Submission_Opportunity__c,Approval_Opportunity__c,Commission_Opportunity__c FROM opportunity WHERE Lead_Id__c = :oppId LIMIT 1];
	   if (results.size() > 0)
       {lateAccount = results.get(0);}
        return lateAccount;
              
    }
    
   @HttpPut
   global static String doPut(String accountname, String accountnumber, string bankname,string swiftcode, string iban,string bankcity,string bankbranch,string bankstreet,string bankcountry) {
   RestRequest request = RestContext.request;
   String oppId = request.requestURI.substring(request.requestURI.lastIndexOf('/')+1);
   	   Opportunity thisopportunity = [ Select id,name,Lead_Id__c from opportunity where Lead_Id__c =:oppId];
       thisopportunity.Bank_Account__c = accountname;
       thisopportunity.Account_Number__c = accountnumber;
       thisopportunity.Bank_Name__c = bankname;
       thisopportunity.SWIFT_Code__c = swiftcode;
       thisopportunity.IBAN__c = iban;
       thisopportunity.Bank_City__c = bankcity;
       thisopportunity.Bank_s_Branch__c = bankbranch;
       thisopportunity.Bank_Street__c = bankstreet;
       thisopportunity.Bank_Country__c = bankcountry;
       update thisopportunity;
       return 'Banking details updated';
    }  
}

Test Class
 
@isTest
private class ReferralOpportunityTest {

    @testSetup
    static void dataSetup() {
        
        Account acc = new Account();
        acc.name = 'Bilal Account';
        acc.type = 'prospect';
        insert acc;
        
        Opportunity opp = new Opportunity();
		opp.Name = 'Bilal-Opp';
        opp.CloseDate= System.Today()+30;
        opp.StageName='Engaged';
        opp.AccountId = acc.id;
        insert opp;
        
        
    }

    static testMethod void testGet() {
        Opportunity opp = [ SELECT Id,name FROM Opportunity WHERE Name = 'Bilal-Opp' LIMIT 1 ];
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();             
        req.requestURI = '/services/apexrest/referralplatformopportunity/' + opp.Id;
        req.httpMethod = 'GET';
        RestContext.request = req;
        RestContext.response= res;
        Opportunity oppResp = ReferralOpportunity.doGet();
        system.assertEquals(oppResp.Name, 'Bilal-Opp');
    }
    
    static testMethod void testPut() {
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();             
        req.requestURI = '/services/apexrest/referralplatformopportunity/';
        req.httpMethod = 'PUT';
        RestContext.request = req;
        RestContext.response= res;
        String oppId = ReferralOpportunity.doPut('Mohamed Bilal', 'ABC12567890', 'ABC Bank', 'GH789JA89','ABC780688','Dubai','Downtown','Sheik Zayed St','UAE');
        Opportunity opp = [ SELECT Id, Bank_Account__c, Account_Number__c FROM Opportunity WHERE Id =: oppId ];
        
        system.assertEquals(opp.Bank_Account__c, 'Mohamed Bilal');
        system.assertEquals(opp.Bank_Name__c, 'ABC Bank');
        
        Opportunity opp1 = new Opportunity();
        opp1.New_Referral_Reward__c = 3000;
        opp1.Lead_Id__c = '00Q0C000002m5pmUAA';
        opp1.Bank_Account__c = 'Mohamed Bilal';
        opp1.Account_Number__c = 'ABC12567890';
        opp1.Bank_Name__c = 'ABC Bank';
        opp1.SWIFT_Code__c = 'GH789JA89';
        opp1.IBAN__c = 'ABC780688';
        opp1.Bank_City__c = 'Dubai';
        opp1.Bank_s_Branch__c = 'Downtown';
        update opp1;
    }
    

}

This class passed in sandbox with 95 percentage. But when moved to production shows below error. Please help!!!!


ReferralOpportunityTesttestGetSystem.NullPointerException: Attempt to de-reference a null object
Stack Trace: Class.ReferralOpportunityTest.testGet: line 31, column 1
ReferralOpportunityTesttestPutSystem.QueryException: List has no rows for assignment to SObject
Stack Trace: Class.ReferralOpportunityTest.testPut: line 42, column 1


Thanks in Advance!!!
Please help me to create test class for this.
 
public class FutureReceiptTriggerHandler{

    Public static boolean blnTrigger = false;
    
    public static void sendEmail(set<Id> setFRIds, string strEmailReminder){
        
        List<PDC_Management__c> lstFutureReceipts = [Select Id, Sales_Invoice__r.c2g__Account__r.c2g__CODAInvoiceEmail__c, First_Email_Sent__c, Second_Email_Sent__c, Third_Email_Sent__c from PDC_Management__c where Id IN: setFRIds];
        
        EmailTemplate objEmailTemplate = new EmailTemplate();
        String strOrgURL = URL.getSalesforceBaseUrl().toExternalForm() + '/'; 
        system.debug('*************** strOrgURL == '+strOrgURL);
        String strFirstReminderTemplateId = '';
        String strSecondReminderTemplateId = '';
        String strThirdReminderTemplateId = '';
        
        if(!Test.isRunningTest()){
            if(strOrgURL == 'https://cs78.salesforce.com/'){
                strFirstReminderTemplateId = '00X6E000000FXwy';
                strSecondReminderTemplateId = '00X6E000000FZEK';
                strThirdReminderTemplateId = '00X6E000000FZEK';
            }else if(strOrgURL == 'https://um1.salesforce.com/'){
                strFirstReminderTemplateId = '00XD0000002RTSp';
                strSecondReminderTemplateId = '00XD0000002RTSu';
                strThirdReminderTemplateId = '00XD0000002RTSz';
            }
            
            if(strEmailReminder == 'First Reminder'){
                objEmailTemplate = [Select Id, HtmlValue, Subject from EmailTemplate where Id =: strFirstReminderTemplateId  limit 1];
            }else if(strEmailReminder == 'Second Reminder'){
                objEmailTemplate = [Select Id, HtmlValue, Subject from EmailTemplate where Id =: strSecondReminderTemplateId limit 1];
            }else if(strEmailReminder == 'Third Reminder'){
                objEmailTemplate = [Select Id, HtmlValue, Subject from EmailTemplate where Id =: strThirdReminderTemplateId limit 1];
            }
        }else{
            strFirstReminderTemplateId = 'Reminder_1_Rejected_Cheque_Notice';
            strSecondReminderTemplateId = 'Reminder_2_Rejected_Cheque_Notice_2nd_Reminder';
            strThirdReminderTemplateId = 'Final_Reminder_Rejected_Cheque_Notice_Immediate_action';
            
            if(strEmailReminder == 'First Reminder'){
                objEmailTemplate = [Select Id, HtmlValue, Subject from EmailTemplate where DeveloperName =: strFirstReminderTemplateId  limit 1];
            }else if(strEmailReminder == 'Second Reminder'){
                objEmailTemplate = [Select Id, HtmlValue, Subject from EmailTemplate where DeveloperName =: strSecondReminderTemplateId limit 1];
            }else if(strEmailReminder == 'Third Reminder'){
                objEmailTemplate = [Select Id, HtmlValue, Subject from EmailTemplate where DeveloperName =: strThirdReminderTemplateId limit 1];
            }
        }
        
        system.debug('************** objEmailTemplate == '+objEmailTemplate);
        
        List<OrgWideEmailAddress> lstOWE = [select Id, Address from OrgWideEmailAddress where Address = 'email1@email.ae'];
        
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        
        for(PDC_Management__c objPDC : lstFutureReceipts){
            if(objPDC.Sales_Invoice__r.c2g__Account__r.c2g__CODAInvoiceEmail__c != null){
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                List<String> sendTo = new List<String>();
                sendTo.add(objPDC.Sales_Invoice__r.c2g__Account__r.c2g__CODAInvoiceEmail__c);
                mail.setToAddresses(sendTo);
                
                List<String> sendCC = new List<String>();
                
                sendCC.add('email3@email.ae');
                mail.setCcAddresses(sendCC);
                
                List<String> sendBCC = new List<String>();
                sendBCC.add('email4@email.ae');
                mail.setBccAddresses(sendBCC); 
                
                mail.setHtmlBody(objEmailTemplate.HtmlValue);
                mail.setSubject(objEmailTemplate.Subject);
                mail.setTreatBodiesAsTemplate(true);
                           
                mail.setWhatId(objPDC.Id);
                
                mail.setSaveAsActivity(true);
                
                if(lstOWE.size() > 0){                    
                    mail.setOrgWideEmailAddressId(lstOWE[0].Id);
                }else{
                    mail.setReplyTo('email2@email.ae');
                    mail.setSenderDisplayName('person name');
                }
                mails.add(mail);
                
                if(strEmailReminder == 'First Reminder'){
                    objPDC.First_Email_Sent__c = system.now();
                }else if(strEmailReminder == 'Second Reminder'){
                    objPDC.Second_Email_Sent__c = system.now();
                }else if(strEmailReminder == 'Third Reminder'){
                    objPDC.Third_Email_Sent__c = system.now();
                }            
            }
        }
        Messaging.sendEmail(mails);
        
        UPDATE lstFutureReceipts;
        
    }    
    
    Public static void firstFRRejectUpdateAccountBucket(set<Id> setFRIds){
        List<PDC_Management__c> lstFutureReceipts = [Select Id, Sales_Invoice__r.c2g__Account__c from PDC_Management__c where Id IN: setFRIds];    
        Set<Id> setAccountIds = new Set<Id>();
        
        for(PDC_Management__c objPDC: lstFutureReceipts){
            setAccountIds.add(objPDC.Sales_Invoice__r.c2g__Account__c);
        }
        
        AggregateResult[] groupedRejectedFR =[select count(Id)rejectedFR , Sales_Invoice__r.c2g__Account__c accId 
            from PDC_Management__c where Status__c = 'Rejected' and  Sales_Invoice__r.c2g__Account__c =: setAccountIds 
            group by Sales_Invoice__r.c2g__Account__c];        
        
        Map<String,Integer> mapAccountwithBucketCount = new Map<String,Integer>();
        
        for (AggregateResult ar : groupedRejectedFR)  {
            if( Integer.valueOf(ar.get('rejectedFR')) > 0 && Integer.valueOf(ar.get('rejectedFR')) == 1 ){
                mapAccountwithBucketCount.put(String.ValueOf(ar.get('accId')), Integer.valueOf(ar.get('rejectedFR')));
            }
        }
        
        if(mapAccountwithBucketCount.size() > 0){
            List<Account> lstAccount = [Select Id, Name, Bucket_Start_of_the_month__c from Account where Id IN: setAccountIds];
            
            for(Account objAcc: lstAccount){
                objAcc.Bucket_Start_of_the_month__c = mapAccountwithBucketCount.get(objAcc.Id);
            }
            
            update lstAccount;
        }
    }

    Public static void updateFRTLIN(set<Id> setFRIds){
        
        map<Id,PDC_Management__c> mapTRNTOFR = new map<Id,PDC_Management__c>();
        
        List<PDC_Management__c> lstFutureReceipt = [Select Id, Transaction_Line_Item__c, Amount__c, Is_Open__c  from PDC_Management__c  where Id IN: setFRIds];
        
        for(PDC_Management__c objFR: lstFutureReceipt){
            if(objFR.Transaction_Line_Item__c != null){
                mapTRNTOFR.put(objFR.Transaction_Line_Item__c, objFR);
            }
        }
        
        if(mapTRNTOFR.size() > 0){
            List<c2g__codaTransactionLineItem__c> lstTRNLI = [Select Id, Future_Receipts_1__c from c2g__codaTransactionLineItem__c where Id IN: mapTRNTOFR.keySet()];
            
            if(lstTRNLI.size() > 0){
                for(c2g__codaTransactionLineItem__c objTRNLI: lstTRNLI){
                    if(mapTRNTOFR.get(objTRNLI.Id).Is_Open__c == true){
                        objTRNLI.Future_Receipts_1__c = mapTRNTOFR.get(objTRNLI.Id).Amount__c ;
                    }else{
                        objTRNLI.Future_Receipts_1__c = 0;
                    }
                }
                update lstTRNLI;
            }
            
        }
        
    }
    
}



Thanks in Advance
Can someone help with Test class for below.

Thanks in Advance
 
@RestResource(urlMapping='/referrallead/*')
global with sharing class ReferalProgram {
   
    @HttpGet
    global static lead getLeadById() {
        //  global static opportunity getOpportunityById() {
        RestRequest request = RestContext.request;
        String leadId = request.requestURI.substring(request.requestURI.lastIndexOf('/')+1);
        
        lead result =  [SELECT lastname,firstname,email,Phone,status FROM lead WHERE Id = :leadId]; 
        return result;
    }
    
    @HttpPost
    global static ID createlead(String firstname, String lastname,String email, String phone, String company, String leadsource, String origin, String reffname, String reflname,String rectype) {
        
        lead thislead = new lead();
        List<Lead> leadlist = [select id,lastname,email from lead where email =: email];
        contact thiscontact = new contact();
        List<Contact> conList = [select id,name,email from Contact where email =: email];
        if(leadlist.size() >0 || conList.size() >0){
            thislead.Email.addError('Email already exists');
        }
        else
        thislead.Lastname = lastname;
        thislead.Firstname = firstname;
        thislead.Email = email;
        thislead.Company = company;
        thislead.phone = phone;
        thislead.leadsource = leadsource;
        thislead.origin__c = origin;
        thislead.Referrer_First_Name__c = reffname;
        thislead.Referrer_Last_Name__c = reflname;
        thislead.RecordTypeId = '012D00000007Q8D';
        insert thislead;
        return thislead.Id;
    }

    @HttpPatch
    global static ID updateleadFields() {
        RestRequest request = RestContext.request;
        String leadId = request.requestURI.substring(
            request.requestURI.lastIndexOf('/')+1);
        lead thislead = [SELECT Id FROM lead WHERE Id = :leadId];
        // Deserialize the JSON string into name-value pairs
        Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(request.requestbody.tostring());
        // Iterate through each parameter field and value
        for(String fieldName : params.keySet()) {
            // Set the field and value on the Lead sObject
            thislead.put(fieldName, params.get(fieldName));
        }
        update thislead;
        return thislead.Id;
    }    
}

 
Hello Folks,

I can't post record from workbench. 
Recieving below error message:
System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [LastName]: [LastName] Class.ReferalProgram.createlead: line 35, column 1

Appreaciate any help can provide.
@RestResource(urlMapping='/referrallead/*')
global with sharing class ReferalProgram {
   
    @HttpGet
    global static lead getLeadById() {
        //  global static opportunity getOpportunityById() {
        RestRequest request = RestContext.request;
        String leadId = request.requestURI.substring(request.requestURI.lastIndexOf('/')+1);
        
        lead result =  [SELECT lastname,firstname,email,Phone,status FROM lead WHERE Id = :leadId]; 
        return result;
    }
    
    @HttpPost
    global static ID createlead(String firstname, String lastname,String email, String phone, String company, String leadsource, String origin, String reffname, String reflname,String rectype) {
        
        lead thislead = new lead();
        List<Lead> leadlist = [select id,lastname,email from lead where email =: email];
        contact thiscontact = new contact();
        List<Contact> conList = [select id,name,email from Contact where email =: email];
        if(leadlist.size() >0 || conList.size() >0){
            thislead.Email.addError('Email already exists');
        }
        else
        thislead.Lastname = lastname;
        thislead.Firstname = firstname;
        thislead.Email = email;
        thislead.Company = company;
        thislead.phone = phone;
        thislead.leadsource = leadsource;
        thislead.origin__c = origin;
        thislead.Referrer_First_Name__c = reffname;
        thislead.Referrer_Last_Name__c = reflname;
        thislead.RecordTypeId = '012D00000007Q8D';
        insert thislead;
        return thislead.Id;
    }

    @HttpPatch
    global static ID updateleadFields() {
        RestRequest request = RestContext.request;
        String leadId = request.requestURI.substring(
            request.requestURI.lastIndexOf('/')+1);
        lead thislead = [SELECT Id FROM lead WHERE Id = :leadId];
        // Deserialize the JSON string into name-value pairs
        Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(request.requestbody.tostring());
        // Iterate through each parameter field and value
        for(String fieldName : params.keySet()) {
            // Set the field and value on the Lead sObject
            thislead.put(fieldName, params.get(fieldName));
        }
        update thislead;
        return thislead.Id;
    }    
}

 
Class
 
@RestResource(urlMapping='/referralplatformopportunity/*')
global with sharing class ReferralOpportunity {
  
    @HttpGet
    global static Opportunity doGet() {
        
        RestRequest request = RestContext.request;
        String oppId = request.requestURI.substring(request.requestURI.lastIndexOf('/')+1);
       /* opportunity result = [SELECT name,stagename,New_Referral_Reward__c,Lead_Id__c,Account_Type__c,Payment_Journal_Reference_Date__c,Product_Family__c,Submission_Opportunity__c,Approval_Opportunity__c,Commission_Opportunity__c FROM opportunity WHERE Lead_Id__c = :oppId LIMIT 1];
        if(result != null)
            return result; */
        Opportunity lateAccount = null;
        List<opportunity> results = [SELECT name,stagename,New_Referral_Reward__c,Lead_Id__c,Account_Type__c,Payment_Journal_Reference_Date__c,Product_Family__c,Submission_Opportunity__c,Approval_Opportunity__c,Commission_Opportunity__c FROM opportunity WHERE Lead_Id__c = :oppId LIMIT 1];
	   if (results.size() > 0)
       {lateAccount = results.get(0);}
        return lateAccount;
              
    }
    
   @HttpPut
   global static String doPut(String accountname, String accountnumber, string bankname,string swiftcode, string iban,string bankcity,string bankbranch,string bankstreet,string bankcountry) {
   RestRequest request = RestContext.request;
   String oppId = request.requestURI.substring(request.requestURI.lastIndexOf('/')+1);
   	   Opportunity thisopportunity = [ Select id,name,Lead_Id__c from opportunity where Lead_Id__c =:oppId];
       thisopportunity.Bank_Account__c = accountname;
       thisopportunity.Account_Number__c = accountnumber;
       thisopportunity.Bank_Name__c = bankname;
       thisopportunity.SWIFT_Code__c = swiftcode;
       thisopportunity.IBAN__c = iban;
       thisopportunity.Bank_City__c = bankcity;
       thisopportunity.Bank_s_Branch__c = bankbranch;
       thisopportunity.Bank_Street__c = bankstreet;
       thisopportunity.Bank_Country__c = bankcountry;
       update thisopportunity;
       return 'Banking details updated';
    }  
}

Test Class
 
@isTest
private class ReferralOpportunityTest {

    @testSetup
    static void dataSetup() {
        
        Account acc = new Account();
        acc.name = 'Bilal Account';
        acc.type = 'prospect';
        insert acc;
        
        Opportunity opp = new Opportunity();
		opp.Name = 'Bilal-Opp';
        opp.CloseDate= System.Today()+30;
        opp.StageName='Engaged';
        opp.AccountId = acc.id;
        insert opp;
        
        
    }

    static testMethod void testGet() {
        Opportunity opp = [ SELECT Id,name FROM Opportunity WHERE Name = 'Bilal-Opp' LIMIT 1 ];
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();             
        req.requestURI = '/services/apexrest/referralplatformopportunity/' + opp.Id;
        req.httpMethod = 'GET';
        RestContext.request = req;
        RestContext.response= res;
        Opportunity oppResp = ReferralOpportunity.doGet();
        system.assertEquals(oppResp.Name, 'Bilal-Opp');
    }
    
    static testMethod void testPut() {
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();             
        req.requestURI = '/services/apexrest/referralplatformopportunity/';
        req.httpMethod = 'PUT';
        RestContext.request = req;
        RestContext.response= res;
        String oppId = ReferralOpportunity.doPut('Mohamed Bilal', 'ABC12567890', 'ABC Bank', 'GH789JA89','ABC780688','Dubai','Downtown','Sheik Zayed St','UAE');
        Opportunity opp = [ SELECT Id, Bank_Account__c, Account_Number__c FROM Opportunity WHERE Id =: oppId ];
        
        system.assertEquals(opp.Bank_Account__c, 'Mohamed Bilal');
        system.assertEquals(opp.Bank_Name__c, 'ABC Bank');
        
        Opportunity opp1 = new Opportunity();
        opp1.New_Referral_Reward__c = 3000;
        opp1.Lead_Id__c = '00Q0C000002m5pmUAA';
        opp1.Bank_Account__c = 'Mohamed Bilal';
        opp1.Account_Number__c = 'ABC12567890';
        opp1.Bank_Name__c = 'ABC Bank';
        opp1.SWIFT_Code__c = 'GH789JA89';
        opp1.IBAN__c = 'ABC780688';
        opp1.Bank_City__c = 'Dubai';
        opp1.Bank_s_Branch__c = 'Downtown';
        update opp1;
    }
    

}

This class passed in sandbox with 95 percentage. But when moved to production shows below error. Please help!!!!


ReferralOpportunityTesttestGetSystem.NullPointerException: Attempt to de-reference a null object
Stack Trace: Class.ReferralOpportunityTest.testGet: line 31, column 1
ReferralOpportunityTesttestPutSystem.QueryException: List has no rows for assignment to SObject
Stack Trace: Class.ReferralOpportunityTest.testPut: line 42, column 1


Thanks in Advance!!!
Can someone help with Test class for below.

Thanks in Advance
 
@RestResource(urlMapping='/referrallead/*')
global with sharing class ReferalProgram {
   
    @HttpGet
    global static lead getLeadById() {
        //  global static opportunity getOpportunityById() {
        RestRequest request = RestContext.request;
        String leadId = request.requestURI.substring(request.requestURI.lastIndexOf('/')+1);
        
        lead result =  [SELECT lastname,firstname,email,Phone,status FROM lead WHERE Id = :leadId]; 
        return result;
    }
    
    @HttpPost
    global static ID createlead(String firstname, String lastname,String email, String phone, String company, String leadsource, String origin, String reffname, String reflname,String rectype) {
        
        lead thislead = new lead();
        List<Lead> leadlist = [select id,lastname,email from lead where email =: email];
        contact thiscontact = new contact();
        List<Contact> conList = [select id,name,email from Contact where email =: email];
        if(leadlist.size() >0 || conList.size() >0){
            thislead.Email.addError('Email already exists');
        }
        else
        thislead.Lastname = lastname;
        thislead.Firstname = firstname;
        thislead.Email = email;
        thislead.Company = company;
        thislead.phone = phone;
        thislead.leadsource = leadsource;
        thislead.origin__c = origin;
        thislead.Referrer_First_Name__c = reffname;
        thislead.Referrer_Last_Name__c = reflname;
        thislead.RecordTypeId = '012D00000007Q8D';
        insert thislead;
        return thislead.Id;
    }

    @HttpPatch
    global static ID updateleadFields() {
        RestRequest request = RestContext.request;
        String leadId = request.requestURI.substring(
            request.requestURI.lastIndexOf('/')+1);
        lead thislead = [SELECT Id FROM lead WHERE Id = :leadId];
        // Deserialize the JSON string into name-value pairs
        Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(request.requestbody.tostring());
        // Iterate through each parameter field and value
        for(String fieldName : params.keySet()) {
            // Set the field and value on the Lead sObject
            thislead.put(fieldName, params.get(fieldName));
        }
        update thislead;
        return thislead.Id;
    }    
}

 
Hello Folks,

I can't post record from workbench. 
Recieving below error message:
System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [LastName]: [LastName] Class.ReferalProgram.createlead: line 35, column 1

Appreaciate any help can provide.
@RestResource(urlMapping='/referrallead/*')
global with sharing class ReferalProgram {
   
    @HttpGet
    global static lead getLeadById() {
        //  global static opportunity getOpportunityById() {
        RestRequest request = RestContext.request;
        String leadId = request.requestURI.substring(request.requestURI.lastIndexOf('/')+1);
        
        lead result =  [SELECT lastname,firstname,email,Phone,status FROM lead WHERE Id = :leadId]; 
        return result;
    }
    
    @HttpPost
    global static ID createlead(String firstname, String lastname,String email, String phone, String company, String leadsource, String origin, String reffname, String reflname,String rectype) {
        
        lead thislead = new lead();
        List<Lead> leadlist = [select id,lastname,email from lead where email =: email];
        contact thiscontact = new contact();
        List<Contact> conList = [select id,name,email from Contact where email =: email];
        if(leadlist.size() >0 || conList.size() >0){
            thislead.Email.addError('Email already exists');
        }
        else
        thislead.Lastname = lastname;
        thislead.Firstname = firstname;
        thislead.Email = email;
        thislead.Company = company;
        thislead.phone = phone;
        thislead.leadsource = leadsource;
        thislead.origin__c = origin;
        thislead.Referrer_First_Name__c = reffname;
        thislead.Referrer_Last_Name__c = reflname;
        thislead.RecordTypeId = '012D00000007Q8D';
        insert thislead;
        return thislead.Id;
    }

    @HttpPatch
    global static ID updateleadFields() {
        RestRequest request = RestContext.request;
        String leadId = request.requestURI.substring(
            request.requestURI.lastIndexOf('/')+1);
        lead thislead = [SELECT Id FROM lead WHERE Id = :leadId];
        // Deserialize the JSON string into name-value pairs
        Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(request.requestbody.tostring());
        // Iterate through each parameter field and value
        for(String fieldName : params.keySet()) {
            // Set the field and value on the Lead sObject
            thislead.put(fieldName, params.get(fieldName));
        }
        update thislead;
        return thislead.Id;
    }    
}