Here's a fairly simple example illustrating the problem that uses only standard objects:
.pages/MyPage.page
A page with an input text box and a button.
<apex:page controller="Remote_MyPage" >
<input id="account-id" />
<button id="button">go</button>
<span
id="script-params"
data-remote-action="{!$RemoteAction.Remote_MyPage.query}"
/>
<script src="{!$Resource.MyPageScript}" ></script>
</apex:page>
./staticresources/MyPageScript.resource
A js script that takes the value from the input text box and sends it as the AccountId of a contact to a vf remoting method.
var button = document.getElementById('button')
, accountId = document.getElementById('account-id')
, remoteAction = document.getElementById('script-params').dataset.remoteAction
var buildContact = function(){
var c = {}
c.AccountId = accountId.value
return c;
}
var buttonClickHandler = function(){
var c = buildContact()
console.log( c )
Visualforce.remoting.Manager.invokeAction(
remoteAction
, c
, function(){ console.log(arguments) }
)
}
button.addEventListener('click',buttonClickHandler);
./classes/Remote_MyPage.cls
A class with a remote action method that takes the contact object and returns a list of contacts from the same account.
public class Remote_MyPage
{
@RemoteAction
public static list<Contact> query( Contact c ){
String QueryString =
'SELECT Id, LastName FROM Contact '
+ ( ( c.AccountId != NULL )
? ' WHERE AccountId = \'' + c.AccountId + '\' '
: '' )
;
return (list<Contact>) Database.query( QueryString );
}
}
The problem is with the behavior when the AccountId is the empty string. In that situation, I want to get contacts from any Account, and not just contacts who are not associated with an account.
I've tried adding an empty string check after the null check in line 8 of the controller
+ ( ( c.AccountId != NULL && c.AccountId != '' )
However, the code above causes an Apex run-time exception:
Visualforce Remoting Exception: Invalid id:
What is typically your approach for handling this situation?
c.AccountId = accountId.value
; perhaps check there and set null for an empty string.null
instead of an empty string will work, but it does add an unfortunate extra bit of complexity to the code. That might be the best we can do here though..null
instead of the empty string in the javascript should work.