The Silver Lining

Lessons & Learnings from a salesforce certified technical architect.

Passing Javascript values to Apex code.

with 12 comments

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.

Advertisement

Written by Wes

September 14, 2009 at 5:03 pm

12 Responses

Subscribe to comments with RSS.

  1. Not bad crocodile!!

    jeffdonthemic

    September 14, 2009 at 11:08 pm

    • 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 !

      John Taylor

      May 23, 2011 at 2:57 pm

  2. […] Passing Apex values to Javascript By Wes Leave a Comment Categories: Apex, SalesForce, VisualForce and force.com Tags: Apex, force.com, JavaScript, values, VisualForce For the sake of completeness, and because I’ve received a large number of hits from the googled phrase ‘pass apex to javascript’, I thought it would be appropriate for me to write an article detailing the converse of an operation explain in a previous post. […]

  3. !$Component.theField <= very cool. Didn't know you could do that.

    d3developer

    September 24, 2009 at 7:45 pm

  4. 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

    John R (The Enforcer)

    October 1, 2009 at 12:18 am

  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

    Dave Carroll

    October 2, 2009 at 6:49 pm

  6. Oops, I guess my VF tags got stripped. I’ll post the source to the force.com Blog.

    http://blog.sforce.com/sforce/2009/10/passing-javascript-values-to-apex-controller.html

    Dave Carroll

    October 2, 2009 at 7:19 pm

    • 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:)

      Wes

      October 2, 2009 at 7:24 pm

  7. i want to write a script that wil generate the record value of my form but im finding very dificult to do that. i need help please

    haidan

    November 22, 2009 at 6:46 pm

  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}’)

    Charles Howard

    August 5, 2011 at 6:04 pm

  9. Hi,

    Is there a way to save more dan one JSvalues wit a single command button ?

    dips

    August 30, 2011 at 10:41 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: