Thursday, 30 April 2009

ADF 11g - Groovy expression for default value of todays date

I have an EO with one Date column which I wanted to default to today's date on record creation. Normally I would create a EO class and add the "create" method to the class to achieve this but I found it's even easier to use a groovy expression which I did as follows.

1. Double click on EO to bring it up in the code editor "Overview" tab.
2. Click on attributes
3. Select the "Date" attribute and press the edit icon
4. Place the following into the "Value" field

String.format('%tF', new Date())

Note: This will ensure we retrieve today's date and format the date into the format which our Date EO attribute is using which in this case is "YYYY-MM-DD".

5. Select the check box "Expression" for the "Value Type"

Note: You can also use the built in Groovy expressions adf.currentDate and adf.currentDateTime that you can use.

6. Press OK.

Now when we create a new record the default value for the date will be todays date using a groovy expression.

You can see from this groovy script that unless we format the output ADF will throw a runtime error with just the use of new Date() without any formatting.

Groovy Script:

def today= new Date() //represents the date and time when it is created
println today

println String.format('%tF', today)


Thu Apr 30 11:51:54 EST 2009

More information on groovy and ADF can be found here.

No comments: