Wednesday, June 4, 2014

2) Insert Records in SF by using JavaScript without Apex classes or controller.


Hi guys,

In this post i am showing how can we use the power of javascript in VF page and inserting record in salesforce without any standard/custom controller or Apex.

By using AJAX Toolkit we can do this task easily.

AJAX Toolkit divides in two type synchronous and asynchronous call.

It works in three simple steps:
Connecting to the AJAX Toolkit(By using login methods or getting Session_ID)
Embedding the API methods in JavaScript.
Processing the results.
in following example i am using synchronous call :-

<apex:page id="Page" sidebar="false">
    <script src="/soap/ajax/20.0/connection.js" type="text/javascript"></script>
    <script>
        function insertAccount(){
            // Getting Session ID.
            sforce.connection.sessionId = "{!$Api.Session_ID}";
         
            //Creating New Account Record.
            var account = new sforce.SObject("Account");
            //Getting Account Name from inputText.
            account.Name = document.getElementById("Page:Form:PB:PBS:PBSI:Name").value;
         
            // This is the line where magic happens, calling Create() method.
            var result = sforce.connection.create([account]);
         
            if (result[0].getBoolean("success")) {
                alert("New Account is created with id " + result[0].id);
            } else {
                alert("failed to create new Account " + result[0]);
            }
        }
    </script>
    <apex:form id="Form">
        <apex:pageBlock title="Insert Account" tabStyle="Account" id="PB">
            <apex:pageBlockSection title="Account Name" columns="1" id="PBS">
                <apex:pageBlockSectionItem id="PBSI">
                    <apex:outputLabel value="Name" />
                    <apex:inputText title="Name" id="Name" />
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
            <apex:pageBlockButtons>
                <apex:commandButton onclick="return insertAccount();" value="Save"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Screen Shots:



 After inserting of record you are having ID of record :


No comments: