2

I have a remote action method that accepts Set collection as a parameter. How do I pass a set collection from Javascript? I tried passing an array and it gave me an error message.

-------- Class -------
     @RemoteAction
     global static string forDemo(set<string> names){
         // Processing using names
         return 'go';
     }

-------- VF Page ------
    <script>

        var lstNames = new Array("Name 1", "Name 2");

        <class>.forDemo(lstNames, function(result, event){
            console.log(result);
        }, {escape: false});

    </script>

When I run the page, I get the following error in browser console

Visualforce Remoting Exception: Unable to convert parameter to Apex type: expected SET, got ArrayList

How do I pass a SET collection or can I not use it in Javascript Remoting?

3

Not sure if Javascript remoting allows sets but it does allow List<>. It looks like JavaScript does not provide a native Set data type so pasing a array of string is still considered as list than a set as per apex ( just guessing here)

public with sharing class RemotingObjectsController {    
@RemoteAction
    public static string insertAccounts(List<string> stringval){
        Map<string,string> stringMap = new Map<string,string>();
        for(string s: stringval){
        stringMap.put(s,s);
        }
        if(stringMap.Keyset() != null){
           for(string s1: stringMap.Keyset()){
             return s1;
           }
        }
return null;
    }
}

This way you can still have unique values as key is a set<> in a map

| improve this answer | |
  • 6
    You could also use the Set method addAll or the overloaded Set constructor that takes a List parameter to convert from List to Set. – Peter Knolle Mar 23 '13 at 9:32
  • Thanks rao, your guess was right. I am able to pass Javascript string array to a remote action which accepts a list<string> parameter. Thanks @peter-knolle for chiming in. – DCBoy Mar 24 '13 at 5:08
  • I usually just pass String[] variableName as the parameter. – Andrew L. Jun 3 '16 at 1:11
1

What you were passing is a JavaScript Array (no Set as you stated) which is why Visualforce thinks it is a List.

I wouldn't recommend this over @rao's answer, but you could declare a method that accepts a Map and get its keySet().

var aMap = {};
function addSetVal(val) {
   aMap[val] = null;
}
addSetVal('a123');
addSetVal('b456');

Visualforce.remoting.Manager.invokeAction(
  '{!$RemoteAction.RemotingController.remoteAction}',
  aMap,
  function(result, event) {
    console.log(result);
  }
);

@RemoteAction
global static void remoteAction(Map<String, String> aMap) {
  System.debug(aMap.keySet()); // {'a123','b456'}
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.