+ Start a Discussion
L0bster1L0bster1 

I want to automatically convert new leads into contacts. I have a trigger on Lead after update that will bulk convert 100 leads at a time. The problem I have  is that my marketing automation tool pushes new leads into Salesforce in batches of 200 at a time. When I try to import 200 leads, the bulk convert fails due to a too many DML 151 error.

 

I read that the convertlead function can only handle 100 records at a time. How can I edit the code to handle 200 imports at a time? Is it possible?

 

Thanks in advance.

 

trigger AutoConvert on Lead (after update) {

for(Lead myLead: Trigger.new){ if(Trigger.new[0].isConverted == false) { Database.LeadConvert lc = new database.LeadConvert(); lc.setLeadId(myLead.Id); lc.convertedStatus = 'Qualified'; //Database.ConvertLead(lc,true); lc.setDoNotCreateOpportunity(true); Database.LeadConvertResult lcr = Database.convertLead(lc); System.assert(lcr.isSuccess()); }}}

 

Best Answer chosen by Admin (Salesforce Developers) 
Jerun JoseJerun Jose

Instead of passing one lead value at a time to the convertLead method, you can pass a list of lead values. From the documentation at

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dml_convertLead.htm
you can do something like

LeadConvertResult[] Database.convertLead(LeadConvert[] leadsToConvert, Boolean opt_allOrNone)

 

Also, you trigger is not designed for bulk operations. Use the updated trigger below and modify it as necessary.

 

trigger AutoConvert on Lead (after update) {
	list<Lead> LeadsToConvert = new list<Lead>();
	for(Lead myLead: Trigger.new){
		if(!myLead.isConverted)
			LeadsToConvert.add(myLead);
	}

	list<Database.LeadConvert> leadConverts = new list<Database.LeadConvert>();
	for(Lead myLead : LeadsToConvert){
		Database.LeadConvert lc = new database.LeadConvert();
		lc.setLeadId(myLead.Id);
		lc.convertedStatus = 'Qualified';
		//Database.ConvertLead(lc,true);
		lc.setDoNotCreateOpportunity(true);
		leadConverts.add(lc);
	}

	if(!leadConverts.isEmpty()){
		for(Integer i = 0; i <= leadConverts.size()/100 ; i++){
			list<Database.LeadConvert> tempList = new list<Database.LeadConvert>();
			Integer startIndex = i*100;
			Integer endIndex = ((startIndex+100) < leadConverts.size()) ? startIndex+100: leadConverts.size();
			for(Integer j=startIndex;j<endIndex;j++){
				tempList.add(leadConverts[j]);
			}
			Database.LeadConvertResult[] lcrList = Database.convertLead(tempList, false);
			for(Database.LeadConvertResult lcr : lcrList)
				System.assert(lcr.isSuccess());
		}
	}
}

 

 Edit - forgot the part about max 100 records for convertLead. Updated the apex code for it

Shobhit SaxenaShobhit Saxena 
The campingList JavaScript controller isn't setting the 'item' as a parameter or saving the record correctly.

My code is as follows:

1---Camping List Component
<aura:component controller="CampingListController">
	
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    
    <aura:handler name="addItem" event="c:addItemEvent"
   	action="{!c.handleAddItem }"/>
    
    <aura:attribute name="newItem" type="Camping_Item__c"
     default="{ 'sobjectType': 'Camping_Item__c',
                    'Name': '',
                    'Quantity__c': 0,
                    'Price__c': 0,
                    'Packed__c': false }"/>
    
    <aura:attribute name="items" type="Camping_Item__c[]"/>
    
    <ol>
    <li>Bug Spray</li>
    <li>Bear Repellant</li>
    <li>Goat Food</li>
    </ol>
    
       <!-- NEW EXPENSE FORM -->
    <div class="slds-col slds-col--padded slds-p-top--large">

        <c:campingListForm/>

    </div>
    <!-- / NEW EXPENSE FORM -->    
   

    <div class="slds-card slds-p-top--medium">
        <header class="slds-card__header">
            <h3 class="slds-text-heading--small">Items</h3>
        </header>
        
        <section class="slds-card__body">
            <div id="list" class="row">
                <aura:iteration items="{!v.items}" var="items">
                    <c:campingListItem item="{!item}"/>
                </aura:iteration>
            </div>
        </section>
    </div>

</aura:component>

2---Camping List Controller
 
({
    // Load items from Salesforce
	doInit: function(component, event, helper) {

    // Create the action
    var action = component.get("c.getItems");

    // Add callback behavior for when response is received
    action.setCallback(this, function(response) {
        var state = response.getState();
        if (component.isValid() && state === "SUCCESS") {
            component.set("v.items", response.getReturnValue());
        }
        else {
            console.log("Failed with state: " + state);
        }
    });

    // Send action off to be executed
    $A.enqueueAction(action);
},

    
    handleAddItem: function(component, event, helper) {
    var newItem = event.getParam("item");
    //helper.createItem(component, newItem);
        this.saveItem(component, item, function(response){
        var state = response.getState();
        if (component.isValid() && state === "SUCCESS") {
            var items = component.get("v.items");
            items.push(response.getReturnValue());
            component.set("v.items", items);
        }
    }
          
}
                      
})

3---Camping List Helper

Empty

4---Camping List Form
 
<aura:component >
	
    <aura:registerEvent name="addItem" type="c:addItemEvent"/>
        <!-- CREATE NEW ITEM FORM -->
    <form class="slds-form--stacked">

      <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputText aura:id="itemname" label="Name"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newItem.Name}"
                  required="true"/>

          </div>
     </div>

     <div class="slds-form-element slds-is-required">
          <div class="slds-form-element__control">
              <ui:inputNumber aura:id="quantity" label="Quantity"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newItem.Quantity__c}"
                  required="true"/>

          </div>
      </div>

      <div class="slds-form-element">
          <div class="slds-form-element__control">
              <ui:inputCurrency aura:id="price" label="Price"
                  class="slds-input"
                  labelClass="slds-form-element__label"
                  value="{!v.newItem.Price__c}"
                  />
          </div>
      </div>

      <div class="slds-form-element">
          <ui:inputCheckbox aura:id="packed" label="Packed?"
              class="slds-checkbox"
              labelClass="slds-form-element__label"
              value="{!v.newItem.Packed__c}"/>
      </div>

      <div class="slds-form-element">
          <ui:button label="Create Camping Item"
              class="slds-button slds-button--brand"
              press="{!c.clickCreateItem}"/>
      </div>

    </form>
    <!-- / CREATE NEW ITEM FORM -->
</aura:component>

5---CampingListFormController
 
({
    
    clickCreateItem: function(component, event, helper) {    
    if(helper.validateItemForm(component)){
        // Create the new item
        var newItem = component.get("v.newItem");
        helper.createItem(component, newItem);
    }
        
        }

})

6---CampingListFormHelper
 
({
 createItem: function(component, newItem) {
    var createItem = component.getItem("createItem");
    createItem.setParams({ "item": item });
    createItem.fire();
             component.set("v.newItem",{ 'sobjectType': 'Camping_Item__c',
                    'Name': '',
                    'Quantity__c': 0,
                    'Price__c': 0,
                    'Packed__c': false }/>);
},
    

		validateItemForm: function(component) {
		
              // Simplistic error checking
        var validItem = true;

        // Name must not be blank
        var nameField = component.find("itemname");
        var itemname = nameField.get("v.value");
        if ($A.util.isEmpty(itemname)){
            validItem = false;
            nameField.set("v.errors", [{message:"Item name can't be blank."}]);
        }
        else {
            nameField.set("v.errors", null);
        }
        
        // Quantity must not be blank
        var quantityField = component.find("quantity");
        var quantity = nameField.get("v.value");
        if ($A.util.isEmpty(quantity)){
            validItem = false;
            quantityField.set("v.errors", [{message:"Quantity can't be blank."}]);
        }
        else {
            quantityField.set("v.errors", null);
        }
		// Price must not be blank
        var priceField = component.find("price");
        var price = priceField.get("v.value");
        if ($A.util.isEmpty(price)){
            validItem = false;
            priceField.set("v.errors", [{message:"Price can't be blank."}]);
        }
        else {
            quantityField.set("v.errors", null);
        }
            return validItem;

	}
})

I am still getting this error:

User-added image

Any help would be appreciated.
 
Best Answer chosen by Shobhit Saxena
John Lay 9John Lay 9
See if this help for saving in the handleAddItem....
 
var action = component.get("c.saveItem");
    		action.setParams({"item": newItem});
    		action.setCallback(this, function(response){
        		var state = response.getState();
        		if (component.isValid() && state === "SUCCESS") {
            		// all good, nothing to do.
        		}
    		});
    		$A.enqueueAction(action);

 
Joe Rodden 7Joe Rodden 7 
Fairly new so bear with me. I've written a class that throws an error message for any duplicate emails on Contacts. While writing the test I thought I'd covered everything the original class does however I'm only ending up with 85% code coverage. I'd like to figure out how to get to 100. 

Class (the lines that aren't covered are bolded and underlined):
 
public class Contact_CheckEmail {

    List<Contact> contacts = new List<Contact>();
    
    public Contact_CheckEmail(List<Contact> trigCon){
       contacts = trigCon; 
    }
    

    public void checkEmail(){
    Set<String> emailSet = new Set<String>();
    
    for(Contact c : contacts){
        
        emailSet.add(c.Email);
    
    }
    
    List<Contact> duplicateEmail = [SELECT Email FROM Contact WHERE Email IN: emailSet];
    
    Set<String> duplicateEmailId = new Set<String>();
    
    for(Contact c : duplicateEmail) {
    
        duplicateEmailId.add(c.Email);
    
    }

    for(Contact c: contacts){
        if(duplicateEmailId.contains(c.Email)){
               c.addError('Email already exists.');
        
        }
    
    }
    
}
}


Test Class:
@isTest
public class Test_CheckEmail {
    
    @isTest static void EmailCheckTest(){
        
        Account acc = new Account();
        acc.Name = 'TestAccount';
        insert acc;
        
        List<Contact> contacts = new List<Contact>();
        for( Integer i = 0;i < 1; i++){
            String iString = String.valueof(i);
            Contact myCon = new Contact();
            myCon.LastName = 'iString';
            myCon.AccountId = acc.Id;
            myCon.Email = 'fakeman@fake.com';
            contacts.add(myCon);
        }
        
        try{
        insert contacts;
        }
        catch (Exception e){
            Boolean expectedException = e.getMessage().contains('Email already exists.') ? true : false;
            System.assertEquals(expectedException, true);
        }
        
        List<Contact> contacts2 = new List<Contact>();
        for( Integer i = 0;i < 1; i++){
            String iString = String.valueof(i);
            Contact myCon = new Contact();
            myCon.LastName = 'iString';
            myCon.AccountId = acc.Id;
            myCon.Email = iString + '@fake.com';
            contacts2.add(myCon);
        }
        
        try{
        insert contacts2;
        }
        catch (Exception e){
            Boolean expectedException = e.getMessage().contains('Email already exists.') ? true : false;
            System.assertEquals(expectedException, false);
        }
        
        
        
    }

}

 
Best Answer chosen by Joe Rodden 7
Khan AnasKhan Anas (Salesforce Developers) 
Hi Joe,

Greetings to you!

Please use the below code, I have checked in my org and it is covering 100%
 
@isTest
public class Test_CheckEmail {
    
    @isTest static void EmailCheckTest(){        
        Account acc = new Account();
        acc.Name = 'TestAccount';
        insert acc;
        
        List<Contact> contacts = new List<Contact>();
        for( Integer i = 0;i < 1; i++){
            String iString = String.valueof(i);
            Contact myCon = new Contact();
            myCon.LastName = 'iString';
            myCon.AccountId = acc.Id;
            myCon.Email = 'fakeman@fake.com';
            contacts.add(myCon);
        }
        
        try{
            insert contacts;
        }
        catch (Exception e){
            Boolean expectedException = e.getMessage().contains('Email already exists.') ? true : false;
            System.assertEquals(expectedException, true);
        }
        
        List<Contact> contacts2 = new List<Contact>();
        for( Integer i = 0;i < 1; i++){
            String iString = String.valueof(i);
            Contact myCon = new Contact();
            myCon.LastName = 'iString';
            myCon.AccountId = acc.Id;
            myCon.Email = iString + '@fake.com';
            contacts2.add(myCon);
        }
        
        try{
            insert contacts2;
        }
        catch (Exception e){
            Boolean expectedException = e.getMessage().contains('Email already exists.') ? true : false;
            System.assertEquals(expectedException, false);
        }
        
        Contact_CheckEmail cce = new Contact_CheckEmail(contacts2);
        cce.checkEmail();
    }
}


I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Thanks and Regards,
Khan Anas
Raghu Sharma 6Raghu Sharma 6 
In which scenarios should we put the logic in apex controller vs java script controller

For eg: For making salesforce SOQL/DML statements, we can put the logic apex controller. Similarly, where should be put the logic for REST API calls? When should we use apex controller? Whar are the best practices
Best Answer chosen by Raghu Sharma 6
Rahul KumarRahul Kumar (Salesforce Developers) 
Hi Raghu,

Create a server-side controller in Apex and use the @AuraEnabled annotation to enable access to the controller method.
Only methods that you have explicitly annotated with @AuraEnabled are exposed. Calling server-side actions aren’t counted against your org’s API limits. However, your server-side controller actions are written in Apex, and as such are subject to all the usual Apex limits. A client-side controller handles events within a component. It’s a JavaScript resource that defines the functions for all of the component’s actions.
A client-side controller is a JavaScript object in object-literal notation containing a map of name-value pairs. Each name corresponds to a client-side action. Its value is the function code associated with the action. Client-side controllers are surrounded by parentheses and curly braces. Separate action handlers with commas (as you would with any JavaScript map). hope it will be helpful.

Please mark it as best answer if the information is informative.so that question is removed from an unanswered question and appear as a proper solution.

Thanks
Rahul Kumar
 
Best Answer chosen by Nikhil Bujade
AshishkAshishk
If you are using "/apex/vfpage" to open VF page in iframe, it is a change in context and origin as visualforce is loading from lightning.

There are mulitple redirects done before page is loaded if we use relative url, resulting in Performance issue in loading.

Try using absolute URL, please visit below article.

http://ashishsfdc.blogspot.com/2018/09/loading-visualforce-in-iframe.html (http://ashishsfdc.blogspot.com/2018/09/loading-visualforce-in-iframe.html" target="_blank)
MCooperMCooper 
On Opportuntities we have the default "Next Steps" field, but it's not very long and we'd like to retain back history of the progress of a deal.  I've created a long text field "Sales Progress".  Here's what I'd like to do using a workflow trigger and field update:  Whenever a new entry is made in Next Steps, copy that entry over to Sales Progress and add it to the bottom (or top) of the existing text.  What would the formula look like?
Best Answer chosen by MCooper
sfdc_ninjasfdc_ninja
You would want to create a workflow rule on the Opportunitiy object.

For evaluation criteria, you would want to use 'created, and every time it’s edited'.  

The Rule Criteria would be 

ISCHANGED(NextStep)

Then for an action, you would create a field update.  The update would be on the Sales_Progress__c field.  You would use a formual to set the new value.  The formula you would want to use would be 

Sales_Progress__c + BR() + BR() + $User.LastName + ', ' + $User.FirstName + ' ' + TEXT(Today()) + ' - ' + NextStep

This appends the the next step field to your custom sales progress field.  It also adds the user and the date so you know who made the change and when, so it should show a decent chronological story of the opportunity.  

Hope that helps

bretondevbretondev 
I have a picklist with an onchange event bound to it.
When I select a value in the picklist, I get the following error message :
This page has an error. You might just need to refresh it. Error in $A.getCallback() [b.run is not a function] Failing descriptor: {lightning:select}

Component :
 
<aura:component>
    
    <aura:attribute name="colors" type="String[]"/>
    <aura:attribute name="selectedColor1" type="String"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.loadOptions}" />
    
    <lightning:select aura:id="select1-id" value="{v.selectedColor1}" onchange="{c.onChangeColor}" name="picklist1" label="Select a Color"  >
        <option value="">-- None --</option>
        <aura:iteration items="{!v.colors}" var="color">
            <option value="{!color.value}" text="{!color.label}"></option>
        </aura:iteration>
    </lightning:select>
    
</aura:component>
Controller :
({
    loadOptions: function (component, event, helper) {
        var opts = [
            { value: "R", label: "Red" },
            { value: "G", label: "Green" },
            { value: "B", label: "Blue" }
         ];
         component.set("v.colors", opts);
    },
    onChangeColor: function (component, event, helper) {
        //var myColor = event.getSource().get("v.value");
        //var test;
    }
})


 
Best Answer chosen by bretondev
Ashif KhanAshif Khan
Hii

There is small syntext error issue -- {!v.selectedColor1}​ & {!c.onChangeColor} here​  ' ! ' is missing
<lightning:select aura:id="select1-id" value="{!v.selectedColor1}" onchange="{!c.onChangeColor}" name="picklist1" label="Select a Color"  >
        <option value="">-- None --</option>
        <aura:iteration items="{!v.colors}" var="color">
            <option value="{!color.value}" text="{!color.label}"></option>
        </aura:iteration>
    </lightning:select>

Regards
Ashif

 
fredkafredka 
Hi.  I am trying to assign a queue as the case owner.. In a Case Before Trigger, I am have the following.  The case owner is getting updated if the abm__c field is populated.. however, it does not get updated with the queue if that field is null.

Account_Team__c at = aMap.get(c.AccountId);
                // Only change the owner if the Account Team has
                // an ABM and the ABM is an active user. Once assigned
                // set the flag Assigned to ABM
            if (string.isNotBlank(at.abm__c)) {
                if (at.abm__r.IsActive) {
                    c.ownerid = at.abm__c;
                    c.Assigned_To_ABM__c = true;                    
                }
             }
              else {
                c.ownerid = abmQueue[0].Id;
                }

Any help woudl be greatly appreciated!!

Fred
Best Answer chosen by fredka
_Zach Boyd_Zach Boyd
I have not used the QueueSObject class before, however I see that it has a QueueId field. Try using that and the owner should be assigned properly.

https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_queuesobject.htm

 
Naveen Kannoju02547126464965992Naveen Kannoju02547126464965992 
cloud you please give me help for this Question

I retrive the data from account(using custom controller) object and display that data in datatable(vf) format this one is good.
but  here column name for example: name,industry,type,rating.
here whenever i click the name or industry ior any other field name I want to display sort order depending on that field.

Thanks
Naveen
Best Answer chosen by Naveen Kannoju02547126464965992
akramakram
Hi Naveen

Try these,
https://github.com/Mottie/tablesorter/wiki
http://mottie.github.io/tablesorter/docs/
https://github.com/Mottie/tablesorter

--Akram
Marry SteinMarry Stein 
Hey guys,

i am not familar with javascript, but i really like how the chart.js libary looks. To get started i want to create some cool Salesforce Dashboards with chart.js. I have already create a visualforce Page to show a simple bar chart. Now, i am looking for a way to get the controller variable to the javascript function : 
http://www.chartjs.org/docs/latest/

This is the javascript Code: 
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["M1", "M2", "M3", "M4", "M5", "M6"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],   
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});
</script>
How can i change the label and dataset with controller variables ? My idea is to create a simple list and transform the list to string. Does this work ? 

Thanks for help guys. I cant find any help for chart.js and visualforce...

Greetings,

Marry





 
Best Answer chosen by Marry Stein
Alain CabonAlain Cabon
Hi,

The access fo remote object from the client in javascript was used for button with javascript (not supported in Lightning) and it is also an interesting technique for VFP used for the mobile (android/iOs). 

Best Practices for Using Remote Objects: 
Remote Objects pairs well with JavaScript frameworks such as jQuery and AngularJS, and those can help with the complexity of your application’s user interface. Always consider separating the concerns of your application into multiple layers and keeping them as discrete as possible. This is called “separation of concerns,” and it’s a classic software pattern and best practice.
http://ttps://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_remote_objects_considerations.htm

An Example of Using Remote Objects with jQuery Mobile​
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_remote_objects_example_extended.htm

i know jQuery and it is explained here:for the basics in Salesforce: https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_javascript_libraries.htm