Passing Javascript values to Apex code.

It’s been a while crocodile. Truth be told I was working furiously on my Site’s Developer Challenge entry, and then I was just too pooped to post. I’m sure you were all waiting with bated breath for my next post.. nooooot.

Anyway, let’s get down to brass tacks. Quite often I’ve needed to manipulate variable values in-page(Visualforce) with JS, and then pass these modified values to Apex or a Standard Controller. Just as often I’ve simply dismissed the possibility and worked-around the issue. Recently I was speaking to a fellow who proposed the beginnings of a terribly smashing idea and thought I’d try my hand at a simple implementation.

The proposition proposes that you should be able the grab the input elements in a Visualforce page and then, using Javascript, modify or add values to a form just before it’s submitted. Obvious isn’t it. Most awesome ideas are in retrospect. As always this pattern is best explained when accompanied by an example, and that’s just what this is,

<apex:page standardController=”experiment__c”>
<script>
var v = ‘Rollercoaster of love.’;
</script>
<apex:form>

<!– This can be any input-type field –>

<apex:inputHidden value=”{!experiment__c.string__c}” id=”theField” />
<!– This is a method to get an element (or it’s Id) without hardcoding values –>

<script> var theField = document.getElementById(‘{!$Component.theField}’); </script>

<!– Grab the value of the Javascript variable and write it to the database –>
<apex:commandButton onclick=”theField.value=v;” action=”{!save}” value=”save”/>
</apex:form>
</apex:page>

If you were to click that-there button you’d save the String value ‘Rollercoaster of Love’ as a field value of a record of the Experiment__c object-type(man that’s a complicated sentence). Bloody marvelous isn’t it.

There are significantly more complex situations in which this code could be applied, and combining this pattern with some of the more prevalent JS frameworks can result in some pretty sweet dynamic interfaces. I’ve planted the seed, now get out the watering can.

28 thoughts on “Passing Javascript values to Apex code.”

    • Hi Wes,

      Used this code again today to dynamically set the value of a text box depending on which page the user completed – pageA = A , PageB = B and so on – Then used this to call a workflow and set the value of a picklist.

      Now I know which page and therefore which marketing link the user came from without asking them.

      I dont know what I do without you or Jeff,

      Thanks !

      Reply
    • Hi Wes,

      Used this code again today to dynamically set the value of a text box depending on which page the user completed – pageA = A , PageB = B and so on – Then used this to call a workflow and set the value of a picklist.

      Now I know which page and therefore which marketing link the user came from without asking them.

      I dont know what I do without you or Jeff,

      Thanks !

      Reply
  1. Wes,

    Congratulations on your Cloud Developer Challenge win!!

    Your site is indeed kewl — slick CSS, nice search results, and successfully “not looking like Force.com”. Oh, and I just love how the Texas Sheet Cake is missing a serve! 🙂

    Congratulations!

    John R
    theEnforcer.net

    Reply
  2. Wes,

    Congratulations on your Cloud Developer Challenge win!!

    Your site is indeed kewl — slick CSS, nice search results, and successfully “not looking like Force.com”. Oh, and I just love how the Texas Sheet Cake is missing a serve! 🙂

    Congratulations!

    John R
    theEnforcer.net

    Reply
  3. Wes,

    Congratulations on your Cloud Developer Challenge win!!

    Your site is indeed kewl — slick CSS, nice search results, and successfully “not looking like Force.com”. Oh, and I just love how the Texas Sheet Cake is missing a serve! 🙂

    Congratulations!

    John R
    theEnforcer.net

    Reply
  4. I think there is another way to do this. Have you looked at the ActionFunction and Param tags? Action function will create a javascript function on your page that you can call from javascript or as an event handler.

    To wit:

    function postToForceDotCom(arg1) {
    hitMe(Date(), arg1);
    }

    Hit Me

    Basically, I’ve defined a function in javascript that I call to handle the onclick event of the span tag. I’m passing in a value just for the heck of it. I could in that function do some other kind of processing, validation, dhtml, calculation, etc. I then call the javascript function that results from the actionFunction tag from my postToForceDotCom function. Just to show that the values passed are refreshed, I’m also passing in a timestamp.

    When using the param tags, you just use your arguments in the same order as the param tags where placed. This results in a post to the action reference in actionFunction with post parameters one and two.

    Take a look at the controller:

    public with sharing class ActionPageController {

    public String valueOne { get; set; }
    public String valueTwo { get; set; }

    public PageReference iWantMyJSValues() {
    valueOne = Apexpages.currentPage().getParameters().get(‘one’);
    valueTwo = Apexpages.currentPage().getParameters().get(‘two’);
    return null;
    }
    }

    This allows passing javascript values that don’t have to be bound to properties. I’m binding the outputText to these for illustration purposes only.

    Cheers,

    DevAngel

    Reply
  5. I think there is another way to do this. Have you looked at the ActionFunction and Param tags? Action function will create a javascript function on your page that you can call from javascript or as an event handler.

    To wit:

    function postToForceDotCom(arg1) {
    hitMe(Date(), arg1);
    }

    Hit Me

    Basically, I’ve defined a function in javascript that I call to handle the onclick event of the span tag. I’m passing in a value just for the heck of it. I could in that function do some other kind of processing, validation, dhtml, calculation, etc. I then call the javascript function that results from the actionFunction tag from my postToForceDotCom function. Just to show that the values passed are refreshed, I’m also passing in a timestamp.

    When using the param tags, you just use your arguments in the same order as the param tags where placed. This results in a post to the action reference in actionFunction with post parameters one and two.

    Take a look at the controller:

    public with sharing class ActionPageController {

    public String valueOne { get; set; }
    public String valueTwo { get; set; }

    public PageReference iWantMyJSValues() {
    valueOne = Apexpages.currentPage().getParameters().get(‘one’);
    valueTwo = Apexpages.currentPage().getParameters().get(‘two’);
    return null;
    }
    }

    This allows passing javascript values that don’t have to be bound to properties. I’m binding the outputText to these for illustration purposes only.

    Cheers,

    DevAngel

    Reply
  6. I think there is another way to do this. Have you looked at the ActionFunction and Param tags? Action function will create a javascript function on your page that you can call from javascript or as an event handler.

    To wit:

    function postToForceDotCom(arg1) {
    hitMe(Date(), arg1);
    }

    Hit Me

    Basically, I’ve defined a function in javascript that I call to handle the onclick event of the span tag. I’m passing in a value just for the heck of it. I could in that function do some other kind of processing, validation, dhtml, calculation, etc. I then call the javascript function that results from the actionFunction tag from my postToForceDotCom function. Just to show that the values passed are refreshed, I’m also passing in a timestamp.

    When using the param tags, you just use your arguments in the same order as the param tags where placed. This results in a post to the action reference in actionFunction with post parameters one and two.

    Take a look at the controller:

    public with sharing class ActionPageController {

    public String valueOne { get; set; }
    public String valueTwo { get; set; }

    public PageReference iWantMyJSValues() {
    valueOne = Apexpages.currentPage().getParameters().get(‘one’);
    valueTwo = Apexpages.currentPage().getParameters().get(‘two’);
    return null;
    }
    }

    This allows passing javascript values that don’t have to be bound to properties. I’m binding the outputText to these for illustration purposes only.

    Cheers,

    DevAngel

    Reply
    • Ooooh, I like the sound of that. I’m trying to build a framework involving some of these concepts and I’d like any quick-tricks that could assist:)

      Reply
  7. Dude, that’s exactly what I was looking for! I’m building a drag and drop interface with jQuery and Interface from eyecon.ro (interface.eyecon.ro) and I needed some way to pass the order that the draggables are in back to the controller when the user saves the record.

    I was trying something similar, but I was hung up on why if I defined my hidden field as

    the java function would find it, but the controller didn’t get the value and if I did

    the java function didn’t appear to see it, but it was linked to the controller…. the {!$Component.theField} binding is key!

    Here are the key pieces of what I ended up in case anyone’s trying to do the same thing:


    var termsField = document.getElementById(‘{!$Component.termOrderP}’)

    Reply
  8. Dude, that’s exactly what I was looking for! I’m building a drag and drop interface with jQuery and Interface from eyecon.ro (interface.eyecon.ro) and I needed some way to pass the order that the draggables are in back to the controller when the user saves the record.

    I was trying something similar, but I was hung up on why if I defined my hidden field as

    the java function would find it, but the controller didn’t get the value and if I did

    the java function didn’t appear to see it, but it was linked to the controller…. the {!$Component.theField} binding is key!

    Here are the key pieces of what I ended up in case anyone’s trying to do the same thing:


    var termsField = document.getElementById(‘{!$Component.termOrderP}’)

    Reply
  9. Dude, that’s exactly what I was looking for! I’m building a drag and drop interface with jQuery and Interface from eyecon.ro (interface.eyecon.ro) and I needed some way to pass the order that the draggables are in back to the controller when the user saves the record.

    I was trying something similar, but I was hung up on why if I defined my hidden field as

    the java function would find it, but the controller didn’t get the value and if I did

    the java function didn’t appear to see it, but it was linked to the controller…. the {!$Component.theField} binding is key!

    Here are the key pieces of what I ended up in case anyone’s trying to do the same thing:


    var termsField = document.getElementById(‘{!$Component.termOrderP}’)

    Reply
  10. Hi,

    Cool the binding framework passing JSvalues. Regarding that, I am actually looking for a way to search more than one passing argument based on a checkbox of different categories for example: Product 1, Product 2 showing from the same dynamic column result.

    Below, the code snippet in force.com:

    public PageReference runSearch() {

    String product = Apexpages.currentPage().getParameters().get(‘product’);
    String version = Apexpages.currentPage().getParameters().get(‘version’);
    String component = Apexpages.currentPage().getParameters().get(‘component’);
    String backlogGroup = Apexpages.currentPage().getParameters().get(‘backlogGroup’);

    soql = ‘SELECT Name,V1_RN_BacklogGroup__c,V1_RN_Component__c, V1_RN_Matriarch__c,V1_RN_ProductVersion__c FROM V1_Release_Notes_Table_Content__c WHERE Name != null’;

    if (!product.equals(”))
    soql += ‘ and V1_RN_Matriarch__c LIKE \’%’+String.escapeSingleQuotes(product)+’%\”;
    if (!version.equals(”))
    soql += ‘ and V1_RN_ProductVersion__c LIKE \’%’+String.escapeSingleQuotes(version)+’%\”;
    if (!component.equals(”))
    soql += ‘ and V1_RN_Component__c LIKE \’%’+String.escapeSingleQuotes(component)+’%\”;
    if (!backlogGroup.equals(”))
    soql += ‘ and V1_RN_BacklogGroup__c LIKE \’%’+String.escapeSingleQuotes(backlogGroup)+’%\”;

    // run the query again
    runQuery();

    return null;
    }

    I am searching by Product and I am comparing but I need to become this search more dynamic allowing multiple Products

    Please, any helps.

    Thanks.

    Reply

Leave a Comment