function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ZedroidZedroid 

How to create record in salesforce?

Hi All,

 

I'm trying to create a record in salesforce, but I'm getting an exception as System.NullException.

 

using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
using System.Data;
using sforce;

public partial class Example : System.Web.UI.Page
{
    private SforceService binding;
  
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }

    protected void btnClick(object sender, EventArgs e)
    {
        CreateAccountSample();
    }

    /// Demonstrates how to create one or more Account records via the API 

    public void CreateAccountSample()
    {
        Account account1 = new Account();
        Account account2 = new Account();

        account1.BillingCity = "Wichita";
        account1.BillingCountry = "US";
        account1.BillingState = "KA";
        account1.BillingStreet = "4322 Haystack Boulevard";
        account1.BillingPostalCode = "87901";

        account2.Name = textName.Text;
        account2.BillingCity = TextBox1.Text;
        account2.BillingCountry = TextBox2.Text;
        account2.BillingState = TextBox3.Text;
       
        sObject[] accounts = new sObject[2];
        accounts[0] = account1;
        accounts[1] = account2;
        
        try
        {
            SaveResult[] saveResults = binding.create(accounts);

            for (int i = 0; i < saveResults.Length; i++)
            {
               if (saveResults[i].success)
                {                   
                    Console.WriteLine("An Account was created with Id: {0}",
                        saveResults[i].id);
                }
                else
                {
                    Console.WriteLine("Item {0} had an error updating", i);
                   
                    foreach (Error error in saveResults[i].errors)
                    {
                        Console.WriteLine("Error code is: {0}",
                            error.statusCode.ToString());
                        Console.WriteLine("Error message: {0}", error.message);
                    }
                }
            }
        }
        catch (System.Web.Services.Protocols.SoapException e)
        {
            Console.WriteLine(e.Code);
            Console.WriteLine(e.Message);
        }
    } 

}

 

 

It would be appriciative if any one rectifies me where I'm going wrong.

 

thanks in advance.

Zubair

Steven RobertSteven Robert

Hi Zubair,

 

Happen to see your post while working on a similar task.  Spun this up quickly and confirmed it works, hope it helps:

 

 public void CreateAccountSample ()
        {
             //create the account object to hold our changes 
                Account newAccount = new Account();

            //wire up properties
                newAccount.Name = "New Name";
                newAccount.Website = "www.website.com";
                newAccount.Phone = "800-123-4567";
                newAccount.BillingStreet = "123 Main";
                newAccount.BillingPostalCode = "48084";
                newAccount.BillingState = "MI";
                newAccount.BillingCountry = "USA";

            //call update passing an array of object 
                binding = new SforceService();
                binding.Timeout = 60000;

                LoginResult lr;
                lr = binding.login("XXX", "XXX");

                binding.Url = lr.serverUrl;
                binding.SessionHeaderValue = new SessionHeader();
                binding.SessionHeaderValue.sessionId = lr.sessionId;

                SaveResult[] saveResults = binding.create(new sObject[] { newAccount });

            //loop through the results, checking for errors 
                for (int j = 0; j < saveResults.Length; j++)
                {
                    Console.WriteLine("Item: " + j);
                    if (saveResults[j].success)
                    {
                        Console.WriteLine("A New Account with an id of: " + saveResults[j].id + " has been created .\n");
                    }
                    else
                    {
                        Console.WriteLine("  The error reported was: " + saveResults[j].errors[0].message + "\n");
                    }
                }
        }

 

 

 

Best,
Steve 

SrikanthKuruvaSrikanthKuruva

Hi Zubair

 

are you sure that you are not having any null values in the control values (textname.Text, Textbox1.Text, Textbox2.Text, Textbox3.Text).

account2.Name = textName.Text;
account2.BillingCity = TextBox1.Text;
account2.BillingCountry = TextBox2.Text;
account2.BillingState = TextBox3.Text;

 if not just comment the necessary code which creates account2 and see if you are still getting the error. 

SuperfellSuperfell

because you never set the class member variable 'binding' to anything. see the docs for the code you have missing to do the login and setup the binding object.

Ashutosh kumar yadavAshutosh kumar yadav
<template>
    <lightning-card title="Create Account ,Contact Record">
        <lightning-layout>
            <lightning-layout-item size="6">
 
                <!-- Displaying fields to get information. -->
                <lightning-card title="Fill Account Details">
                <lightning-input class="slds-p-around_medium" label="Name" name="accoutName"
                    onchange={nameChangedHandler}></lightning-input>
                <lightning-input class="slds-p-around_medium" label="Account Number" name="accoutNumber"
                    onchange={numberChangedHandler}></lightning-input>
                <lightning-input class="slds-p-around_medium" label="Phone" type="phone" name="accountPhone"
                    onchange={phoneChangedHandler}></lightning-input>
                <br/>
            </lightning-card>
            <!--    <lightning-input class="slds-p-around_medium" label="Enter First  Name for Contact" name="strPhone"
                onchange={nameChangedHandlerConName}></lightning-input>   --> 
                <lightning-card title="Fill Contact Details">
                    <lightning-input class="slds-p-around_medium" label=" last Name " name="LastNamee"
                    onchange={nameChangedHandlerCon}></lightning-input>
                   <lightning-input class="slds-p-around_medium" label="Email" name="ConEmail"
                    onchange={nameChangedHandlerConEmail}></lightning-input>  
                </lightning-card>
                    
                   <lightning-button class="slds-m-left_x-small" label=" Multiple con" variant="brand"
                    onclick={createContact}></lightning-button> 
                         
                    <br/>
                    <br/>
                    <br/>
                    <br/>
                    <lightning-card title="Fill Opportunity Details">
                    <lightning-input class="slds-p-around_medium" label="Name" value={name} 
                    onchange={handleChangeOpp}></lightning-input>
                   <lightning-input class="slds-p-around_medium" type="date" name="input2" label="Date" value={Date}
                    onchange={handleChangeOpp}></lightning-input>
                    <lightning-combobox
                    name="progress"
                      label="StageName"
                      value={StageName}
                      placeholder=""
                      options={options}
                      onchange={handleChangeOpp} >
                     </lightning-combobox>
                     
                     <br/>
                    <lightning-button class="slds-m-left_x-small" label="Multiple Opp" variant="brand"
                    onclick={createOpp}></lightning-button>
                </lightning-card>
                    <br/>
                    <br/>
                    <br/>
                    <lightning-button class="slds-m-left_x-small" label="Save" variant="brand"
                    onclick={createAccount}></lightning-button>
                    <br/>
            </lightning-layout-item>
        </lightning-layout>
    </lightning-card>
</template>




import { LightningElement,track } from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';
 
export default class LdsCreateRecord extends LightningElement {
    strName;
    strAccountNumber;
    strPhone;
 
    // Change Handlers.
    nameChangedHandler(event){
        this.strName = event.target.value;
    }
    numberChangedHandler(event){
        this.strAccountNumber = event.target.value;
    }
    phoneChangedHandler(event){
        this.strPhone = event.target.value;
    }
 
  @track AccId;
  @track LastNamee='';
  @track ConEmail='';
  @track strPhone='';
  nameChangedHandlerCon(event){
    this.LastNamee = event.target.value;
}
nameChangedHandlerConName(event){
    this.strPhone = event.target.value;
}
nameChangedHandlerConEmail(event){
    this.ConEmail = event.target.value;
}
@track Name = '';
@track StageName ='';
@track CloseDate; 
handleChangeOpp(event) {
    console.log(event.target.label);       
    if(event.target.label=='Name'){
        this.Name = event.target.value;
     
    } 
    if(event.target.label=='Date'){
        this.CloseDate = event.target.value;
     
    } 
    if(event.target.label=='StageName'){
        this.StageName = event.target.value;
     
    } 
  
                        
}



    // Insert record.
    createAccount(){
 
        // Creating mapping of fields of Account with values
        var fields = {'Name' : this.strName, 'AccountNumber' : this.strAccountNumber, 'Phone' : this.strPhone};
 
        // Record details to pass to create method with api name of Object.
        var objRecordInput = {'apiName' : 'Account', fields};
 
        // LDS method to create record.
        createRecord(objRecordInput).then(response => {
            alert('Account created with Id: ' +response.id);
            this.AccId=response.id;
            console.log(this.AccId);


            var fields = {'LastName' : this.LastNamee, 'AccountId' : this.AccId,'Email' : this.ConEmail };
            // Record details to pass to create method with api name of Object.
            var objRecordInputt = {'apiName' : 'Contact', fields};
            createRecord(objRecordInputt).then(response => {
                alert('COntact created with Id: ' +response.id);
               // this.AccId=response.id;
               // console.log(this.AccId);

               var fields = {'Name' : this.Name,'CloseDate' : this.CloseDate,'StageName' : this.StageName, 'AccountId' : this.AccId};
 
               // Record details to pass to create method with api name of Object.
               var objRecordInputt = {'apiName' : 'Opportunity', fields};
        
               // LDS method to create record.
               createRecord(objRecordInputt).then(response => {
                   alert('Oppor created with Id: ' +response.id);
                  // this.AccId=response.id;
                  // console.log(this.AccId);
               }).catch(error => {
                   alert('Error: ' +JSON.stringify(error));
               });

            }).catch(error => {
                alert('Error: ' +JSON.stringify(error));
            });
      
        }).catch(error => {
            alert('Error: ' +JSON.stringify(error));
        });
    //    createContact();
              
      // var fields = {'Name' : this.ConName,'Email' : this.ConEmail ,'LastName' : this.LastNamee, 'AccountId' : this.AccId};
   
        // LDS method to create record.
       
        
    }
   createContact()
    {
        var fields = {'LastName' : this.LastNamee, 'AccountId' : this.AccId};
 
        // Record details to pass to create method with api name of Object.
        var objRecordInputt = {'apiName' : 'Contact', fields};
 
        // LDS method to create record.
        createRecord(objRecordInputt).then(response => {
            alert('COntact created with Id: ' +response.id);
           // this.AccId=response.id;
           // console.log(this.AccId);
        }).catch(error => {
            alert('Error: ' +JSON.stringify(error));
        });
    }
    createOpp()
    {
        var fields = {'Name' : this.Name,'CloseDate' : this.CloseDate,'StageName' : this.StageName, 'AccountId' : this.AccId};
 
        // Record details to pass to create method with api name of Object.
        var objRecordInputt = {'apiName' : 'Opportunity', fields};
 
        // LDS method to create record.
        createRecord(objRecordInputt).then(response => {
            alert('Opportunity created with Id: ' +response.id);
           // this.AccId=response.id;
           // console.log(this.AccId);
        }).catch(error => {
            alert('Error: ' +JSON.stringify(error));
        });
    }

    get options() {
        return [
                 { label: 'Prospecting', value: 'Prospecting' },
                 { label: 'Qualification', value: 'Qualification' },
                 { label: 'Needs Analysis', value: 'Needs Analysis' },
               ];
            }
   
}











 <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
        <target>lightning__HomePage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
    </targets>