Tuesday, February 1, 2005

Fun With Value Binding

WARNING: This blog entry was imported from my old blog on blogs.sun.com (which used different blogging software), so formatting and links may not be correct.


JSF supports Value Binding, which allows you to do some really
cool things, really easily. For example, lets say you have a Data Table,
and in one
of the columns you want to show a name. However, that name is really
two columns in the database: FIRSTNAME and LASTNAME. When you drop
the datasource on the Data Table, you end up with two columns - one
with the first name, and one with the last name.



How can you have the data table show "First Last" in a single column?
Just go to the
JSP and locate the section which looks something like this:


<h:outputText binding="#{MyPage.outputText1}" id="outputText1" value="#{currentRow['FIRSTNAME']}"/>

I've made the value binding expression in the above bold so it stands out.
You can change the value binding expression to this

value="#{currentRow['FIRSTNAME']} #{currentRow['LASTNAME']}"

or if you prefer a "Last, First" format,

value="#{currentRow['LASTNAME']}, #{currentRow['FIRSTNAME']}"

When you run the application, the full value binding expresison
(with multiple column lookups) will be computed and rendered into
your single column in the data table.
(Remember to delete the "other" column that we didn't modify - it's
still showing the last name.)



Let's say you want to do something more complicated - you don't just
want to concatenate these expressions with some text in between, you
want to make dynamic decisions about what to include. For that, use
property binding.



Let's say you have two columns in your rowset - "Location", and
"OverrideLocation" (probably from a join on a couple of different database
tables). Location is the default, but whenever OverrideLocation
is nonempty, you want to use that instead. In this case, open your page's Java
file (the so-called Page Bean), and add a method like this:


/** Produce a location based on the default location and the location override */
public String getLocation() {
String override = (String)getValue("#{currentRow['OVERRIDELOCATION']}");
if (override != null && override.length() > 0) {
return override;
}
return (String)getValue("#{currentRow['LOCATION']}");
}

Now, simply go and bind your database column to this property! That's easy
- click on the OutputText component in the data table, then right click,
choose Property Bindings..., and in the dialog, make sure the
"value" property is selected on the left, and on the right, drill to this
page's page bean, and locate the "location" property and select it. Hit
ok and you're done.



This technique allows you to really easily "massage"
your Data Table components (and obviously any other data bound components)
to display the information in the way you want, regardless of the actual
column layout in your database schema.


No comments:

Post a Comment