Visualforce Remoting – Passing wrapper class object as a parameter

Currently I have a controller similar to the following (used example, it’s easier to understand):

global class myClass
{
    global class wrapperClass
    {
        public String name {get; set;}
        public Account account {get; set;}

        public wrapperClass()
        {
            account = new Account();
        }
    }

    @RemoteAction
    global static wrapperClass executeProcess(wrapperClassArg arg1)
    {
        reutrn wrapperClassArg;
    }
}

Then from the VF page if I pass an empty JS object for the wrapper class parameter, it works good and I can set the primitive types of variables in the wrapper class:

var wrapper = new Object();
wrapper['name'] = 'Test';

myClass.executeProcess(wrapper, function(result, event)
{
    if(event.type === 'exception')
    {
        console.log(event);
        return false;
    }
    else if(result)
    {
        console.log(result);
        // do something
    }
    else
    {
        console.log(event);
    }
});

which results with object and the name variable is set without problems.

Now the interesting bit… How can you set an sObject from the VF page?

I’ve done this in the past for single public sObjects, but doesn’t seem to work if the sObject is inside a wrapper class. So I’ve tried the following:

var wrapper = new Object();
wrapper['name'] = 'Test';
wrapper['account'] = new Object();
wrapper['account']['Name'] = 'Test';

myClass.executeProcess(wrapper, function(result, event)
...

which results with the following error:

Unexpected type for myClass.executeProcess(myClass.wrapper)

EDIT: I have also tried setting sobjectType = 'Account' and Id =
null / ''
for the javascript account object.

Does anyone know a workaround for the above issue?

Answer

@RemoteAction
    global static wrapperClass executeProcess(string arg1)
    {
        JSONParser parser = JSON.createParser(arg1);
        wrapperClass wrap = (wrapperClass)parser.readValueAs(wrapperClass.class);
        return wrap;
    }

Attribution
Source : Link , Question Author : Boris Bachovski , Answer Author : metadaddy

Leave a Comment