• sachinarorasf
  • SMARTIE
  • 534 Points
  • Member since 2018
  • Cloud Analogy


  • Chatter
    Feed
  • 19
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 152
    Replies
This is the code of auto lead conversion and autoLeadConversion is the function.I had written master class so i need specific function to be tested
public class AAAExisting{ 
    public List<wrapLead> wrapLeadList {get; set;}
    public List<Lead> accs {get; set;}
    
    public void ConvertedLeadList(){
       accs = [SELECT Id, Name, ConvertedAccountId, ConvertedContactId, ConvertedOpportunityId, Status FROM Lead WHERE IsConverted=true];
   // System.debug(accs);
    }
    
    
    
    public AAAExisting(){
        if(wrapLeadList == null) {
            wrapLeadList = new List<wrapLead>();
            for(Lead a: [select Id, Name, Company, Email, Phone, Status FROM Lead WHERE IsConverted=false]) {
                // As each Account is processed we create a new wrapAccount object and add it to the wrapAccountList
                wrapLeadList .add(new wrapLead(a));
               // System.debug(wrapLeadList);
            }
        }
    }
       
  
    
       Public void autoLeadConversion(List<Lead> autoLeadConversions) {
       //  List<Lead> autoLeadConversions= new List <Lead>();
           for(Lead lead: autoLeadConversions){
              if (lead.isConverted == false) { //to prevent recursion
       Database.LeadConvert lc = new Database.LeadConvert();
       lc.setLeadId(lead.Id); 
       String oppName = lead.LastName;
       lc.setOpportunityName(oppName);
       LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
       lc.setConvertedStatus(convertStatus.MasterLabel);
       Database.LeadConvertResult lcr = Database.convertLead(lc);
       System.assert(lcr.isSuccess());            
           }
        } 
    }
 
   
    
    public void processSelected() {
        for(wrapLead wrapAccountObj : wrapLeadList ) {
        if(wrapAccountObj.selected == true) {
            Database.LeadConvert lc = new Database.LeadConvert();
           lc.setLeadId(wrapAccountObj.acc.Id);
           lc.setopportunityname(wrapAccountObj.acc.Company);
            LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
            lc.setConvertedStatus(convertStatus.MasterLabel);
            Database.LeadConvertResult lcr = Database.convertLead(lc);
            }
            }
             }
 
    // This is our wrapper/container class. A container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. In this example a wrapper class contains both the standard salesforce object Account and a Boolean value
    public class wrapLead{
        public Lead acc {get; set;}
        public Boolean selected {get; set;}
 
        //This is the contructor method. When we create a new wrapAccount object we pass a Account that is set to the acc property. We also set the selected value to false
        public wrapLead(Lead a) {
            acc = a;
            selected = false;
            System.debug('convertStatus'+ acc);
        }

    }
    
}



 
Hi,

I'm trying to insert a negative number but it does not allow me to enter a minus. 

<lightning:input min="-10.0" type="number" formatter="decimal" step = ".01" value="{!v.price}" onchange="{!c.calc}"/>
                                                                
Hello everyone,
My component:
apex:component layout="block" access="global" language="{!lan}" id="ac" >
apex:attribute name="selA" type="String" default="" description="" />
apex:attribute name="SOList" type="map" default="" description="" />

apex:selectList value="{!selA}" size="1 id="aslLinOrgMan" >
apex:selectOption itemValue="" itemLabel="Select" />
/apex:selectList>
What I would like to do is dynamically building the list <apex:selectOption> with the itemValue/itemLabel passed in the SOList map attribute, or through another approach if this is not a good one.
Is there a way to achieve this? If so, how?
Thanks in advance for your support,
All the best,
Jerome
Hi All,

I was referring the salesforce documentation for lightning:input type="email" .There it is mentioned When multiple email is used, the email field expects a single email address or a comma-separated list of email addresses. Example, my@domain.com,your@domain.com with or without a space after the comma.Is it possible to use type="email" when there is a need to enter multiple email id.I have tried to enter multiple emails with comma separation but it is giving me error as "You have entered an invalid format.".
Hi all,

I need something like a clickable image. when I click the image in a page related record should be created.

Thanks in advance.
How to get All Objects and Their Field? Please help me thank before<.^.>
Hello, I am working on updating Salesforce records from an outside platform, and I need my:
1. SF Consumer Key
2. SF Consumer Secret
3. SF Token

How can I find what these are? 
Hi ,

I tried to create my first lightning application but i get the folowing error.

User-added image

Below is my code

Application
<aura:application extends="force:slds" >
    <c:TeacherAppCompo/>
</aura:application>

Component
<aura:component controller='TeacherCreateRecord' >

    <aura:attribute name="client" type="Teacher__c" default="{'sObjectType':'Teacher__c','Name' : '' }" />
    <ui:inputtext label="Enter Teacher Name"   value="{!v.client.Name}" />
    <ui:button label="Submit" press="{!c.createClient}"/>
</aura:component>

Client side contoller
({
    createClient : function(component, event) {
        
        
       //for logs
        console.log("In Client Controller");

        //getting the record info from component to js
        var varClient=component.get("v.client");
       
        //validation to  check of field is empty or not
        if($A.util.isEmpty(varClient.Name) || $A.util.isUndefined(varClient.Name) )
        {
           alert('First name is required');
            //return the value and function will stop
            return;
        }
         
         helper.createRecord(varClient);
    }
})

Helper
({
    createRecord : function() {
         
       
       console.log("In helper");
        
        //calling apex function
        alert('Before action');
        var action = component.get("c.createTeacherRecord");
         
        alert('Before set params function');
        //set the parameters
        action.setParams({
            client : varClient
        });
        
        alert('Before callback function');
        //set callback function
        action.setCallback(this,function(a){
            
            var response=a.getState();
            if(response == "SUCCESS")
            {
                //Reset form and this is optional
                var newrecord= {'sObjectType' : 'Teacher__c','Name':''};
                component.set("v.client",newrecord);
                alert('Record is Created');
            }else if(response == "ERROR")
            {
                alert('Record is not Created');
            }
        });
        //To enqueue all actions and let all happen one by one 
        $A.enqueueAction(action);
    }
    
})

ApexClass
public with sharing class TeacherCreateRecord {
    
    
    @AuraEnabled
    public static void createTeacherRecord(Teacher__c  client)
    {
        try{
            System.debug('Teacher Create Record class'+ client) ;
            if(client != null)
            {
                insert client;
            }
        }
    
       catch(Exception e) 
       {
            System.debug('Inside Apex class') ;   
       }
    }
 }

The object i have used is Teacher__c and i am trying to fetch the name which is a standard field .
Hi I am preparing for Saleforce Developer certification (PD-01) , I came acroos the below question.

A developer wants multiple test classes to use the same set of test data?

As per my kowledge , answer should be 'create set up method for each test class'

But in dump paper, it says,  "use seealldata==true annotaton in the test class"

i am not getting how it works, please explain.

Also please share dumps if u have
I am new to integrations, so this may be a very basic question. I need to create a mock up of JSON of a sample Salesforce record, to ultimately be able to post to an external API. My question is: is there any required context for constructing the JSON? E.g. do the field names need to equal the API names in salesfroce (e.g. {
  "Lead" : [ {
    "bed_count__c" : 55}]}

Or- can I assign the fields any name I want? Apologies if this is very basic, but your assitance is greatly helpful. 
I am working on Process Builder. My criteria is that if a multi-select-picklist field on the lookup object is not blank, I want to populate this field with that value. 

I am entering this value in my action step but it won't let me save:
What do I need to change? Thank you. 

[Discharge__c].Referral_Name__c.Language__c 
I need assistance in working on Trigger. I have a requirement, where I need to insert contact when Checkbox is clicked in account.

Eg: I have 3 checkboxes Electronics, Fashion, Furnitures. If I select 2 checkboxes Electronics and Fashion and save the Account. Then, I need to insert 2 contacts with field selected as Electronics and field selected as Fashion in another record.

I need assistance in this requirement.

Thanks.
Hi, i need to create event on lead for a test apex.
The EndDateTime (or activityDate) of this event need to be past.

I have create a lead and event on this lead but i can't choose a negative EndDateTime.
How can i do ?
It's possible to set a date time on Start Test for launch the test in the futur? Ty
Hi there, 

I'm quite stuck here. 
I've written a test class for my batch but it doesn't appears to be running. It stays at 0% :( 

I'm missing something but don't know what. 

Can someone help me figure it out? 

Here is my batch class : 
global class BatchUpdateAllLeads implements Database.Batchable <SObject> {
//START METHOD
    global Database.QueryLocator start(Database.BatchableContext bc){
        String Query='Select id,TECH_Update__c from Lead where TECH_Update__c=false AND Converted=false ' ;
        return Database.getQueryLocator(Query);
            }
//EXECUTE METHOD
    global void execute(Database.BatchableContext bc, List<Lead> scope){
        for(Lead l: scope){
            l.TECH_Update__c = true;
        }
        update scope;
    }
//FINISH METHOD
    global void finish(Database.BatchableContext bc){
        Id job= bc.getJobId();
        System.debug(job);
    }
}

And this is my attemp of writting a proper test class :( 
@istest
private class BatchUpdateAllLeads_TEST {
    @istest
    static void testAcc(){
        List<Lead> l = new List<Lead>();
        Lead l1 = new Lead(Company	='BTP',LastName = 'Test',SIRET__c='12659991955626',Numero_d_ordre__c='9999-99-99',Region_GRDF__c='Ile de France',Tech_Update__c=false,IsConverted=false);
        l.add(l1);

        Lead l2= new Lead(Company	='Comp',LastName = 'Test2',SIRET__c='12659991955687',Numero_d_ordre__c='1111-99-99',Region_GRDF__c='Ile de France',Tech_Update__c=false, IsConverted=true);
        l.add(l2);

        Lead l3= new Lead(Company	='Agny', LastName = 'Test3', SIRET__c='19959991988687', Numero_d_ordre__c='1111-99-11', Region_GRDF__c='Ile de France', Tech_Update__c=true,IsConverted=true);
        l.add(l3);
        insert l;
   
    Test.startTest();
    BatchUpdateAllLeads ap= new BatchUpdateAllLeads();
    Id jobid= Database.executeBatch(ap);
    Test.stopTest();
    }
}

Ty very much for your help
I have a Batch Class where it sends an email when Expiry Date (Custom Date Field) is today. The mail body contains the list of opportunities whose Expiry Date is Today. I have created a list and added the opportunities whose Expiry Date is today. But I am stuck at calling Opportunity Name from the List. Can someone help me to solve this.
//Batch Class

global class OpportunityExpiryDate_New implements DataBase.Batchable <sObject> {
    global DataBase.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Name, Expiry_Date__c  FROM Opportunity WHERE Expiry_Date__c = TODAY';
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Opportunity> scope) {
        List<Opportunity> oppList = new List<Opportunity>();
        for(Opportunity opp : scope) {
            if(opp.Expiry_Date__c == date.today()) {
                oppList.add(opp);
            }
        }
        update oppList;
        messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
        String body = 'The Opportunity ' +oppList+ ' is expiring today.';
        email.setToAddresses(new String[]{'maddulasaivineeth@gmail.com'});
        email.setSubject('Opportunities Expiring Today');
        email.setPlainTextBody(body);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
    global void finish(Database.BatchableContext BC) {   
    }
}
I am having a major brain block. I have the following Apex Trigger designed to keep a Probability % at a previously (manually) set level. This is that code:
trigger keepProbability on Opportunity (before update) {
    for(Integer i = 0; i < Trigger.new.size(); i++) {
        if(Trigger.old[i].stagename != Trigger.new[i].stagename) {
            if(Trigger.old[i].probability != Trigger.new[i].probability) {
               Trigger.new[i].probability = Trigger.old[i].probability;
            }
        }
    }

}

The trigger works great, but I am losing my mind trying to write a Test Class. Any tips on writing the test would be greatly appreciated.
 
Hello everyone!

My friends, maybe you can advise where I can practise new exercises on Apex Code (Classes, Triggers, Tests).

Do not offer Trailhead :)
Hi I am not able to save the record using lightning component.please find the code below.

Lightning Component:
<aura:component access="global" controller="LightningBloodDonorReg">
    
        <aura:attribute name="bloodReg" type="WT_BloodDonor__c" default="{ 'sobjectType' : 'WT_BloodDonor__c' }"/>
        
        <lightning:layout multipleRows="true">
            <div class="div1">
                <lightning:layoutItem flexibility="auto" padding="around-small" size="12">
                    JANASENA
                </lightning:layoutItem></div>
            <div class="div2">
                <lightning:layoutItem flexibility="auto" padding="around-small" size="12">
                    My Life; My janasena
                </lightning:layoutItem></div>
            
            <lightning:layoutItem flexibility="auto" padding="around-small" size="12">
                <lightning:layout >
                    <div style="padding-left:400px;">
                        <lightning:layoutItem size="4"></lightning:layoutItem>
                    </div>
                    <div style="background-color:orange;width:100%;">
                        <lightning:layoutItem flexibility="auto" padding="around-small" size="12" >
                            
                            <ui:inputText label="Donor Name" aura:id="Donor Name" class="field" value="{!v.bloodReg.Name}" />
                          Blood Group  <force:inputField  aura:id="Donor Name" class="field" value="{!v.bloodReg.BloodGroup__c}" />
                            <ui:inputText label="Donor Phone"  aura:id="Donor Name" class="field" value="{!v.bloodReg.PhoneNumber__c}" />
                           State <force:inputField  aura:id="Donor Name" class="field" value="{!v.bloodReg.State__c}" />
                           District <force:inputField  aura:id="Donor Name" class="field" value="{!v.bloodReg.District__c}" />
                            <!--   <ui:inputText label="Enter some text     " class="field" value="Test Field" updateOn="click"/>
                        <ui:inputText label="Enter some text     " class="field" value="Test Field" updateOn="click"/>
                        <ui:inputText label="Enter some text     " class="field" value="Test Field" updateOn="click"/>
                        <ui:inputText label="Enter some text     " class="field" value="Test Field" updateOn="click"/>-->
                            
                            <ui:button label="Submit" class="slds-button slds-button--neutral" labelClass="label" press="{!c.createDonor}"/>
                        </lightning:layoutItem>
                    </div>
                    
                    <lightning:layoutItem size="4"></lightning:layoutItem>
                </lightning:layout>
            </lightning:layoutItem>
        </lightning:layout>
  
</aura:component>


.JS file

({
  createDonor : function(component, event) {
    var newDonor = component.get("v.bloodReg");
    var action = component.get("c.createDonor");
    action.setParams({ 
        "bloodDonor": newDonor
    });
    action.setCallback(this, function(a) {
           var state = a.getState();
            if (state === "SUCCESS") {
                var name = a.getReturnValue();
                alert("success");
            }
        else{
              alert("Failed");
         }
        });
    $A.enqueueAction(action)
}
})

Class:

public class LightningBloodDonorReg {
    @AuraEnabled
    public static WT_BloodDonor__c bloodDonor { get; set; }
    
    public LightningBloodDonorReg() {
        
        bloodDonor = new WT_BloodDonor__c();
        
        
    }
    @AuraEnabled
    public static WT_BloodDonor__c saveDetails() {
        system.debug('bloodDonor'+bloodDonor);
       Upsert bloodDonor;
        system.debug('bloodDonor'+bloodDonor);
         return bloodDonor ;
    }
}
From my experimentation with the metadata api, it appears to only allow the creation of custom fields on custom objects. 
Is this really the case?
Any suggestions on how i can programatically add 1 to N fields to say the "Lead" object?
I will not know ahead of time on how many fields there are so a package update probably won't work.
Any sample code is appreciated. 
Hi All,
          I have created a test class for a class but its failing and giving me error:- System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out.
my class is given below:-

global without sharing class ZoomService {
    @Future(callout=true)
    public static void createWebinar(String requestBody, String userId, Id sessionId){
        SessionTriggerHelper.runTrigger = false;
        String requestEndpoint =ZoomJWTAuthentication.getZoomCredentials().rie__Zoom_URL__c + 'users/'+userId+'/webinars';
        String requestMethod = 'POST';
        
        httpResponse res = ZoomCalloutService.postCallout(requestMethod, requestEndpoint, requestBody);
        CreateWebinarJSONParser cwp = CreateWebinarJSONParser.parse(res.getBody());
        Session__c ss = [Select id, rie__Zoom_URL__c, rie__Meeting_ID__c, 
                         rie__Meeting_Password__c, rie__Session_Type__c
                         from Session__c 
                         where Id =: sessionId];
        ss.rie__Zoom_URL__c = cwp.join_url;
        ss.rie__Meeting_ID__c = String.valueOf(cwp.Id);
        ss.rie__Meeting_Password__c = cwp.password;
        ss.rie__Session_Type__c = 'Webinar';
        update ss; 
        
        //System.debug(res.getStatusCode());
    }
    
    @Future(callout=true)
    public static void createUser(String requestBody){
        String requestEndpoint = ZoomJWTAuthentication.getZoomCredentials().rie__Zoom_URL__c + 'users';
        String requestMethod = 'POST';
        Map<String, Object> reqMap = new Map<String, Object>();
        reqMap.put('action', 'create');
        Map<String, Object> userInfo = new Map<String, Object>();
        userInfo.put('email', 'absinghrathore127@gmail.com');
        userInfo.put('type', '1');
        userInfo.put('first_name', 'abhimanyu');
        userInfo.put('last_name', 'singh');
        reqMap.put('user_info', userInfo);
        String  reqBody = JSON.serialize(reqMap);
        
        httpResponse res = ZoomCalloutService.postCallout(requestMethod, requestEndpoint, reqBody);
        System.debug(res.getStatus());
        System.debug(res.getBody());
    }
    
    @Future(callout=true)
    public static void listUsers( String emailId, Id zoomUserRecordId){
        String requestEndpoint = ZoomJWTAuthentication.getZoomCredentials().rie__Zoom_URL__c + 'users';
        String requestMethod = 'GET';
        
        httpResponse res = ZoomCalloutService.getCallout(requestMethod, requestEndpoint);
        if(res.getStatusCode() == 200){
            GetUsersJSONParser gu = GetUsersJSONParser.parse(res.getBody());
            List<GetUsersJSONParser.users>  userList= gu.users;
            String userId = '';
            if(!userList.isEmpty()){
                for(GetUsersJSONParser.users u : userList){
                    if(u.email != Null && u.email == emailId){
                       userId = u.id;
                       break; 
                    }
                }
                rie__Zoom_User__c zoomUser = [Select id from rie__Zoom_User__c where Id =: zoomUserRecordId];
                if(userId != Null){
                    zoomUser.rie__User_Id__c = userId;
                }
                update zoomUser;
            }
            
        }
        
    }
    
    //@Future(callout=true)
    webservice static String getMeetingRecording(String meetingId, Id recId){
        String requestEndpoint = ZoomJWTAuthentication.getZoomCredentials().rie__Zoom_URL__c + 'meetings/'+meetingId+'/recordings';
        String requestMethod = 'GET';
        
        httpResponse res = ZoomCalloutService.getCallout(requestMethod, requestEndpoint);
        if(res.getStatusCode() == 200){
            GetRecordingJSONParser getRecordingJSONParser = GetRecordingJSONParser.parse(res.getBody());
            Session__c ss = [Select id, rie__Zoom_URL__c, rie__Meeting_ID__c, 
                             rie__Zoom_Recording_URL__c
                             from Session__c 
                             where Id =: recId];
            ss.rie__Zoom_Recording_URL__c = getRecordingJSONParser.share_url;
            update ss;
            return 'Success';  
        }else{
            return 'There is no recording for this meeting ';
        }
    }
    
}
my test class is given below:-
@isTest
private class ZoomServiceTest {
    public static Integer RESPONSE_CODE = 200;
    private class Mock implements HttpCalloutMock {
        
        public HTTPResponse respond(HTTPRequest req) {
            
            HTTPResponse res = new HTTPResponse();
            
            res.setStatusCode(200);
            res.setBody('{"topic": "Test Webinar","type": 5,"start_time": "2020-04-20T06:59:00Z","duration": 60,"timezone": "America/Los_Angeles","password": "avfhfgh","agenda": "Test Webinar","recurrence": {"type": 1,"repeat_interval": 1,"end_date_time": "2020-04-20T06:59:00Z"},"settings": {"host_video": true,"panelists_video": true,"practice_session": true,"hd_video": true,"approval_type": 0,"registration_type": "integer",'+
                        +'"audio": "both","auto_recording": "none","enforce_login": false,"enforce_login_domains": "","alternative_hosts": "","close_registration": true,"show_share_button": true,"allow_multiple_devices": false,"registrants_email_notification": true}}');
            
            return res;
        }
    }
    
    
    static testmethod void createWebinarTest() {
        
        Test.setMock(HttpCalloutMock.class, new Mock());
        Test.startTest();
        
        rie__Event__c evt = new rie__Event__c();
        insert evt;
        
        Session__c ss = new Session__c();
        ss.name = 'Test webinar'; 
        ss.rie__Event__c = evt.Id;
        insert ss;
        
         ZoomService.createWebinar('','',ss.Id);
        //ZoomService.createUser(res);
       ZoomService.listUsers('',ss.id);
        ZoomService.getMeetingRecording('',ss.id);
        Test.stopTest();
    }
}
Can anyone help me with this error?
Hello Everyone

I have a lightning component put on a record page. I'm using RefreshEvent in my component to see if RefreshEvent was done on record page and then perform some action.
<aura:handler event="force:refreshView" action="{!c.handleEvent}"/>

I have my component put on Lead object record page as well as Opportunity record page.

My problem is, when I navigate from Lead Record page to Opportunity record page, and I make some changes on Opportunity record, the RefreshEvent is called twice - one for Lead record (as i had navigated from Lead object, probably it kind of cached it) and one for current Opportunity record. If I'm printing v.recordId in console I clearly see two different record Ids being printed and hence my action is getting called twice for two different records.
 
handleEvent: function(component,event,helper){
        console.log('HANDLER '+component.get('v.recordId'));
}

--
Console Log: 
HANDLER 0063h000004n7r5AAA
HANDLER 00Q3h0000052lCCEAY

How can I tackle this scenario?

Thanks,
Saurabh Kulkarni
<apex:page controller="Hospital" >
<apex:form >
<apex:pageBlock >
  <apex:pageMessages id="showmsg"></apex:pageMessages>  
<apex:pageBlockSection >
<apex:pageBlockSectionItem >
  Hospital Name : 
<apex:inputField value="{!hosp.Name}"/>  
</apex:pageBlockSectionItem>
    
 <apex:pageBlockSectionItem >
Account Name :  
 <apex:inputField value="{!hosp.Account__c}"/>
</apex:pageBlockSectionItem>  
</apex:pageBlockSection>   
  
    <apex:pageBlockButtons >
    
<apex:commandButton action="{!insertNewItem}" value="Save" rerender="showmsg"/>   

</apex:pageBlockButtons>
    
<apex:pageBlockTable value="{! insertedrecord }" var="ct" id="mainSection">
    <apex:column headerValue="Hospital Name">"{! ct.Name }"</apex:column>
    <apex:column headerValue="Account Name">"{! ct.Account__c }"</apex:column>
</apex:pageBlockTable>    

</apex:pageBlock>
</apex:form>
</apex:page>
 
public class Hospital{

    public Hospital__c hosp{get;set;}
    public Hospital__c insertedrecord{get;set;}
 public Hospital()
    {
        hosp = new Hospital__c();
    }
    
  public void insertNewItem() {
if(hosp.Name == NULL || hosp.Name == '' )
{
   ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Please enter'));   
}
 else
 {     
      insert hosp;
      id insertedrecordid = hosp.Id;
      insertedrecord = [Select Name, Account__c  from Hospital__c where Id = :insertedrecordid Limit 1];
     
 }   
  }
}



Insert failed. First exception on row 0 with id a0B2w000000hYugEAE; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]
Error is in expression '{!insertNewItem}' in component <apex:commandButton> in page task1hospital: Class.Hospital.insertNewItem: line 17, column 1
 

I am getting above error, Please help me

Thanks in Advance

This is the code of auto lead conversion and autoLeadConversion is the function.I had written master class so i need specific function to be tested
public class AAAExisting{ 
    public List<wrapLead> wrapLeadList {get; set;}
    public List<Lead> accs {get; set;}
    
    public void ConvertedLeadList(){
       accs = [SELECT Id, Name, ConvertedAccountId, ConvertedContactId, ConvertedOpportunityId, Status FROM Lead WHERE IsConverted=true];
   // System.debug(accs);
    }
    
    
    
    public AAAExisting(){
        if(wrapLeadList == null) {
            wrapLeadList = new List<wrapLead>();
            for(Lead a: [select Id, Name, Company, Email, Phone, Status FROM Lead WHERE IsConverted=false]) {
                // As each Account is processed we create a new wrapAccount object and add it to the wrapAccountList
                wrapLeadList .add(new wrapLead(a));
               // System.debug(wrapLeadList);
            }
        }
    }
       
  
    
       Public void autoLeadConversion(List<Lead> autoLeadConversions) {
       //  List<Lead> autoLeadConversions= new List <Lead>();
           for(Lead lead: autoLeadConversions){
              if (lead.isConverted == false) { //to prevent recursion
       Database.LeadConvert lc = new Database.LeadConvert();
       lc.setLeadId(lead.Id); 
       String oppName = lead.LastName;
       lc.setOpportunityName(oppName);
       LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
       lc.setConvertedStatus(convertStatus.MasterLabel);
       Database.LeadConvertResult lcr = Database.convertLead(lc);
       System.assert(lcr.isSuccess());            
           }
        } 
    }
 
   
    
    public void processSelected() {
        for(wrapLead wrapAccountObj : wrapLeadList ) {
        if(wrapAccountObj.selected == true) {
            Database.LeadConvert lc = new Database.LeadConvert();
           lc.setLeadId(wrapAccountObj.acc.Id);
           lc.setopportunityname(wrapAccountObj.acc.Company);
            LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
            lc.setConvertedStatus(convertStatus.MasterLabel);
            Database.LeadConvertResult lcr = Database.convertLead(lc);
            }
            }
             }
 
    // This is our wrapper/container class. A container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. In this example a wrapper class contains both the standard salesforce object Account and a Boolean value
    public class wrapLead{
        public Lead acc {get; set;}
        public Boolean selected {get; set;}
 
        //This is the contructor method. When we create a new wrapAccount object we pass a Account that is set to the acc property. We also set the selected value to false
        public wrapLead(Lead a) {
            acc = a;
            selected = false;
            System.debug('convertStatus'+ acc);
        }

    }
    
}



 
I have custom object with a field Geolocation type .
How can i create map view of that cities .
I have inserted longitude and latitude values for every city.
how i add it to page layout?
  • April 12, 2020
  • Like
  • 0
I'm trying to generate Json in following format
{
   "name":"TestAPIFromTrigger",
   "discovered":null,
   "occurred_on":null,
   "group":{
      "id":7387,
      "name":"Default Group"
   },
   "description":"",
   "channel":{
      "source":"API"
   },
   "submitted_by":{
      "given_name":"First Name",
      "surname":"Last Name",
      "email":"SSS@edu",
      "phone":"78965555"
   }

Apex code

Patient_Satisfaction__c c = [select id, Name, Reporter_Phone__c, Description_of_Feedback__c from Patient_Satisfaction__c where Patient_Relation__c ='Referred to Privacy Office' order by lastmodifiedDate desc limit 1];
    JSONGenerator gen = JSON.createGenerator(true);
    gen.writeStartObject();
    gen.writeObjectField('Name',c.Name);
    gen.writeObjectField('incident_group_id',7387);
    gen.writeObjectField('description',c.Description_of_Feedback__c);
    gen.writeStartObject();
    gen.writeFieldName('submitted_by');
    gen.writeStartArray();
    gen.writeObjectField('phone',c.Reporter_Phone__c);
    gen.writeEndArray();
    gen.writeEndObject();
    String jsonS = gen.getAsString(); 
    System.debug('jsonMaterials'+jsonS)
I am stuck in the second chllenge on Automate Accounts in Process Automation Specialist Superbadge.I'm getting this error-
*
Challenge Not yet complete... here's what's wrong:
A validation rule did not prevent a new Account from being saved when Shipping Country is blank and Shipping State has three characters.
*
I have used the following Validation Rules on Accounts object-

(1)Billing_Country_Validation_Rule-------------------------------------------
Validation Formula: --------------------------------------------------------------------------------------------------- NOT(OR(BillingCountry = "US", BillingCountry = "USA", BillingCountry = "United States", ISBLANK(BillingCountry))) ------------------------------------------------------------------------------------------------------
(2).Billing_State_Validation_Rules -----------------------------------------------Validation Formula-------------------------------------------------------
OR( LEN(BillingState) != 2, NOT(CONTAINS("AL:AK:AZ:AR:CA:CO:CT:DE:DC:FL:GA:HI:ID:" & "IL:IN:IA:KS:KY:LA:ME:MD:MA:MI:MN:MS:MO:MT:NE:NV:NH:" & "NJ:NM:NY:NC:ND:OH:OK:OR:PA:RI:SC:SD:TN:TX:UT:VT:VA:" & "WA:WV:WI:WY:PR", BillingState)) ) ------------------------------------------------------------------------------------------------------- (3).For_Customer_Channel ----------------------------------------------------------Validation Formula--------------------------------------------
ISCHANGED( Name ) && ISPICKVAL(Type, 'Customer - Channel') -------------------------------------------------------------------------------------------------(4).For_Customer_Direct -------------------------------------------------------------Validation Formula-----------------------------------------
ISCHANGED( Name ) && ISPICKVAL(Type, 'Customer - Direct' ) ----------------------------------------------------------------------------------------------------- (5).Shipping_Country_Validation_Rule ----------------------------------------Validation Formula----------------------------------------------------------- NOT(OR(ShippingCountry = "US", ShippingCountry = "USA", ShippingCountry = "United States", ISBLANK(ShippingCountry))) ---------------------------------------------------------------------------------------------- (6).Shipping_State_Validation_Rule----------------------------------
Validation Formula---------------------------------------------- OR(LEN(ShippingState) != 2, NOT(CONTAINS("AL:AK:AZ:AR:CA:CO:CT:DE:DC:FL:GA:HI:ID:" & "IL:IN:IA:KS:KY:LA:ME:MD:MA:MI:MN:MS:MO:MT:NE:NV:NH:" & "NJ:NM:NY:NC:ND:OH:OK:OR:PA:RI:SC:SD:TN:TX:UT:VT:VA:" & "WA:WV:WI:WY:PR", ShippingState)) )

Please help me to complete this challenge..
How to get all the SObjects fields and datatype in single table in an org
I am trying to get all the validation error message from my apex class in to the lightning component. Earlier I was using the DMLException and only one 1 validation error was captured. So I tried to use the Database.SaveResultlike below is my apex Class
@AuraEnabled
public static String passCase(String caseId){
    List<Case> case_recs = [SELECT id,_Case_Flow__c,Status from Case WHERE Id = :caseId];
    String msg = '';
    for (Case rec : case_recs)
    {
        rec.Status = 'Transferred';
        rec.Route_Case_Flow_Executing__c = true;
        Database.SaveResult saves = Database.update(rec, false);

            if(!saves.isSuccess()) {
                msg = 'Error '+ saves.getErrors()[0].getMessage();
            }
           else {
               msg = 'Successfully Updated!';
           }
           return msg; 
        }          
    return msg;
}
And my lightning component looks like below
passCaseToCS_helper : function(c,e,h) {
    var set_action1 = c.get("c.passCase");
    set_action1.setParams({caseId: c.get('v.recordId')});
    set_action1.setCallback(this, function(result)
    {
        var resultFormApex = result.getReturnValue();
        if (result.getState() === 'SUCCESS')
            {               
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    message: resultFormApex ,
                    type: 'success',
                    mode: 'pester'
                });
                toastEvent.fire(); 
            }                
            else if(result.getState() === 'ERROR')
            {
                $A.get("e.force:showToast")
                        .setParams({
                            type: 'error',
                            mode: 'pester',
                            message: resultFormApex  }).fire();  
           }

        $A.get("e.force:refreshView").fire();
    });
    $A.enqueueAction(set_action1);       
}
When the record successfully gets updated with no Validation error I can see the Successfully Updated!in the toast for the records with Validation error I cannot see anything in the Toast. I tried to put a debug log to show what msg when the record update fails with Validation error I dont see anything on the logs either. I am not sure what I am missing here. Any help is greatly appreciated
 
  • April 10, 2020
  • Like
  • 0
<apex:page standardController="Campaign" extensions="ForSaleLookupOnCampaignController"> 
    <script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");                  
            for(var i=0; i<inputCheckBox.length; i++){          
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){                                     
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
   
}
    </script>
    <apex:form >
        <apex:pageBlock >
             <apex:pageBlockButtons >
                <apex:commandButton value="Save" style="width: 100px; height: 30px" action="{!processSelected}" rerender="table2"/>
            </apex:pageBlockButtons>
            <p style="font-size: 15px;font-weight: bold;">Select FID :</p><apex:inputfield style="width: 200px; height: 30px" value="{!Campaign.For_Sale__c}" id="forsaleid"/><br/>
            <apex:pageblockSection title="Related Campaign Members" collapsible="false">
                <apex:pageBlockTable value="{!wrapcontactList}" var="conWrap" id="table" title="All Related Campaign Members">     
                    <apex:column >
                        <!--apex:facet name="header">
                          <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                         </apex:facet-->
                        <apex:inputCheckbox value="{!conWrap.selected}" id="inputId"/>
                    </apex:column>
                    <apex:column value="{!conWrap.con.Name}" />
                    <apex:column value="{!conWrap.con.Account.name}" />
                </apex:pageBlockTable>
            </apex:pageblockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>
public class ForSaleLookupOnCampaignController { 
    public List<CampaignMember> Campaignmemberlist{get;set;} 
    public Campaign cmp {get;set;} 
    public List<wrapContact> wrapcontactList {get; set;}
    public List<Contact> selectedcontacts{get;set;}
    set<id>conid=new set<ID>();
    public String ID { get; set;}
    set<id>ForSaleid=new set<id>();
    public ForSaleLookupOnCampaignController (ApexPages.StandardController standardControllerParam) {
        this.cmp = (Campaign)standardControllerParam.getRecord();
        Campaignmemberlist = [SELECT id,name,Campaignid,Company__c,type,For_Sale__c,Contact.For_Sale__c  FROM CampaignMember WHERE Campaignid = : ApexPages.currentPage().getParameters().get('id') ];
        for(CampaignMember cm:Campaignmemberlist){
            conid.add(cm.ContactId);
            ForSaleid.add(cm.For_Sale__c);
        }
        //
        if(wrapContactList == null) {
            wrapContactList = new List<wrapContact>();
            for(Contact c: [select Id,Name,Account.name,For_Sale__c from Contact where id=:conid]) {
                wrapContactList.add(new wrapContact(c));
            }
        }
        
    }
    public PageReference processSelected() {
        PageReference pr;
        selectedcontacts = new List<contact>();
        system.debug('for sale '+cmp.For_Sale__c);
        for(wrapContact wrapcontactObj : wrapcontactList) {
            if(wrapcontactObj.selected == true) {
                selectedcontacts.add(wrapcontactObj.con);
                
            }
        }
        for(contact s:selectedcontacts){
            s.For_Sale__c=cmp.For_Sale__c;
        }
            try{
                
                database.update(selectedcontacts);
                
            }catch( Exception e ){
                ApexPages.addMessages(e);
            }
            system.debug('selectedcontacts'+selectedcontacts);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'FID Update on Contact'));
      return pr;   
    }
    public class wrapContact {
        public Contact con {get; set;}
        public string forsaleid{get;set;}
        public Boolean selected {get; set;}
        
        public wrapContact(Contact c) {
            con = c;
            forsaleid=c.For_Sale__c;
            selected = false;
        }
    }
}
How should I show success message on VF Page
& another thing is
here <apex:inputfield style="width: 200px; height: 30px" value="{!Campaign.For_Sale__c}" id="forsaleid"/> when I click on button & page is load the value is already populate on this but I want to clear this value when page populate how can I do that?


 
Hi,

I am trying to make a trigger where that returns the number of key fields that have been populated into a custom number field, before creation of the record. Upon creation of the record, for each key field that has been populated, I want to create a task record and associate it to the Lead.

I am having trouble with a statement causing recursion when including the 'after insert' event, which I believe I require to return the Lead record Id which will be needed for the What.Id of the task.

I have posted the code below, highlighting in bold, the line that causes the error.

Thank you all!

trigger KeyFields on Lead (before insert) {
    List<integer> keyFields = new List<integer>();
    for (Lead newLead : Trigger.new) {
        if(newLead.FirstName == null) {
            keyFields.isEmpty();
            } else { keyFields.add(1); }
        if (newLead.LastName == null) {
                keyFields.isEmpty();
            } else {
                keyFields.add(2);
            }
        if (newLead.Email == null) {
                    keyFields.isEmpty();
        } else { keyFields.add(3);
            
        }    
        if (newLead.Phone == null) {
                        keyFields.isEmpty();
        } else { keyFields.add(4);
        }
        if (newLead.Website == null) {
                            keyFields.isEmpty();
        } else { keyFields.add(5);
            
        }
        if (newLead.Title == null){
                                keyFields.isEmpty();
        } else { keyFields.add(6);} 
        keyFields.size();
        Decimal sizeOfList = keyFields.size();
        newLead.Key_Fields_Populated__c = sizeOfList;
        
        // from the Set, return the elements that have been populated into the list
        // if the size of the set is greater than 3.
        List<integer> fields = new List<integer>();
        if(sizeOfList >=3) {
            for (Integer i=0; i < sizeOfList; i++){
                Integer num = i;
                Integer indexNumber = keyFields.get(i);
                if (!keyFields.isEmpty()){ 
                    fields.add(indexNumber);
               }
      }
}
        //System debug - look to see if the fields list is being populated.
        for (Integer checkfields : fields) {
            System.debug(checkfields);
        }
        List<String> fieldNames = new List<String>();
        fieldNames.add('First Name');
        fieldNames.add('Last Name');
        fieldNames.add('Email');
        fieldNames.add('Phone');
        fieldNames.add('Website');
        fieldNames.add('Title');
        
        for (Integer i=0; i <fields.size(); i++){
            Integer loopNumber = fields.get(i);
            Task t = new Task();
            t.WhatId = newLead.id;
            t.Subject = 'Verify the' + fieldNames.get(loopNumber) + 'fields';
            t.Status = 'Not Started';
            t.WhoId = newLead.OwnerId;
            t.ActivityDate = date.today();
        }
      }
}
Hi,

I'm trying to insert a negative number but it does not allow me to enter a minus. 

<lightning:input min="-10.0" type="number" formatter="decimal" step = ".01" value="{!v.price}" onchange="{!c.calc}"/>
                                                                
Hi Friends, I am new to integration and my task is
How to create webhooks in salesforce ?
thanks in advance.
Hello there, 
My question is that there is a picklist field with 3 (a, b, c) values , the value  b changes from b to b1. So then what happens to

1 All the records,
2 The reports column and the report filter. 

Thanks. 
Hi ..
I created Validation rule on child component, But when i click on 'Save'(Standard Save)   from Parent component, The Validation rule not display any error message . For this end users confuse and not sure, Whats the problem inside the application 
************************
AND(
OR(
Case_Sold__r.RecordType.Name ='Other1',
Case_Sold__r.RecordType.Name ='Other2'
),
OR(
TEXT(Type__c)= 'emp1',
TEXT(Type__c)= 'emp2',
TEXT(Type__c)= 'emp3'
)
,
ISBLANK(Prior_GA_Number__c)
)
**************
Error message : GA Number cant be blank.
But when i try to save this from Parent compoent , The Error mesage not populating " GA Number cant be blank".

Even i tried Event messages and toast message in Standard ' Save' function , But its not stopping and not display error message 

can you pls assist on this ....its littel bit urgent 
  • March 26, 2020
  • Like
  • 0
I am looking to have a button on my opportunity record page layout that redirects to a URL that lives in the opportunities field.
Hi

I've been reading on properties in apex but still bit confused on the actual use case of it. please can anyone help me to understand it?
  • October 05, 2015
  • Like
  • 1