Record creation using JavaScript in Salesforce Visualforce Page

Record creation using JavaScript in Salesforce Visualforce Page

soap/ajax/54.0/connection.js library can be used to create records using JavaScript in Salesforce. There is no need to use Apex. 

Sample Code:

<apex:page >
    <script type="text/javascript">
        let __sfdcSessionId = '{!GETSESSIONID()}';
    </script>
    <script 
        src="../../soap/ajax/54.0/connection.js"
        type="text/javascript">
    </script>
    <script>
        function createAccount() {
            
            console.log( 'Inside createAccount method' );
            let objAccount = new sforce.SObject( "Account" );
            objAccount.Name = 'Test VF';
            objAccount.Description = '{!$User.Id}' + ' created this Account';
            let result = sforce.connection.create( [ objAccount ] );
            console.log( 'Result is', JSON.stringify( result ) );
            if ( result[ 0 ].getBoolean( "success" ) ) {
               alert( 'Account was created successfully' );
            }
            else {
              alert( 'Error occured: ' + result );
            }
            
        }
    </script>
    <apex:form id="pageForm">
        <apex:pageBlock >
            <apex:commandButton value="Create Account" onclick="createAccount();" reRender="pageForm"/>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Output:

Leave a Reply