• trailhead solutions 10
  • NEWBIE
  • 30 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 9
    Questions
  • 11
    Replies
Hello All

Please find the below,   controller and a part of VF Page. Here the refresh not working when User clicks on Verify Asset button, the new one , which User has to enter is populating 3 Fields (Location, Warranty, Date) with the Previous entered Values. Please someone help in change of code or where have to change to get empty of those 3 fields on addition of new?

Thanks in Advance!
TrialHead Aspirant

VF Page:
========

 <apex:outputPanel rendered="{!renderAddAsset}">
                
                Model Number:<apex:inputText value="{!modelNumber}"/> 
                Serial Number:<apex:inputText value="{!serialNumber}"/>
                Install Date:<apex:input value="{!installDate}" 
                    html-placeholder="Install Date" 
                                              type="date"/>
                <apex:selectList label="Fields" value="{!selectedLocationId}" multiselect="false" size="1" >
                     <apex:selectOptions value="{!LocationSelections}" />
                </apex:selectList>
                In Warranty?<apex:selectList id="WarrantyStatusId" value="{!WarrantyStatus}" size="1">
                    <apex:selectOption itemValue="true" itemLabel="Yes"/>
                    <apex:selectOption itemValue="false" itemLabel="No"/>
                </apex:selectList> 
                 <apex:commandButton action="{!verifyAsset}" value="Verify Asset" reRender="apexform" status="spinnerStatus" styleclass="slds-button slds-button_brand"/>
                 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <apex:commandButton action="{!cancelAddAsset}" value="Cancel" reRender="apexform" status="spinnerStatus" styleclass="slds-button slds-button_brand"/>
            </apex:outputPanel>

Controller:
============
public PageReference verifyAsset(){
        resetError();
        Boolean hasErrors = false;
       
        
        if(modelNumber == '' || modelNumber == null){
            apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,'Please enter model number.')); 
            hasErrors = true;
        }
        if(selectedLocationId == 'Select service location' ){
            apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,'Please select a location.')); 
            hasErrors = true;
        }
        if(!string.isBlank(modelNumber)  && !modelNumber.isAlphanumeric() ){
            apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,'Model Number can only contain alphanumeric characters.')); 
            hasErrors = true;
        }
        if(hasErrors){
            assetError = true;
            return null;
        }
        User-added image
Hello All
The test class for the below Apex Rest API with Http Patch Method is failing and at 0% Code Coverage. Can someone please help to complete this in order to deploy to Production.

Apex Class:
@RestResource(urlMapping='/opportunityiWiseUpdate/*')
global class opportunityiWiseUpdate {
    public class responseWrapper{
      public id SalesForceId;
      public Date EffectiveDate;
      public string stage;
      //public date closedate;
      public Decimal ContractValue;
      }

    @httppatch
      global Static string fetchopportunity(){
      RestRequest req = RestContext.request;
      RestResponse res = Restcontext.response;
          system.debug('req : ' + req);
      string jsonString=req.requestBody.tostring();
          system.debug(jsonString);
      responseWrapper wResp=(responseWrapper) JSON.deserialize(jsonString,responseWrapper.class);
          system.debug('wResp : ' + wResp);
         
          for(opportunity op : [select id,recordtype.name,stagename,closedate,Amount,TCV__c from opportunity 
                                where id =:wResp.SalesForceId ]){
          system.debug('op : ' + op);
         // if(op.id !=null){
              if(op.recordtype.Name=='HOS'){
               op.Id = wResp.SalesForceId;
               op.Amount = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
               else if(op.recordtype.Name=='IBS'){
               op.Id = wResp.SalesForceId;
               op.TCV__C = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
          }
             
          return 'sucess';
      }
       
}

Test Class:
@isTest
global class opportunityiWiseUpdateTest {
   @testsetup
    static void datasetup(){ 
       
        String strRecordTypeId = [Select Id From RecordType Where SobjectType = 'Account' and Name = 'IBS'].Id;
    Account a = new Account();
            a.Name = 'EXPEDIA';
            a.Segment__c = 'Aviation';
            a.Sub_Segment__c = 'Startup';
            a.IBS_Region__c = 'IBSZ';
            a.IBS_Sub_Region__c = 'ANZ';
            a.Account_Domain_Name__c = 'test.com';
            a.Account_Code__c='MIII';
            a.Approved__c = True;
            a.RecordTypeId=strRecordTypeId;
            insert a;
    
    String strRecordTypeId1 = [Select Id From RecordType Where SobjectType = 'Opportunity' and Name = 'IBS'].Id;
           Opportunity o = new Opportunity();
                
            o.Name = 'Test Opportunity ibs';
            o.AccountId = a.Id;
           // o.Opportunity_Name__c = 'Test Record';
            o.Contract_Type__c = 'CDx Services';
            o.TCV__c = 5000;
            o.CloseDate = system.today();
            o.Type_of_Deal__c = 'CR';
            o.Opportunity_Source__c = 'Other';
                o.Type_of_Proposal__c='RFP';
            o.StageName = 'Closed Won';
           o.IBS_Lob__c = 'Adopt - ADOPT';
                o.Reason_for_Closed_Won__c='Pricing';
           o.Products__c = 'iFlight Crew Planning Classic';
            o.Incumbent__c = 'Sabre';
           o.Tenure__c = 6;
            o.Tenure_Unit_of_Measure__c = 'Years';
           o.One_Time_Fee__c = 5000;
            o.Reason_for_Winning_or_Losing__c ='Pricing';
            o.Annual_Recurring_Revenue__c = 100001;
            o.RecordTypeId=strRecordTypeId1;
            insert o;
            
     
                
    String strRecordTypeIda1 = [Select Id From RecordType Where SobjectType = 'Account' and Name = 'HOS'].Id;
    Account a1 = new Account();
            a1.Name = 'EXPEDIA1';
            a1.Type='Prospect';
            a1.Industry='Supply';
            a1.RecordTypeId=strRecordTypeIda1;
            insert a1;
    
    String strRecordTypeIdo1 = [Select Id From RecordType Where SobjectType = 'Opportunity' and Name = 'HOS'].Id;
           Opportunity o1 = new Opportunity();
                
            o1.Name = 'Test Opportunity';
            o1.AccountId = a1.Id;
           // o1.Opportunity_Name__c = 'Test Record';
            o1.StageName = 'Closed Won';
            o1.Category__c='CORE';
            o1.Type='Supply - Accom';
            o1.CloseDate = system.today();
            o1.Amount=8520;
            o1.Term__c=5;
            o1.Implementation_Fee__c=58;
            o1.Ramp_to_Live__c=5;
            o1.Ramp_to_Maturity__c=6;
            o1.Probability=10;
            o1.Finance_TCV_Stage__c='Initial - 10%';
            o1.Lead_Generation_Date__c=system.today();
            o1.RecordTypeId=strRecordTypeIdo1;
            insert o1;
    }
    
       @isTest
   static void updateBOClassMethod(){
   Test.startTest();
 Opportunity sHOppRec= [SELECT Id,Name,recordtype.DeveloperName,StageName,CloseDate,Amount From Opportunity Where Name ='Test Opportunity' Limit 1];
system.debug('sHOppRec : ' + sHOppRec);        
   SingleRequestMock fakeResponse1 = new SingleRequestMock(sHOppRec.Id,22500,
                                                
                                                 'Contracted',
                                                 system.today()+1
                                                   );
    String JsonMsg=JSON.serialize(fakeResponse1);
        system.debug('JsonMsg : ' + JsonMsg);
   RestRequest req = new RestRequest(); 
   RestResponse res = new RestResponse();

    req.requestURI = '/services/apexrest/DemoUrl';  //Request URL
    req.httpMethod = 'PATCH';//HTTP Request Type
    req.requestBody = Blob.valueof(JsonMsg);
    RestContext.request = req;
    RestContext.response= res; 
   opportunityiWiseUpdate.fetchopportunity();
    Test.stopTest();
}
    
    
    
 @isTest
    static void updateBOClassMethod1(){
   Test.startTest();
 Opportunity sIOppRec= [SELECT Id,Name,recordtype.Name,StageName,CloseDate,TCV__c From Opportunity Where Name ='Test Opportunity ibs' Limit 1];
        system.debug('sIOppRec : ' + sIOppRec);
   SingleRequestMock fakeResponse1 = new SingleRequestMock(sIOppRec.Id,82503,
                                               
                                                 'Contracted',
                                                 system.today()+2
                                                   );
    String JsonMsg=JSON.serialize(fakeResponse1);
        system.debug('JsonMsg : ' + JsonMsg);
   RestRequest req = new RestRequest(); 
   RestResponse res = new RestResponse();

    req.requestURI = '/services/apexrest/DemoUrl';  //Request URL
    req.httpMethod = 'PUT';//HTTP Request Type
    req.requestBody = Blob.valueof(JsonMsg);
    RestContext.request = req;
    RestContext.response= res;
   opportunityiWiseUpdate.fetchopportunity();
    Test.stopTest();
}
 public class SingleRequestMock {
        
      public id SalesForceId;
      public Date EffectiveDate;
      public string stage;
     // public date closedate;
      public Decimal ContractValue;
        
            public SingleRequestMock(id SalesForceId, Decimal ContractValue, string stage,Date EffectiveDate) {
            this.SalesForceId = SalesForceId;
            this.EffectiveDate = EffectiveDate;
            this.stage = stage;
            this.ContractValue = ContractValue;
        }
    }
  
}

Thanks in Advance!
Hello Everyone

Can someone help me on how to test PUT Method from Postman to Salesforce, instance URL generated from all details like Client Id, Secret, test URL, Username, Password. After getting instance URL, how to connect with SF Org endpoint URL? Confused on PUT Method. Someone Please Share.

Thanks in Advance
TH Aspirant

 
Hello

Please someone help me in writing test class for this class rest api for Http put.  My Test Class is failing at 20%.

Thanks in Advance
SF Aspirant

@RestResource(urlMapping='/opportunityiWiseUpdate/*')
Global class opportunityiWiseUpdate {
    global class responseWrapper{
       global id SalesForceId;
       global Date EffectiveDate;
       global string stage;
       global date closedate;
       global Decimal ContractValue;
      }

    @httpput
      global Static string fetchopportunity(){
      RestRequest req = RestContext.request;
      RestResponse res = Restcontext.response;
      string jsonString=req.requestBody.tostring();
          system.debug(jsonString);
      responseWrapper wResp=(responseWrapper) JSON.deserialize(jsonString,responseWrapper.class);
          //system.debug(wResp);
          //string id = wResp.Id;
         // system.debug(id);
     
      opportunity op = [select id,recordtype.name,stagename,closedate,Amount,TCV__c from opportunity where id =:wResp.SalesForceId ];
          
          if(op.id !=null){
              if(op.recordtype.Name=='H'){
               op.Id = wResp.SalesForceId;
               op.Amount = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
               else if(op.recordtype.Name=='I'){
               op.Id = wResp.SalesForceId;
               op.TCV__C = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
          }
             
          return 'sucess';
      }
       
}



My Test Class:
@istest
public class TestUpdateBOfromiwise {
 @testsetup
    static void datasetup(){

        Profile p =[SELECT ID FROM Profile Where Name='System Administrator'];
        
        User u = new User();
        u.Alias = 'standt1';
        u.Email='sauser1@testorg.com';
        u.EmailEncodingKey='UTF-8'; 
        u.LastName='Testing1';
        u.LanguageLocaleKey='en_US';
        u.LocaleSidKey='en_US';
        u.ProfileId = p.Id;
        u.TimeZoneSidKey='America/Los_Angeles';
        u.UserName='sauser1@testorg.com';
        u.Head_Of_Region__c = 'IBSZ';
        insert u;
        
        Account a = new Account();
        a.Name = 'Test Account';
        a.Segment__c = 'Aviation';
        a.Sub_Segment__c = 'Startup';
        a.IBS_Region__c = 'IBSZ';
        a.IBS_Sub_Region__c = 'ANZ';
        a.Account_Domain_Name__c = 'test.com';
        a.Account_Code__c='Test';
        a.Approved__c = True;
        insert a;
        
        Opportunity o = new Opportunity();
        o.Name = 'Test Opportunity';
        o.AccountId = a.Id;
        o.Opportunity_Name__c = 'Test Record';
        o.Contract_Type__c = 'CDx Services';
        o.TCV__c = 5000;
        o.CloseDate = system.today();
        o.Type_of_Deal__c = 'New Deal';
        o.Opportunity_Source__c = 'Other';
        o.StageName = 'SQL';
        o.IBS_Lob__c = 'Aviation Passenger Solutions - APS';
        o.Products__c = 'iFly Res';
        o.Incumbent__c = 'Sabre';
        o.Tenure__c = 6;
        o.Tenure_Unit_of_Measure__c = 'Years';
        o.One_Time_Fee__c = 5000;
        o.Annual_Recurring_Revenue__c = 100001;
        insert o;
        
         string name='nalini';
    }
       @isTest
    static void updateBOClassMethod(){
         
        Test.startTest();

   RestRequest req = new RestRequest(); 
   RestResponse res = new RestResponse();

    req.requestURI = '/services/apexrest/DemoUrl';  //Request URL
    req.httpMethod = 'POST';//HTTP Request Type
  
    RestContext.request = req;
    RestContext.response= res;
 
   opportunityiWiseUpdate.fetchopportunity();
    Test.stopTest();
}
}
 
Hello

The below trigger is working fine if not putting or differentiating with   record types. Please help whether this is in right format to get fire?

Thanks in Advance
SF Aspirant


trigger sendDatatoWiseApi on Opportunity (after update) {
 
    Trigger_Setting__mdt    triggr = [Select Trigger_Name__c,Active__c from Trigger_Setting__mdt where Trigger_Name__c ='iWise Trigger' ];

  if(triggr.Active__c == TRUE){
    set<id> oppIds = new set<id>();
    if(shouldIRun.canIRun())
   {
    for(Opportunity op : trigger.new){
        if(op.recordtype.Name=='H'){
        if(op.StageName=='Closed Won'  || 
           (trigger.oldMap.get(op.Id).Response_from_iWise_System__c==null && op.Response_from_iWise_System__c!=null && 
            op.Response_from_iWise_System__c.containsIgnoreCase('Error'))){
            oppIds.add(op.Id);
        }
    
    if(oppIds.size()>0)
        
        calliwisehos.sendBoToIwise(oppIds); 
    }
        if(op.recordtype.Name=='I'){
        if(op.StageName=='Closed Won'  || 
           (trigger.oldMap.get(op.Id).Response_from_iWise_System__c==null && op.Response_from_iWise_System__c!=null && 
            op.Response_from_iWise_System__c.containsIgnoreCase('Error'))){
            oppIds.add(op.Id);
        }
    
    if(oppIds.size()>0)
        callIwiseAPI.sendBoToIwise(oppIds); 
       //calliwisehos.sendBoToIwise(oppIds);
    }  
    }
   }
  }
}
 
Hello

Please someone help how to cover the test class and code coverage for the below rest api class?

Thanks in Advance
TH

public class callIwiseAPI {

    //To capture getOauthToken response
    public class tokenResponse{
        public string access_token;
    }
  
  public class OpptyInput{
    String SalesForceId;
        string OpportunityType;
    String Lob;
    String Product;
    String Region;
        String SubRegion;
    String BOTitle;
  //  String BType;
    String DealNature;
  //  String BOCurrency;
    Decimal ContractValue;
    Date EffectiveDate;
    Decimal ContractDuration;
    String ContractDurationUnitOfMesurement;
  //  String AccountCode;
    String Description;
    String SalesPerson1;
    String CreatedBy;
        string ProspectName;
        String ContactPerson;
        String ContactNumber;
        String Competitors;
        String ContactEmail;
        String JobTitle;
        String AccountName;

  }
/******************************************************************************************************************
Method      : getOauthToken
Parameters  : # 
ReturnType  : object
Description : Calling iWise API to get oAuth Token and pass the same token get the BO data
*******************************************************************************************************************/
    public  String getOauthToken(){
        String oAuthToken;
        tokenResponse atResponse = new tokenResponse();
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('callout:iWise_Credentials/token');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json; charset=utf-8');
        request.setHeader('username', '{!$Credential.Username}');
        request.setHeader('password', '{!$Credential.Password}');
        request.setHeader('grant_type', 'password');
    
        System.debug('Request to get oAuth Token:'+request);
        
    
        HttpResponse response = http.send(request);
        system.debug('Response from iWise for OAUTH Token:::'+response.toString());
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 201 || response.getStatusCode() == 200) {
            // Deserialize the JSON string into collections of primitive data types.
            //Map<String, object> results = (Map<String, object>) JSON.deserializeUntyped(response.getBody());
            system.debug(':::: Response::::'+response.getBody());
            atResponse = (tokenResponse)json.deserialize(response.getBody(),tokenResponse.class);
            // get the oAuth tken from the response
            
            oAuthToken = atResponse.access_token;//(String) results.get('access_token');
            System.debug('OAuth Acces Token from response:'+oAuthToken);
            return oAuthToken;
            
        }
        else{
            System.debug('The status code returned was not expected: ' +
            response.getStatusCode() + ' ' + response.getStatus());
            return oAuthToken;
        }
        
    }
    
/******************************************************************************************************************
Method      : sendBoToIwise
Parameters  : oAuthToken 
ReturnType  : object
Description : Calling iWise API to send the BO
*******************************************************************************************************************/
  @future(callout = true)
    public static void sendBoToIwise(set<id> oppIds){
//    system.debug('this');
    list<Opportunity> opty = new list<Opportunity>();
       String oAuthToken;
        
    
    opty = [select Id,Name,TCV__c,IBS_Lob__c,Contract_Type__c,Competitors_Names__c,Products__c,CloseDate,Type_of_Deal__c,Tenure_Unit_of_Measure__c,Tenure__c,Description,Owner.Name,Owner.Email,Account__r.Account_Code__c,Response_from_iWise_System__c,Account.Name,
                ( SELECT contact.firstName,contact.phone,contact.Email,contact.Title,contact.IBS_Region__c,contact.IBS_Sub_Region__c FROM OpportunityContactRoles ),
                (select Name,TeamMemberRole,User.Name,User.Email   from OpportunityTeamMembers where  TeamMemberRole = 'Sales Rep')
                                                from Opportunity where Id IN : oppIds];
            system.debug(opty);
       list<OpptyInput> inputRequest = new list<OpptyInput>();
        callIwiseAPI obj = new callIwiseAPI();
        oAuthToken = obj.getOauthToken();
    if(!opty.isEmpty()){
      for(Opportunity op : opty){
        OpptyInput reqInput  = new OpptyInput();
        reqInput.BOTitle=op.Name;
        reqInput.SalesForceId=op.Id;
                reqInput.OpportunityType=op.Type_of_Deal__c;
        reqInput.Lob = op.IBS_Lob__c;
        reqInput.Product=op.Products__c;
        reqInput.Region=op.OpportunityContactRoles[0].contact.IBS_Region__c;
        reqInput.SubRegion=op.OpportunityContactRoles[0].contact.IBS_Sub_Region__c;
      //  reqInput.BType = 'New BO';
        reqInput.DealNature = op.Contract_Type__c;
      //  reqInput.BOCurrency = 'USD';
        reqInput.ContractValue = op.TCV__c;
                reqInput.EffectiveDate = op.CloseDate;
        reqInput.ContractDuration = op.Tenure__c;
        reqInput.ContractDurationUnitOfMesurement = op.Tenure_Unit_of_Measure__c ;
      //  reqInput.AccountCode= op.Account__r.Account_Code__c;
      //  reqInput.Description= op.Description;
        reqInput.SalesPerson1 =op.OpportunityTeamMembers[0].User.Email;
        reqInput.CreatedBy=op.Owner.Email;
                reqInput.ProspectName= op.Account.Name;
                reqInput.ContactPerson=op.OpportunityContactRoles[0].contact.firstName;
                reqInput.ContactNumber=op.OpportunityContactRoles[0].contact.phone;
                reqInput.Competitors=op.Competitors_Names__c;
                reqInput.ContactEmail = op.OpportunityContactRoles[0].contact.Email;
                reqInput.JobTitle=op.OpportunityContactRoles[0].contact.Title;
                reqInput.AccountName=op.Account.Name;

      inputRequest.add(reqInput);
      
      } 
    }
    String OpportunityInput = Json.serialize(inputRequest);
    System.debug('Input request to send Opportunity to iWise::'+OpportunityInput); 
    Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('Actual Endpoint to service');// also add this endpoint in remote site settings
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json; charset=utf-8');
        request.setHeader('Authorization', oAuthToken);
    request.setBody(OpportunityInput);
    
    System.debug('Request to send Opportunity:'+request);
    System.debug('Request body send Opportunity:'+request.getBody());
    
    HttpResponse response = http.send(request);
        system.debug('Response from iWise for Get Opportunity request:::'+response.toString());
    system.debug('Response from iWise for Get Opportunity request:::'+response.getBody());
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 200) {
      System.debug('Success Response from iWise::'+response.getStatus());
        opty[0].Response_from_iWise_System__c=response.getStatusCode()+' - '+response.getStatus()+' - '+ response.getBody();
    }
    else{
      System.debug('Error Response from iWise::'+response.getStatus());
      opty[0].Response_from_iWise_System__c=response.getStatusCode()+' - '+response.getStatus()+' - '+ response.getBody();
    }
    if(!opty.isEmpty())
      Update opty;  
  }
}
Hello

I have my Salesforce.com Certified Administrator and Certified PD 1credential, and would like to gain more experience in the field.

I am having 1 Yr Exp in Salesforce Admin and Development.

I am located in Hyderabad, India. I am ready to contribute my time in delivering the Salesforce Project in my free time for free.

Appreciate any leads or any direction you can give.

Sincerely,
Nalini
srinalini.ch@gmail.com
Hello

I have added apex class and VF Page to override standard convert button to Accept Button. The mentioned below code is working fine. But it is getting converted in Classic Version. But need the lead Conversion Page in Lightning Version. Anyone Please suggest.

public class AutoConvertLeads {
    
    private final Lead lead; //variable for the standard Lead object
    
    public AutoConvertLeads(ApexPages.StandardController standardPageController) {
        this.lead = (Lead)standardPageController.getRecord(); //initialize the standard controller
    }
    
    public PageReference redirectToConvertionPage() {
        PageReference nextPage = new PageReference('/lead/leadconvert.jsp'); //set the starting point for the page reference to which the User will be sent
        nextPage = encodeAndSetParam(nextPage, 'retURL', lead.Id); //set the retURL parameter in order to allow for returning to Lead if User cancels from page
        nextPage = encodeAndSetParam(nextPage, 'id', lead.Id); //set the id parameter so that the conversion page knows the proper record
        nextPage = encodeAndSetParam(nextPage, 'nooppti', '1'); //set the nooppti parameter to pre-populate the "Do not create a new opportunity upon conversion." checkbox
        nextPage = encodeAndSetParam(nextPage, 'nooverride', '1'); //set the nooverride parameter in order to prevent looping in the user interface
        nextPage.setRedirect(true); //indicate that the redirect should be performed on the client side
        return nextPage; //send the User to the Lead conversion page
    }
    
    public PageReference encodeAndSetParam(PageReference passedPageReference, String passedParameterId, String passedParameterValue){
        if (passedParameterValue != null) { //if the passedParameterValue is not null
            String encodedParameterValue = EncodingUtil.urlEncode(passedParameterValue, 'UTF-8'); //encode the value that was passed to eliminate conflicts with unsafe characters
            passedPageReference.getParameters().put(passedParameterId, EncodingUtil.urlDecode(encodedParameterValue, 'UTF-8')); //add the parameter to the page reference
        }
        return passedPageReference;
    }

}

Visual Force Page:

<apex:page action="{!redirectToConvertionPage}" extensions="AutoConvertLeads" standardController="Lead">
    <apex:sectionHeader title="Accept" subtitle="{!Lead.Name}" help="/htviewhelpdoc?id=leads_convert.htm&siteLang=en_US"></apex:sectionHeader>
    <apex:pageMessages ></apex:pageMessages>
</apex:page>


Thanks
TS

 
Hello

I have a custom button. On clicking on that, a field update with checkbox true has to be done. How this can be done with Apex and VF. Any code, Please suggest.

Thanks
TS
Hello All

Please find the below,   controller and a part of VF Page. Here the refresh not working when User clicks on Verify Asset button, the new one , which User has to enter is populating 3 Fields (Location, Warranty, Date) with the Previous entered Values. Please someone help in change of code or where have to change to get empty of those 3 fields on addition of new?

Thanks in Advance!
TrialHead Aspirant

VF Page:
========

 <apex:outputPanel rendered="{!renderAddAsset}">
                
                Model Number:<apex:inputText value="{!modelNumber}"/> 
                Serial Number:<apex:inputText value="{!serialNumber}"/>
                Install Date:<apex:input value="{!installDate}" 
                    html-placeholder="Install Date" 
                                              type="date"/>
                <apex:selectList label="Fields" value="{!selectedLocationId}" multiselect="false" size="1" >
                     <apex:selectOptions value="{!LocationSelections}" />
                </apex:selectList>
                In Warranty?<apex:selectList id="WarrantyStatusId" value="{!WarrantyStatus}" size="1">
                    <apex:selectOption itemValue="true" itemLabel="Yes"/>
                    <apex:selectOption itemValue="false" itemLabel="No"/>
                </apex:selectList> 
                 <apex:commandButton action="{!verifyAsset}" value="Verify Asset" reRender="apexform" status="spinnerStatus" styleclass="slds-button slds-button_brand"/>
                 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <apex:commandButton action="{!cancelAddAsset}" value="Cancel" reRender="apexform" status="spinnerStatus" styleclass="slds-button slds-button_brand"/>
            </apex:outputPanel>

Controller:
============
public PageReference verifyAsset(){
        resetError();
        Boolean hasErrors = false;
       
        
        if(modelNumber == '' || modelNumber == null){
            apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,'Please enter model number.')); 
            hasErrors = true;
        }
        if(selectedLocationId == 'Select service location' ){
            apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,'Please select a location.')); 
            hasErrors = true;
        }
        if(!string.isBlank(modelNumber)  && !modelNumber.isAlphanumeric() ){
            apexpages.addMessage(new ApexPages.message(Apexpages.Severity.ERROR,'Model Number can only contain alphanumeric characters.')); 
            hasErrors = true;
        }
        if(hasErrors){
            assetError = true;
            return null;
        }
        User-added image
Hello Everyone

Can someone help me on how to test PUT Method from Postman to Salesforce, instance URL generated from all details like Client Id, Secret, test URL, Username, Password. After getting instance URL, how to connect with SF Org endpoint URL? Confused on PUT Method. Someone Please Share.

Thanks in Advance
TH Aspirant

 
Hello

Please someone help me in writing test class for this class rest api for Http put.  My Test Class is failing at 20%.

Thanks in Advance
SF Aspirant

@RestResource(urlMapping='/opportunityiWiseUpdate/*')
Global class opportunityiWiseUpdate {
    global class responseWrapper{
       global id SalesForceId;
       global Date EffectiveDate;
       global string stage;
       global date closedate;
       global Decimal ContractValue;
      }

    @httpput
      global Static string fetchopportunity(){
      RestRequest req = RestContext.request;
      RestResponse res = Restcontext.response;
      string jsonString=req.requestBody.tostring();
          system.debug(jsonString);
      responseWrapper wResp=(responseWrapper) JSON.deserialize(jsonString,responseWrapper.class);
          //system.debug(wResp);
          //string id = wResp.Id;
         // system.debug(id);
     
      opportunity op = [select id,recordtype.name,stagename,closedate,Amount,TCV__c from opportunity where id =:wResp.SalesForceId ];
          
          if(op.id !=null){
              if(op.recordtype.Name=='H'){
               op.Id = wResp.SalesForceId;
               op.Amount = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
               else if(op.recordtype.Name=='I'){
               op.Id = wResp.SalesForceId;
               op.TCV__C = wResp.ContractValue;
               op.stagename = wResp.stage;
               op.closedate = wResp.EffectiveDate;
              update op;
          }
          }
             
          return 'sucess';
      }
       
}



My Test Class:
@istest
public class TestUpdateBOfromiwise {
 @testsetup
    static void datasetup(){

        Profile p =[SELECT ID FROM Profile Where Name='System Administrator'];
        
        User u = new User();
        u.Alias = 'standt1';
        u.Email='sauser1@testorg.com';
        u.EmailEncodingKey='UTF-8'; 
        u.LastName='Testing1';
        u.LanguageLocaleKey='en_US';
        u.LocaleSidKey='en_US';
        u.ProfileId = p.Id;
        u.TimeZoneSidKey='America/Los_Angeles';
        u.UserName='sauser1@testorg.com';
        u.Head_Of_Region__c = 'IBSZ';
        insert u;
        
        Account a = new Account();
        a.Name = 'Test Account';
        a.Segment__c = 'Aviation';
        a.Sub_Segment__c = 'Startup';
        a.IBS_Region__c = 'IBSZ';
        a.IBS_Sub_Region__c = 'ANZ';
        a.Account_Domain_Name__c = 'test.com';
        a.Account_Code__c='Test';
        a.Approved__c = True;
        insert a;
        
        Opportunity o = new Opportunity();
        o.Name = 'Test Opportunity';
        o.AccountId = a.Id;
        o.Opportunity_Name__c = 'Test Record';
        o.Contract_Type__c = 'CDx Services';
        o.TCV__c = 5000;
        o.CloseDate = system.today();
        o.Type_of_Deal__c = 'New Deal';
        o.Opportunity_Source__c = 'Other';
        o.StageName = 'SQL';
        o.IBS_Lob__c = 'Aviation Passenger Solutions - APS';
        o.Products__c = 'iFly Res';
        o.Incumbent__c = 'Sabre';
        o.Tenure__c = 6;
        o.Tenure_Unit_of_Measure__c = 'Years';
        o.One_Time_Fee__c = 5000;
        o.Annual_Recurring_Revenue__c = 100001;
        insert o;
        
         string name='nalini';
    }
       @isTest
    static void updateBOClassMethod(){
         
        Test.startTest();

   RestRequest req = new RestRequest(); 
   RestResponse res = new RestResponse();

    req.requestURI = '/services/apexrest/DemoUrl';  //Request URL
    req.httpMethod = 'POST';//HTTP Request Type
  
    RestContext.request = req;
    RestContext.response= res;
 
   opportunityiWiseUpdate.fetchopportunity();
    Test.stopTest();
}
}
 
Hello

The below trigger is working fine if not putting or differentiating with   record types. Please help whether this is in right format to get fire?

Thanks in Advance
SF Aspirant


trigger sendDatatoWiseApi on Opportunity (after update) {
 
    Trigger_Setting__mdt    triggr = [Select Trigger_Name__c,Active__c from Trigger_Setting__mdt where Trigger_Name__c ='iWise Trigger' ];

  if(triggr.Active__c == TRUE){
    set<id> oppIds = new set<id>();
    if(shouldIRun.canIRun())
   {
    for(Opportunity op : trigger.new){
        if(op.recordtype.Name=='H'){
        if(op.StageName=='Closed Won'  || 
           (trigger.oldMap.get(op.Id).Response_from_iWise_System__c==null && op.Response_from_iWise_System__c!=null && 
            op.Response_from_iWise_System__c.containsIgnoreCase('Error'))){
            oppIds.add(op.Id);
        }
    
    if(oppIds.size()>0)
        
        calliwisehos.sendBoToIwise(oppIds); 
    }
        if(op.recordtype.Name=='I'){
        if(op.StageName=='Closed Won'  || 
           (trigger.oldMap.get(op.Id).Response_from_iWise_System__c==null && op.Response_from_iWise_System__c!=null && 
            op.Response_from_iWise_System__c.containsIgnoreCase('Error'))){
            oppIds.add(op.Id);
        }
    
    if(oppIds.size()>0)
        callIwiseAPI.sendBoToIwise(oppIds); 
       //calliwisehos.sendBoToIwise(oppIds);
    }  
    }
   }
  }
}
 
Hello

I have added apex class and VF Page to override standard convert button to Accept Button. The mentioned below code is working fine. But it is getting converted in Classic Version. But need the lead Conversion Page in Lightning Version. Anyone Please suggest.

public class AutoConvertLeads {
    
    private final Lead lead; //variable for the standard Lead object
    
    public AutoConvertLeads(ApexPages.StandardController standardPageController) {
        this.lead = (Lead)standardPageController.getRecord(); //initialize the standard controller
    }
    
    public PageReference redirectToConvertionPage() {
        PageReference nextPage = new PageReference('/lead/leadconvert.jsp'); //set the starting point for the page reference to which the User will be sent
        nextPage = encodeAndSetParam(nextPage, 'retURL', lead.Id); //set the retURL parameter in order to allow for returning to Lead if User cancels from page
        nextPage = encodeAndSetParam(nextPage, 'id', lead.Id); //set the id parameter so that the conversion page knows the proper record
        nextPage = encodeAndSetParam(nextPage, 'nooppti', '1'); //set the nooppti parameter to pre-populate the "Do not create a new opportunity upon conversion." checkbox
        nextPage = encodeAndSetParam(nextPage, 'nooverride', '1'); //set the nooverride parameter in order to prevent looping in the user interface
        nextPage.setRedirect(true); //indicate that the redirect should be performed on the client side
        return nextPage; //send the User to the Lead conversion page
    }
    
    public PageReference encodeAndSetParam(PageReference passedPageReference, String passedParameterId, String passedParameterValue){
        if (passedParameterValue != null) { //if the passedParameterValue is not null
            String encodedParameterValue = EncodingUtil.urlEncode(passedParameterValue, 'UTF-8'); //encode the value that was passed to eliminate conflicts with unsafe characters
            passedPageReference.getParameters().put(passedParameterId, EncodingUtil.urlDecode(encodedParameterValue, 'UTF-8')); //add the parameter to the page reference
        }
        return passedPageReference;
    }

}

Visual Force Page:

<apex:page action="{!redirectToConvertionPage}" extensions="AutoConvertLeads" standardController="Lead">
    <apex:sectionHeader title="Accept" subtitle="{!Lead.Name}" help="/htviewhelpdoc?id=leads_convert.htm&siteLang=en_US"></apex:sectionHeader>
    <apex:pageMessages ></apex:pageMessages>
</apex:page>


Thanks
TS

 
Hello

I have a custom button. On clicking on that, a field update with checkbox true has to be done. How this can be done with Apex and VF. Any code, Please suggest.

Thanks
TS
Hi there, I am trying to emulate the "convert lead" action on a custom object of mine which I've made a path for (see below)User-added image

When I click on the final stage in my Path, I would like it to generate a pop-up that will then let me create new records in related objects.  Is this possible?  Here is a picture of what im talking about.

User-added image

If anyone could should me how to do this I would really appreciate it!