Its pretty straight forward to create records using JS remoting. Where it gets tricky is to pass a Map from JS to controller.

The following code illustrates how to call a RemoteAction and pass the following:
1. Single sObject (Account) record
2. List of sObjects
3. Map containing Id,sObjects (Indirect way)

Q. Why cant you send Map directly using the JS Map collection i.e. var x = new Map();
A. Since Salesforce is handling all the type conversion internally, it seems to not be converting the JS Map into Apex Map. It may work someday, but it doesn’t as of Nov 2016

Live demo can be found here: (remember the code is not idiot proof — not try null inputs)
http://ima-developer-edition.ap1.force.com/jsRemotingv1

Do see the console on your browser for relevant information like logs

Now, the code!
As always, the comments are embedded. Enjoy coding!

public class jsRemotingControllerv1 {

    //take object from jsRemoting and create account
    @RemoteAction
    public static void createAccount(Account a) {
        try {
            Database.SaveResult sr = Database.insert(a);
        } catch(DmlException e) {

                system.debug(e.getmessage());
        }

    }
    //object list from jsRemoting and create accounts
    @RemoteAction
    public static void createAccounts(List<Account> a) {
        try {
            Database.SaveResult[] sr = Database.insert(a);
        } catch(DmlException e) {

                system.debug(e.getmessage());
        }

    }    

    //object map from jsRemoting and create accounts
    @RemoteAction
    public static void createAccountsMap(List<String> keys,List<Account> a) {

        //if you need an account map recreate it here
        Map<String,Account> accountMap = new Map<String,Account>();
        for (Integer i = 0 ; i < keys.size(); i++) {
            accountMap.put(keys[i],a[i]);
        }

        system.debug('accountMap = '+accountMap);
        try {
            Database.SaveResult[] sr = Database.insert(a);
        } catch(DmlException e) {

                system.debug(e.getmessage());
        }

    }      

}
<apex:page controller="jsRemotingControllerv1" showHeader="false" title="Use JS remoting to create accounts">
    <script           src="https://code.jquery.com/jquery-3.1.1.slim.min.js"           integrity="sha256-/SIrNqv8h6QGKDuNoLGA4iret+kyesCkHGzVUUV0shc="           crossorigin="anonymous">
    </script>    

    <script type="text/javascript">
        $j=jQuery.noConflict();
        console.log('hi');
    	//create a js class for account insertion
    	function Account() {
            this.name = null;
        }    	
    	//single account
    	function createAccount() {
            var accountsingle = new Account();
            accountsingle.name = $j('[id$="accountname1"]').val();
            console.log(accountsingle.name);
            Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.jsRemotingControllerv1.createAccount}', 
                                                      accountsingle, function(result,event) {
                                                          console.log(event);
                                                          $j('[id$="output1"]').text('Account inserted using method "' +event.method+'". Insert success? = '+event.status);	
                                                      }
                                                     );
        }
    	//list of accounts
		function createAccounts() {    
            
            var account1 = new Account();
            account1.name = $j('[id$="accountname1"]').val();
            var account2 = new Account();
            account2.name = $j('[id$="accountname2"]').val();
            var accounts = new Array(account1, account2);
            console.log(accounts);
            Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.jsRemotingControllerv1.createAccounts}', accounts, 
                                                      function(result, event) {
                                                          console.log(event);
                                                          $j('[id$="output1"]').text('Account inserted using method "' +event.method+'". Insert success? = '+event.status);	
                                                      }
                                                      );
            
        }
    
    	//map of accounts
		function createAccountsMap() {    

            var account1 = new Account();
            account1.name = $j('[id$="accountname1"]').val();
            var account2 = new Account();
            account2.name = $j('[id$="accountname2"]').val();
            var accounts = new Array(account1, account2);
            //var accountsMap = new Map();
            //accountsMap.put('account1key',account1);
            //accountsMap.put('account2key',account2);
            var keys = new Array('keyvalue1','keyvalue2');
            
            console.log(accounts);
            Visualforce.remoting.Manager.invokeAction('{!$RemoteAction.jsRemotingControllerv1.createAccountsMap}', keys, accounts, 
                                                      function(result, event) {
                                                          console.log(event);
                                                          $j('[id$="output1"]').text('Account inserted using method "' +event.method+'". Insert success? = '+event.status);	
                                                      }
                                                      );
            
        }    
    </script>

    <apex:form>
        <apex:pageBlock>
            <b>Use JS remoting to create accounts</b>

        <apex:outputPanel id="output">
            <apex:pageBlockSection columns="1">

                <apex:inputText id="accountname1" label="Account name1"/>
                <apex:inputText id="accountname2" label="Account name2"/>
                <apex:commandButton value="submit account" onclick="createAccount();" reRender="output"/>
                <apex:commandButton value="submit accounts" onclick="createAccounts();" reRender="output"/>
                <apex:commandButton value="submit accountsMap" onclick="createAccountsMap();" reRender="output"/>
                <apex:outputtext id="output1" label="Result"></apex:outputtext>

        	</apex:pageBlockSection>
    	</apex:outputPanel>
        </apex:pageBlock>
    </apex:form>
</apex:page>
Advertisements