7 Adding Business Logic to Data Controls

This chapter describes how to configure your data controls with declarative metadata, such as default labels for attributes, new transient attributes, validation rules, and built-in search criteria. In addition, this chapter shows how you can test the data controls that you have configured before you use them in an application and provides a reference on using Groovy expressions in data controls.

This chapter includes the following sections:

Introduction to Adding Business Logic to Data Controls

Business services that you expose in the ADF data model of an ADF application support defining additional functionality, such as configuring default attribute values. JDeveloper applies this additional functionality to UI components that you drag and drop from the Data Controls panel into web pages of the ADF application.

When you generate data controls, you can use them without further modification to create bindings between your data model and the UI components in your application. In addition, you can configure the data controls to add business logic and other features to your data model so that those features are applied when you use the Data Controls panel to create UI components. For example, depending on the type of data control you are creating, you can do the following things:

  • Configure default values for attributes

  • Add labels and tooltips for attributes

  • Add custom metadata (typically name-value pairs) that can be referenced via expression language (EL) from the ADF Faces UI

  • Add calculated attributes

  • Add attribute-level validation rules with custom error messages

  • Define declarative search forms

Configuring Data Controls

Business services that you expose in the ADF data model of an ADF application support configuring values and behavior through data control structure files. JDeveloper applies this additional functionality to UI components that you drag and drop from the Data Controls panel into web pages of the ADF application.

When you create a data control, a standard set of values and behaviors are assumed for the data control. For example, the data control determines how the label for an attribute will display in a client. You can configure these values and behaviors by creating and modifying data control structure files that correspond to the elements of the data control. You first generate a data control structure file using the overview editor for the .dcx file.

How to Edit a Data Control

You can make a data control configurable by using the overview editor for the DataControls.dcx file to create data control structure files that correspond to objects encompassed by the data control. You can then edit the individual data control structure files.

Before you begin:

It may be helpful to have a general understanding of data control configuration. For information on data controls, see Configuring Data Controls.

You also need to create a data control, as described in How to Create ADF Data Controls.

To edit a data control:

  1. In the Applications window, double-click DataControls.dcx.
  2. In the overview editor, select the object that you would like to configure and click the Edit icon to generate a data control structure file, as shown in Figure 7-1.

    Figure 7-1 Edit Button in Data Controls Registry

    This image is described in the surrounding text.
  3. In the overview editor of the data control structure file, make the desired modifications.

What Happens When You Edit a Data Control

When you edit a data control, JDeveloper creates a data control structure file that contains metadata for the affected collection and opens that file in the overview editor. This file stores configuration data for the data control that is specific to that collection, such as any UI hints or validators that you have specified for the data object.

A data control structure file has the same base name as the data object with which it corresponds. For example, if you click the Edit icon when you have a collection node selected that corresponds with the Customer.java entity bean, the data control structure file is named Customer.xml. The data control structure file is generated in a package that corresponds to the package of the bean class, but with persdef prepended to the package name. For example, if the Customer.java bean is in the model package, the Customer.xml data control definition file is generated in the persdef.model package. Once a data control structure file has been generated, you can use the overview editor for that file to make further configurations.

A data control structure file contains the following information:

  • Attributes: Describes all of the attributes on the service. For example, for entity beans, there is an attribute for each bean property that is mapped to a database column. You can also add transient attributes. You can set UI hints that define how these attributes will display in the UI. You can also set other properties, such as whether the attribute value is required, whether it must be unique, and whether it is visible. For information on attributes, see Working with Attributes.

    You can also set validation for an attribute and create custom properties. For information on validation, see Defining Validation Rules on Attributes Declaratively. For information on custom properties, see How to Implement Generic Functionality Driven by Custom Properties in Developing Fusion Web Applications with Oracle Application Development Framework.

  • Accessors: Describes data control elements that return result sets.

  • Named Criteria: Enables you to create rules to filter the rows that are presented. Named criteria are available for JPA-based data controls.

    For information on named criteria, see Filtering Result Sets with Named Criteria.

  • List of Values: Enables you to create declarative associations between an attribute of the current data object and rows from another data object. You can then create components from these associations such as dropdown lists.

  • Operations: Describes methods on the data object that are used by the data control's built-in operations, such as add and remove methods, which are used by the Create and Delete built-in operations, respectively.

Figure 7-2 shows the data control structure file for the Item bean.

Figure 7-2 Data Control Structure File in the Overview Editor

Description of Figure 7-2 follows
Description of "Figure 7-2 Data Control Structure File in the Overview Editor"

Note:

The overview editor of a data control structure file shows all of the attributes, accessors, and operations that are associated with the data object. However, the data control structure file's XML source only contains definitions for elements that you have edited. The base elements are introspected from the data object. Also, when you make changes to the underlying data object, the data control inherits those changes.

How to Convert Data Controls from a Previous Release

The format of data control structure files changed in Release 11.1.2 to enable additional features, such as named criteria and list of values. In addition, data control structure files are now only generated on demand, such as when you need to add metadata to a data control object or if you have them generated when creating the data control. There is no longer metadata for data control objects that merely repeats information that is already available in the object on which the data control is based. For JPA-based data controls, UpdatableSingleValue.xml and UpdateableCollection.xml files are no longer generated.

If you have a data control from a previous release, you can continue using that data control in applications that you develop with later versions of JDeveloper. However, if you plan to make changes to that data control, you must first convert the data control to the new format. Modification of data controls in the old format is not supported.

Converting an old data control to use the current structure definition format involves a few changes to the DataControls.dcx file, such as updating the entry for the implementation class from the following table.

Table 7-1 Data Control Implementation Classes

Data Control Type Data Control Implementation Class

EJB

oracle.adfinternal.model.adapter.ejb.EjbDCDefinition

Bean

oracle.adf.model.adapter.bean.BeanDCDefinition

Web Service

oracle.adfinternal.model.adapter.webservice.WSDefinition

URL Service

oracle.adfinternal.model.adapter.url.URLDCDefinition

You will also need to generate the new data control structure files. But, you do not need to rebind existing UI components to the updated data control.

To migrate a data control from a previous release:

  1. In the current version of JDeveloper, open the application workspace that contains the data control.

  2. Open the DataControls.dcx file and make the following changes:

    • Change the value of the ImplDef attribute to the name of the appropriate data control implementation class, as shown in Table 7-1.

    • Optionally, for bean and EJB data controls, add a DataControlHandler attribute to the data control's bean-definition or ejb-definition element to enable full query and paging support. For JPA-based data controls, typically you would typically use oracle.adf.model.adapter.bean.jpa.JPQLDataFilterHandler. For non-JPA data controls you typically use oracle.adf.model.adapter.bean.DataFilterHandler.

    • Optionally, for JPA-based bean and EJB data controls, add an accessMode attribute to the data control's bean-definition or ejb-definition element to specify the type of paging for the data control. The value of the accessMode can be scrollable or rangePaging.

    • Optionally, for JPA-based bean and EJB data controls, add an eagerPersist attribute to the data control's bean-definition or ejb-definition element to specify whether new records are persisted eagerly. The value of eagerPersist can be false or true.

  3. For data controls to which you have added metadata (such as UI hints or validators), create new data control structure files.

  4. Optionally, in the data control's project, delete the old data control structure files. These include:

    • UpdatableSingleValue.xml

    • UpdateableCollection.xml

    • Files ending in .xml that contain metadata for a data control object (not including the new files that you generated in step 3.

The following example shows a converted DataControls.dcx file.

<?xml version="1.0" encoding="UTF-8" ?>
<DataControlConfigs xmlns="http://xmlns.oracle.com/adfm/configuration"
                    version="11.1.1.61.92" id="DataControls" Package="model1">
  <AdapterDataControl id="BeanPagingDC1"
                    FactoryClass="oracle.adf.model.adapter.DataControlFactoryImpl"
                    ImplDef="oracle.adf.model.adapter.bean.BeanDCDefinition"
                    SupportsTransactions="false" SupportsSortCollection="true"
                    SupportsResetState="false" SupportsRangesize="false"
                    SupportsFindMode="false" SupportsUpdates="true"
                    Definition="model1.BeanPagingDC1"
                    BeanClass="model1.BeanPagingDC1"
                    xmlns="http://xmlns.oracle.com/adfm/datacontrol">
    <CreatableTypes>
      <TypeInfo FullName="model1.SampleData1"/>
      <TypeInfo FullName="model1.BeanPagingDC1"/>
    </CreatableTypes>
    <Source>
      <bean-definition BeanClass="model1.BeanPagingDC1"                            
        DataControlHandler="oracle.adf.model.adapter.bean.DataFilterHandler"
        AccessMode="scrollable"
        xmlns="http://xmlns.oracle.com/adfm/adapter/bean"/>
    </Source>
  </AdapterDataControl>
</DataControlConfigs>

What You May Need to Know About MDS Customization of Data Controls

If you wish for all of the objects that are encompassed by the data control to be available for Oracle Metadata Services (MDS) customization, the packaged application must contain data control structure files for those objects.

When you create a data control based on the adapter framework, data control structure files are not generated by default, since they are not needed by the data control if you do not add metadata to a given object. Typically, a data control structure file is only generated for a data control object once you edit the data control to add declarative metadata (such as UI hints or validators) to that object, as described in How to Edit a Data Control. To create data control structure files for each data control object, you need to repeat that procedure for each data control object.

Note:

In the Create EJB Data Control and the Create Bean Data Control wizards, there is a Generate Metadata checkbox that you can select in order to have structure files for each data control object generated upon creation of the data control.

For information on MDS, see Customizing Applications with MDS in Developing Fusion Web Applications with Oracle Application Development Framework.

Working with Attributes

Business services that you expose in the ADF data model of an ADF application support defining UI hints for the attributes of the data control, such as configuring default attribute values. JDeveloper applies this additional functionality to UI components that you drag and drop from the Data Controls panel into web pages of the ADF application.

When you create a data control for your business services, you can create a data control structure file for an individual data object in which you can declaratively augment the functionality of the data object's persistent attributes. For example, you can create validation rules and set UI hints to control the default presentation of attributes in UI components. In addition, you can create transient attributes.

In all cases, you set these properties on the Attributes page of the overview editor of the data control structure file. For information on creating a data control structure file, see How to Edit a Data Control.

How to Designate an Attribute as Primary Key

In the overview editor for a data object's data control structure file, you can designate an attribute as a primary key for that data object if you have not already done so in the data object's underlying class.

Before you begin:

It may be helpful to have an understanding of how you set attribute properties. For information on attribute properties, see Working with Attributes.

You also need to create the desired data control structure files as described in How to Edit a Data Control.

To set an attribute as a primary key:

  1. In the Applications window, double-click the desired data control structure file.
  2. In the overview editor, click the Attributes navigation tab.
  3. On the Attributes page, select the attribute you want to designate as the primary key and then click the Details tab.
  4. On the Details page, set the Key Attribute property.

Note:

If the attribute has already been designated as the primary key in the class (such as through the JPA @ID annotation), the data control inherits that setting and the Key Attribute checkbox will be selected. However, in this case, you can not deselect the Key Attribute option.

How to Control the Updatability of an Attribute

The Updatable property controls whether the value of a given attribute can be updated. You can select the following values for the Updatable property:

  • Always - the attribute is always updatable

  • Never- the attribute is read-only

  • While New- the attribute can be set during the transaction that creates the row for the first time, but after being successfully committed to the database the attribute is read-only

Before you begin:

It may be helpful to have an understanding of how you set attribute properties. For information on attribute properties, see Working with Attributes.

You also need to create the desired data control structure files as described in How to Edit a Data Control.

To set the updatability of an attribute:

  1. In the Applications window, double-click the desired data control structure file.
  2. In the overview editor, click the Attributes navigation tab.
  3. On the Attributes page, select the attribute you want to edit, and then click the Details tab.
  4. On the Details page, select a value from the Updatable dropdown list.

How to Define a Static Default Value for an Attribute

The Value field in the Details section allows you to specify a static default value for the attribute when the value type is set to Literal. For example, you might set the default value of a ServiceRequest entity bean's Status attribute to Open, or set the default value of a User bean's UserRole attribute to user.

Before you begin:

It may be helpful to have an understanding of how you set attribute properties. For information on attribute properties, see Working with Attributes.

To define a static default value for an attribute:

  1. In the Applications window, double-click the desired data control structure file.
  2. In the overview editor, click the Attributes navigation tab.
  3. On the Attributes page, select the attribute you want to edit, and then click the Details tab.
  4. On the Details page, select the Literal option.
  5. In the text field below the Literal option, enter the default value for the attribute.

How to Define a Default Value Using a Groovy Expression

You can use a Groovy expression to define a default value for an attribute. This approach is useful if you want to be able to change default values at runtime. However, if the default value is always the same, the value is easier to see and maintain using value field with the Literal type (on the Details tab). For general information Groovy expression, see Groovy Language Support.

Before you begin:

It may be helpful to have an understanding of how you set attribute properties. For information on attribute properties, see Working with Attributes.

You also need to create the desired data control structure files as described in How to Edit a Data Control.

To define a default value using a Groovy expression:

  1. In the Applications window, double-click the desired data control structure file.
  2. In the overview editor, click the Attributes navigation tab.
  3. On the Attributes page, select the attribute you want to edit, and then click the Details tab.
  4. On the Details page, select Expression for the default value type, and click the Edit button next to the adjoining text field.
  5. In the Edit Expression dialog, enter an expression in the field provided.

    Attributes that you reference can include any attribute that is defined for the data object.

  6. If the attribute is transient, select the appropriate recalculate setting, as shown in Figure 7-3.

    Figure 7-3 Edit Expression Editor

    This image is described in the surrounding text

    If you select Always (default), the expression is evaluated each time any attribute in the row changes.

    If you select Never, the expression is evaluated only when the row is created.

    If you select Based on the following expression, you can provide an expression that determines when to recalculate the attribute value.

    For example, the following expression in the Based on the following expression field causes the attribute to be recalculated when either the Quantity attribute or the UnitPrice attribute are changed:

    return (adf.object.dataProvider.isAttributeChanged("Quantity") || adf.object.dataProvider.isAttributeChanged("UnitPrice"));
    
  7. In the Available list at the bottom of the dialog, select any attributes upon which the value expression or the optional recalculate expression is based and shuttle each to the Selected list.
  8. Click OK to save the expression.

What Happens When You Create a Default Value Using a Groovy Expression

When you define a default value using a Groovy expression, <RecalcCondition> and <TransientExpression> tags are added within the tag for the corresponding attribute in the data control structure file. In addition, a <Dependencies> tag is added if you have specified any dependencies for the expression. The following example shows the code that is added to the LineItemTotal attribute when an expression is written to define the default value as the product of the price and quantity attributes and the recalculate condition is specified as Always.

<RecalcCondition><![CDATA[true]]></RecalcCondition>
<TransientExpression><![CDATA[price * quantity]]></TransientExpression>
<Dependencies>
  <Item
    Value="price"/>
  <Item
    Value="quantity"/>
</Dependencies>

How to Set UI Hints on Attributes

You can set UI hints on attributes so that those attributes are displayed and labeled in a consistent and localizable way by any UI components that use those attributes. To create UI hints for attributes, use the overview editor for the data object's data control structure file, which is accessible from the Applications window.

Note:

As an alternative to using data control structure files to set UI hints for EJB and bean data controls, you can add annotations directly to the bean classes to create much of the same functionality. For information on adding annotations to the bean classes, see Providing UI Hints for Attributes Using Annotations.

Before you begin:

It may be helpful to have an understanding of how you set attribute properties. For information on attribute properties, see Working with Attributes.

You also need to create the desired data control structure files as described in How to Edit a Data Control.

To set a UI hint:

  1. In the Applications window, double-click the desired data control structure file.
  2. In the overview editor, click the Attributes navigation tab.
  3. On the Attributes page, select the attribute you want to edit, and then click the UI Hints tab.
  4. In the UI Hints section, set the desired UI hints.

For information on the various UI hints, see the Defining UI Hints for View Objects section of Developing Fusion Web Applications with Oracle Application Development Framework.

Note:

The view objects referenced in Developing Fusion Web Applications with Oracle Application Development Framework are ADF Business Components used to encapsulate SQL queries and to simplify working with the results. Data control structure files function much like view objects in adapter data controls and provide many of the same configuration options. For information on view objects, see About View Objects in Developing Fusion Web Applications with Oracle Application Development Framework.

What Happens When You Set UI Hints on Attributes

When you set UI hints on an attribute, those hints are stored as properties. Tags for the properties are added to the data object's data control structure file and the values for the properties are stored in a resource bundle file. If the resource bundle file does not already exist, it is generated in the data control's package and named according to the project name when you first set a UI hint.

The following example shows the code for the price attribute in the Item.xml data control structure file, including tags for the Label and Format Type hints which have been set for the attribute.

<PDefAttribute
  Name="price">
  <Properties>
    <SchemaBasedProperties>
      <LABEL
        ResId="${adfBundle['model.ModelBundle']['model.Item.price_LABEL']}"/>
      <FMT_FORMATTER
        ResId="${adfBundle['model.ModelBundle']['model.Item.price_FMT_
                                                       FORMATTER']}"/>
    </SchemaBasedProperties>
  </Properties>
</PDefAttribute>

The following example shows the corresponding entries for the Label and Format Type hints in the ModelBundle.properties resource bundle file, which contains the values for all of the project's localizable properties.

model.Item.price_LABEL=Price
. . .
model.Item.price_FMT_FORMATTER=oracle.jbo.format.DefaultCurrencyFormatter

Adding Transient Attributes to a Data Object

Business services that you expose in the ADF data model of an ADF application support adding attributes that are not persistent to the data control and defining calculated values. JDeveloper applies this additional functionality to UI components that you drag and drop from the Data Controls panel into web pages of the ADF application.

In addition to having attributes that map to columns in an underlying table, your data control structure files can include transient attributes that display calculated values.

For example, a transient attribute you create, such as FullName, could be calculated based on the concatenated values of FirstName and LastName attributes.

Once you create the transient attribute, you can use a Groovy expression in the attribute definition to specify a default value.

How to Add a Transient Attribute

Use the Attributes page of the overview editor to create a transient attribute.

Before you begin:

It may be helpful to have an understanding of transient and calculated attributes. For information on transient attributes, see Adding Transient Attributes to a Data Object.

You also need to create the desired data control structure files as described in How to Edit a Data Control.

To add a transient attribute to a data object's data control structure file:

  1. In the Applications window, double-click the data object's data control structure file.
  2. In the overview editor, click the Attributes navigation tab, and then click the Create new attribute icon.
  3. In the New View Attribute dialog, enter a name for the attribute and click OK.
  4. On the Attributes page of the overview editor, click the Details tab and select an object type from the Type dropdown list.
  5. Optionally, in the Default Value section, set a default value or enter an expression to calculate the default value.
  6. If the value will be calculated with an expression, set Updatable to Never.

    For information on setting an expression to calculate the default value, see How to Define a Default Value Using a Groovy Expression.

What Happens When You Add a Transient Attribute

When you add a transient attribute, JDeveloper adds a <ViewAttribute> tag to the data object's data control structure file to reflect the new attribute. The following example shows the XML code for a transient attribute named LineItemTotal that is based on an expression that multiplies the values of the price and quantity attributes.

<ViewAttribute
  Name="LineItemTotal"
  IsUpdateable="false"
  IsSelected="false"
  IsPersistent="false"
  PrecisionRule="true"
  Type="java.lang.String"
  ColumnType="$none$">
  SQLType="VARCHAR">
  <RecalcCondition><![CDATA[true]]></RecalcCondition>
  <TransientExpression><![CDATA[price * quantity]]></TransientExpression>
  <Dependencies>
    <Item
      Value="price"/>
    <Item
      Value="quantity"/>
  </Dependencies>
 </ViewAttribute>

Defining Validation Rules on Attributes Declaratively

Business services that you expose in the ADF data model of an ADF application support defining attribute value validation rules on the data control. JDeveloper applies this additional functionality to UI components that you drag and drop from the Data Controls panel into web pages of the ADF application.

The easiest way to create and manage validation rules is through declarative validation rules. Declarative validation rules are defined using the overview editor, and once created, are stored in the data object's data control structure file. Encapsulating the business logic this way ensures that your business information is validated consistently in every client that accesses it, and it simplifies maintenance by centralizing where the validation is stored.

Oracle ADF provides built-in declarative validation rules for many common business needs. You can also base validation on a Groovy expression, as described in How to Use Groovy Expressions For Validation Rules.

When you add a validation rule, you supply an appropriate error message and can later translate it easily into other languages if needed. You can also set the severity level.

Many of the declarative validation features available for data objects are also available at the page definition level, should your application warrant the use of page-level validation in addition to business-layer validation. For information on page-level validation, see Using Validation in the ADF Model Layer in Developing Fusion Web Applications with Oracle Application Development Framework.

Note:

You can also add validation rules by implementing a custom validation class. This approach is particularly useful if you need to define complex parameterized validation rules (such as for checking credit card numbers) that you will need to use multiple times in your application. For information on the implementation of custom validation rules, see Implementing Custom Validation Rules in Developing Fusion Web Applications with Oracle Application Development Framework.

How to Add Validation Rules to Attributes

The process for adding a validation rule to a data object is similar for most of the validation rules, and is done using the Add Validation Rule dialog. You can open this dialog by opening the data object's data control structure file, selecting an attribute on Attributes page, clicking the Validation Rules tab, and then clicking the Add icon

It is important to note that when you define a rule declaratively using the Add Validation Rule dialog, the rule definition you provide specifies the valid condition for the attribute. At runtime, the entry provided by the user is evaluated against the rule definition, and an error or warning is raised if the entry fails to satisfy the specified criteria. For example, if you specify a Length validator on an attribute that requires it to be Less Than or Equal To 12, the validation fails if the entry is more than 12 characters, and the error or warning is raised.

To add a declarative validation rule to a data control structure file, use the Attributes page of the data object's overview editor.

Before you begin:

It may be helpful to have an understanding of the use of validation rules in data control structure files. For information on using validation rules, see Defining Validation Rules on Attributes Declaratively.

You also need to create the desired data control structure files as described in How to Edit a Data Control.

To add a validation rule:

  1. In the Applications window, double-click the desired data control structure file.
  2. In the overview editor, click the Attributes navigation tab.
  3. On the Attributes page, select the attribute for which you want to add the validation rule, and then click the Validation Rules tab.
  4. In the Validation Rules page, click the Add Validation Rule icon.
  5. In the Add Validation Rule dialog, select the type of validation rule desired from the Rule Type dropdown list.

    Note that the subordinate fields change depending on your choices.

  6. Use the dialog settings to configure the new rule.
  7. Click the Failure Handling tab and enter or select the error message that will be shown to the user if the validation rule fails.
  8. Click OK.

    For information on the different validation rules, see How to Use the Built-in Declarative Validation Rules.

    For information on error messages, see How to Create Validation Error Messages.

What Happens When You Add a Validation Rule

When you add a validation rule to a data object, JDeveloper updates the data object's data control structure file to include an entry describing what rule you've used and what rule properties you've entered.

For example, if you add a compare validation rule to the dateShipped attribute to ensure that the shipping date does not precede the date in the dateOrdered attribute, this results in a <validation:CompareValidationBean> entry in the XML file, as shown in the following example.

<validation:CompareValidationBean
  Name="dateShipped_Rule_0"
  ResId="${adfBundle['model.ModelBundle']['model.Ord.dateShipped_Rule_0']}"
  OnAttribute="dateShipped"
  OperandType="EXPR"
  Inverse="false"
  CompareType="GREATERTHANEQUALTO">
  <validation:TransientExpression><![CDATA[dateOrdered]]>
  </validation:TransientExpression>
</validation:CompareValidationBean>

How to Use the Built-in Declarative Validation Rules

The built-in declarative validation rules can satisfy many, if not all, of your business needs. These rules are easy to implement because you don't write any code. You use the user-interface tools to choose the type of validation and how it is used.

Built-in declarative validation rules can be used to:

  • Make a comparison between an attribute and literal value or expression.

  • Validate against a list of values that you provide manually.

  • Make sure that a value falls within a certain range, or that it is limited by a certain number of bytes or characters.

  • Validate using a regular expression or evaluate a Groovy expression.

Validating Based on a Comparison

The Compare validator performs a logical comparison between an attribute and a value. When you add a Compare validator, you specify an operator and something to compare with. You can compare the following:

  • Literal value

    When you use a Compare validator with a literal value, the value in the attribute is compared against the specified literal value. When using this kind of comparison, it is important to consider data types and formats. The literal value must conform to the format specified by the data type of the attribute to which you are applying the rule. In all cases, the type corresponds to the type mapping for the attribute.

    For example, an attribute of column type DATE maps to the oracle.jbo.domain.Date class, which accepts dates and times in the same format accepted by java.sql.TimeStamp and java.sql.Date. You can use format masks to ensure that the format of the value in the attribute matches that of the specified literal.

  • Expression

    For information on the expression option, see How to Use Groovy Expressions For Validation Rules.

Before you begin:

It may be helpful to have an understanding of the use of validation rules in data control structure files. For information on using validation rules, see Defining Validation Rules on Attributes Declaratively.

You also need to create the desired data control structure files as described in How to Edit a Data Control.

To validate based on a comparison:

  1. In the Applications window, double-click the desired data control structure file.
  2. In the overview editor, click the Attributes navigation tab.
  3. On the Attributes page, select the attribute for which you want to add the validation rule, and then click the Validation Rules tab.
  4. In the Validation Rules page, click the Add Validation Rule icon.
  5. In the Add Validation Rule dialog, in the Rule Type dropdown list, select Compare.
  6. Select the appropriate operator.
  7. Select an item in the Compare With list, and based on your selection provide the appropriate comparison value.
  8. Click the Failure Handling tab and enter or select the error message that will be shown to the user if the validation rule fails.
  9. Click OK.
For information on validation error messages, see How to Create Validation Error Messages.
What Happens When You Validate Based on a Comparison

When you create a Compare validator, a <validation:CompareValidationBean> tag is added to the data object's data control structure file.

The example in What Happens When You Add a Validation Rule shows the XML code for the validator on the dateShipped attribute.

Validating Using a List of Values

The List validator compares an attribute against a list of values that you provide manually. The validator ensures that the value of the data object attribute is in (or not in, if specified) that list.

Before you begin:

It may be helpful to have an understanding of the use of validation rules in data control structure files. For information on using validation rules, see Defining Validation Rules on Attributes Declaratively.

You also need to create the desired data control structure files as described in How to Edit a Data Control.

To validate using a list of values:

  1. In the Applications window, double-click the desired data control structure file.
  2. In the overview editor, click the Attributes navigation tab.
  3. On the Attributes page, select the attribute for which you want to add the validation rule, and then click the Validation Rules tab.
  4. In the Validation Rules page, click the Add Validation Rule icon.
  5. In the Add Validation Rule dialog, in the Rule Type dropdown list, select List.
  6. In the Operator field, select In or NotIn, depending on whether you want an inclusive list or an exclusive list.
  7. In the Enter List of Values section, enter the values, one per line.
  8. Click the Failure Handling tab and enter or select the error message that will be shown to the user if the validation rule fails.
  9. Click OK.
For information on validation error messages, see How to Create Validation Error Messages.
What Happens When You Validate Using a List of Values

When you validate using a list of values, a <validation:ListValidationBean> tag is added to the data object's data control structure file.

Ensuring That a Value Falls Within a Certain Range

The Range validator performs a logical comparison between an attribute and a range of values. When you add a Range validator, you specify minimum and maximum literal values. The Range validator verifies that the value of the attribute falls within the range (or outside the range, if specified).

If you need to dynamically calculate the minimum and maximum values, or need to reference other attributes, use the Script Expression validator and provide a Groovy expression. For information on referencing ADF objects in groovy expressions, see How to Reference ADF Objects in Groovy Expressions.

Before you begin:

It may be helpful to have an understanding of the use of validation rules in data control structure files. For information on using validation rules, see Defining Validation Rules on Attributes Declaratively.

You also need to create the desired data control structure files as described in How to Edit a Data Control.

To validate within a certain range:

  1. In the Applications window, double-click the desired data control structure file.
  2. In the overview editor, click the Attributes navigation tab.
  3. On the Attributes page, select the attribute for which you want to add the validation rule, and then click the Validation Rules tab.
  4. In the Validation Rules page, click the Add Validation Rule icon.
  5. In the Add Validation Rule dialog, in the Rule Type dropdown list, select Range.
  6. In the Operator field, select Between or NotBetween.
  7. In the Minimum Value and Maximum Value fields, enter appropriate values.
  8. Click the Failure Handling tab and enter or select the error message that will be shown to the user if the validation rule fails.
  9. Click OK.
For information on validation error messages, see How to Create Validation Error Messages.
What Happens When You Use a Range Validator

When you validate against a range, a <validation:RangeValidationBean> tag is added to the data control structure file.

The following example shows the quantity attribute with a minimum of zero and a maximum of 10.

<PDefAttribute
  Name="quantity">
  <validation:RangeValidationBean
    Name="quantity_Rule_0"
    ResId="${adfBundle['model.ModelBundle']['QUANTITY_VALIDATOR']}"
    OnAttribute="quantity"
    OperandType="LITERAL"
    Inverse="false"
    MinValue="0"
    MaxValue="10"/>
. . .
</PDefAttribute>
Validating Against a Number of Bytes or Characters

The Length validator validates whether the string length (in characters or bytes) of an attribute's value is less than, equal to, or greater than a specified number, or whether it lies between a pair of numbers. For example, you might have a field where the user enters a password or PIN and you need to validate that it is at least 6 characters long, but not longer than 10.

Before you begin:

It may be helpful to have an understanding of the use of validation rules in data control structure files. For information on using validation rules, see Defining Validation Rules on Attributes Declaratively.

You also need to create the desired data control structure files as described in How to Edit a Data Control.

To validate against a number of bytes or characters:

  1. In the Applications window, double-click the desired data control structure file.
  2. In the overview editor, click the Attributes navigation tab.
  3. On the Attributes page, select the attribute for which you want to add the validation rule, and then click the Validation Rules tab.
  4. In the Validation Rules page, click the Add Validation Rule icon.
  5. In the Add Validation Rule dialog, in the Rule Type dropdown list, select Length.
  6. In the Operator field, select how to evaluate the value.
  7. In the Comparison Type field, select Byte or Character and enter a length in the Value field.
  8. Click the Failure Handling tab and enter or select the error message that will be shown to the user if the validation rule fails.
  9. Click OK.
For information on validation error messages, see How to Create Validation Error Messages.
What Happens When You Validate Against a Number of Bytes or Characters

When you validate using length, a <validation:LengthValidationBean> tag is added to the data control structure file. The following example shows the Between operator with a minimum value of 6 and a maximum value of 10.

    <validation:LengthValidationBean
      OnAttribute="pin"
      CompareType="BETWEEN"
      DataType="CHARACTER"
      MinValue="6"
      MaxValue="10"
      Inverse="false"/>
Validating Using a Regular Expression

The Regular Expression validator compares attribute values against a mask specified by a Java regular expression.

If you want to create expressions that can be personalized in metadata, you can use the Script Expression validator. For information on using the script expression validator, see How to Use Groovy Expressions For Validation Rules.

Before you begin:

It may be helpful to have an understanding of the use of validation rules in data control structure files. For information on using validation rules, see Defining Validation Rules on Attributes Declaratively.

You also need to create the desired data control structure files as described in How to Edit a Data Control.

To validate using a regular expression:

  1. In the Applications window, double-click the desired data control structure file.
  2. In the overview editor, click the Attributes navigation tab.
  3. On the Attributes page, select the attribute for which you want to add the validation rule, and then click the Validation Rules tab.
  4. In the Validation Rules page, click the Add Validation Rule icon.
  5. In the Add Validation Rule dialog, in the Rule Type dropdown list, select Regular Expression.
  6. In the Operator field, you can select Matches or Not Matches.
  7. To use a predefined expression (if available), you can select one from the dropdown list and click Use Pattern. Otherwise, write your own regular expression in the field provided.
  8. Click the Failure Handling tab and enter or select the error message that will be shown to the user if the validation rule fails.
  9. Click OK.

For information on validation error messages, see How to Create Validation Error Messages.

Figure 7-4 shows what the dialog looks like when you select a Regular Expression validator and validate that the Email attribute matches a predefined Email Address expression.

Figure 7-4 Regular Expression Validator Matching Email Address

This image is described in the surrounding text
What Happens When You Validate Using a Regular Expression

When you validate using a regular expression, a <RegExpValidationBean> tag is added to the data control structure file. The following example shows an Email attribute that must match a regular expression.

<validation:RegExpValidationBean
  Name="Email_Rule_0"
  OnAttribute="Email"
  Pattern="[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}"
  Flags="CaseInsensitive"
  Inverse="false"/>

How to Use Groovy Expressions For Validation Rules

Groovy expressions are Java-like scripting code stored in the data control structure file. You can even change or specify values at runtime.

For information on creating validation rules, see Defining Validation Rules on Attributes Declaratively.

For information on using Groovy expressions in your business logic, see Groovy Language Support.

Validating Using a Groovy Expression

You can use a Groovy expression to return a true/false statement. The Script Expression validator requires that the expression either return true or false, or that it calls the adf.error.raise/warn() method. A common use of this feature would be to validate an attribute value, for example, to make sure that an account number is valid.

Note:

Using the adf.error.raise() and adf.error.warn() methods (rather than simply returning true or false) allows you to define the message text to show to the user, and to associate a validator with a specific attribute. For information on raising error messages, see Raising Error Message Conditionally Using Groovy.

Before you begin:

It may be helpful to have an understanding of validation in data control structure files. For information on using validation rules, see Defining Validation Rules on Attributes Declaratively.

You may also find it helpful to understand the use of Groovy in validation rules. For information on using groovy expressions in validation rules, see How to Use Groovy Expressions For Validation Rules.

You also need to create the desired data control structure files as described in How to Edit a Data Control.

To validate using a true/false expression:

  1. In the Applications window, double-click the desired data control structure file.
  2. In the overview editor, click the Attributes navigation tab.
  3. On the Attributes page, select the attribute for which you want to add the validation rule, and then click the Validation Rules tab.
  4. In the Validation Rules page, click the Add Validation Rule icon.
  5. In the Add Validation Rule dialog, in the Rule Type dropdown list, select Script Expression.
  6. Enter a validation expression in the field provided.
  7. Click the Failure Handling tab and enter or select the error message that will be shown to the user if the validation rule fails.
  8. Click OK.
For information on validation error messages, see How to Create Validation Error Messages.
What Happens When You Validate Based on a Groovy Expression

When you create a Groovy expression, it is saved in the data object's data control structure file. The Groovy expression is wrapped by a <TransientExpression> tag. For some Groovy expressions, the <TransientExpression> tag is wrapped by a <validation:ExpressionValidationBean> tag as well.

Referencing Data Object Methods in Groovy Validation Expressions

You can call methods on the data object using the adf.source.dataProvider property of the current object. The adf.source.dataProvider property allows you to access the data object that is being validated.

If the method is a non-boolean type and the method name is getXyzAbc() with no arguments, then you access its value as if it were a property named XyzAbc. For example, the following Groovy expression would call the getXyzAbc() method.

adf.source.dataProvider.XyzAbc

For a Boolean property, the same holds true but the JavaBeans component naming pattern for the getter method changes to recognize isXyzAbc() instead of getXyzAbc(). If the method on your data object does not match the JavaBeans getter method naming pattern, or if it takes one or more arguments, then you must call it like a method using its complete name.

How to Create Validation Error Messages

Validation error messages provide important information for the user: the message should convey what went wrong and how to fix it.

Creating Validation Error Messages

Before you begin:

It may be helpful to have an understanding of the use of validation rules in data control structure files. For information on using validation rules, see Defining Validation Rules on Attributes Declaratively.

You also need to create the desired data control structure files as described in How to Edit a Data Control.

To create validation error messages:

  1. In the Applications window, double-click the desired data control structure file.
  2. In the overview editor, click the Attributes navigation tab.
  3. On the Attributes page, select the attribute for which you want to create the validation error message, and then click the Validation Rules tab.
  4. In the Validation Rules page, select the validation rule that you want to edit and click the Edit Validation Rule icon.
  5. In the Edit Validation Rule dialog, click the Failure Handling tab.
  6. In the Message Text field, enter your error message.

    You can also define error messages in a message bundle file. To select a previously defined error message or to define a new one in a message bundle file, click the Select Message icon in the top right corner of the Message Text field to open the Select Text Resource dialog.

    Note:

    The Script Expression validator allows you to enter more than one error message. This is useful if the validation script conditionally returns different error or warning messages. For information on raising error messages using the script expression validator, see Raising Error Message Conditionally Using Groovy.

  7. Optionally, define a message token by entering the message token's name in curly braces ({}) within the text of the error message. An entry for the token will then appear in the Token Message Expressions list where you can then define an expression to determine the value of the message token.

    Figure 7-5 shows a failure message that contains a message token for a validation rule in the data control structure file.

  8. Click OK.

For information on this feature, see Embedding a Groovy Expression in an Error Message.

Figure 7-5 Failure Handling Message for a Validation Rule

This image is described in the surrounding text
What Happens When You Create a Validation Error Message

When you create an error message for a validation rule, it is saved in a .properties file. The .properties file and the message string are referenced from the ResId tag attribute of the validator's tag in the data control structure file.

The following example shows the validation rule tag's ResId attribute that specifies the location and key of the error message.

<validation:CompareValidationBean
  Name="dateShipped_Rule_0"
  ResId="${adfBundle['model.ModelBundle']['model.Ord.dateShipped_Rule_0']}"

Here is the corresponding entry in the .properties file which contains the error message.

model.Ord.dateShipped_Rule_0=Date Shipped cannot be before Date Ordered
Localizing Validation Messages

The error message is a translatable string and is managed in the same way as translatable UI hints in a message bundle file. To view the error message for the defined rule in the message bundle class, locate the key in the message bundle that corresponds to the ResId property in the data control structure file entry for the validator.

Raising Error Message Conditionally Using Groovy

You can use the adf.error.raise() and adf.error.warn() methods to conditionally raise one error message or another depending upon branching in the Groovy expression.

If the expression returns false (versus raising a specific error message using the raise() method), the validator calls the first error message associated with the validator.

The syntax of the raise() method takes one required parameter (the msgId to use from the message bundle), and optionally can take the attrName parameter.

You can use either of the adf.error.raise() and adf.error.warn() methods, depending on whether you want to throw an exception, or whether you want processing to continue, as described in How to Set the Severity Level for Validation Exceptions.

The following example shows a rule that will allow the input of value 5000 or under. If the value is above 5000, the error message tied to the SALARY_TOO_HIGH_ERROR resource bundle property is shown and validation fails. If the entered value is between 1001 and 5000, validation passes, but a warning is displayed to the user.

if (newValue > 1000)
{
if (newValue > 5000)
{adf.error.raise("SALARY_TOO_HIGH_ERROR")
return false}
adf.error.warn("SALARY_LIMIT_WARNING")
return true
}
else
{
return true
}
Embedding a Groovy Expression in an Error Message

A validator's error message can contain embedded expressions that are resolved by the server at runtime. To access this feature, simply enter a named token delimited by curly braces (for example, {2} or {errorParam}) in the error message text where you want the result of the Groovy expression to appear.

After entering the token into the text of the error message (on the Failure Handling tab of the Edit Validation Rule dialog), the Token Message Expressions table at the bottom of the dialog displays a row that allows you to enter a Groovy expression for the token. Figure 7-5 shows a failure message that contains a message token for a validation rule.

The expression shown in Figure 7-5 is a Groovy expression that returns the value of the quantity attribute. You can also use Groovy expressions to access attribute UI hints and other objects that are defined in the data control structure file.

You can use the Groovy expression newValue to return the entered value.

For information on accessing ADF objects using Groovy, see Groovy Language Support.

How to Set the Severity Level for Validation Exceptions

You can set the severity level for validation exceptions to either Informational Warning or Error. If you set the severity level to Informational Warning, an error message will display, but processing will continue. If you set the validation level to Error, the user will not be able to proceed until you have fixed the error.

Under most circumstances you will use the Error level for validation exceptions, so this is the default setting. However, you might want to implement an Informational Warning message if the user has a certain security clearance. For example, a store manager may want to be able to make changes that would surface as an error if a clerk tried to do the same thing.

To set the severity level for validation exceptions, use the Failure Handling tab of the Add Validation Rule dialog.

Before you begin:

It may be helpful to have an understanding of the use of validation rules in data control structure files. For information on using validation, see Defining Validation Rules on Attributes Declaratively.

You also need to create the desired data control structure files as described in How to Edit a Data Control.

To set the severity level of a validation exception:

  1. In the Applications window, double-click the desired data control structure file.
  2. In the overview editor, click the Attributes navigation tab.
  3. On the Attributes page, select the attribute for which you want to create the validation error message, and then click the Validation Rules tab.
  4. In the Validation Rules page, select the validation rule that you want to edit and click the Edit Validation Rule icon.
  5. In the Edit Validation Rule dialog, click the Failure Handling tab and select the option for either Error or Informational Warning.
  6. Click OK.

Filtering Result Sets with Named Criteria

Business services that you expose in the ADF data model of an ADF application support defining criteria objects to filter a collection of the data control. JDeveloper enables this functionality as query components that you drag and drop from the Data Controls panel into web pages of the ADF application.

JDeveloper enables you to create named criteria for data control structure files for JPA-based data controls. Named criteria can be used in the application's data model and can be exposed to users as seeded queries in search forms.

You can specify named criteria in order to filter results to display. The named criteria object is a row set of one or more named criteria rows, whose attributes mirror those in the corresponding data object. The named criteria definition comprises query conditions that function like the WHERE clause of an SQL query.

In the result set of a named criteria, the data type of each attribute is String, which enables the use of Query-by-Example operators. For example, this allows the user to enter conditions such as "OrderId > 304".

You use the Named Criteria page of the overview editor to define named criteria for specific data control structure files.

Use Case for Named Criteria

You create named criteria definitions when you need to filter individual accessor results. Named criteria that you define at design time can be used for easy creation of Query-by-Example search forms that allow the end user to supply values for attributes of the target data control structure file.

For example, the end user might want to be able to input the value of a customer name and the date to filter the results in a web page that displays the rows of a CustomerOrders collection. To satisfy that case, the web page designer can easily create a search form based on named criteria that have been created for this purpose and made available in the Data Controls panel. For information on the utilizing the named criteria in the Data Controls panel, see Creating ADF Databound Search Forms in Developing Fusion Web Applications with Oracle Application Development Framework.

How to Create Named Criteria Declaratively

To define named criteria for a JPA-based data control structure file, you open the data control structure file in the overview editor and use the Named Criteria page. A dedicated editor that you open from the Named Criteria page helps you to build the equivalent of a WHERE clause using attribute names (as opposed to SQL column names). You may define multiple named criteria for each data object.

Each named criteria definition consists of the following elements:

  • One or more named criteria rows consisting of an arbitrary number of named criteria groups or an arbitrary number of references to another named criteria already defined for the current data control structure file.

  • Optional named criteria groups consisting of an arbitrary number of named criteria items.

  • Named criteria items consisting of an attribute name, an attribute-appropriate operator, and an operand. Operands can be a literal value when the filter value is defined or a bind variable that can optionally utilize a scripting expression that includes dot notation access to attribute property values.

    Expressions are based on the Groovy scripting language, as described in Groovy Language Support.

Named criteria expressions you construct in the Edit View Criteria dialog use logical conjunctions to specify how to join the selected criteria item or criteria group with the previous item or group in the expression:

  • AND conjunctions specify that the query results meet both joined conditions. This is the default for each named criteria item you add.

  • OR conjunctions specify that the query results meet either or both joined conditions. This is the default for named criteria groups.

Additionally, you may create nested named criteria to have more control over the logical conjunctions among the various named criteria items. A nested named criteria group consists of an arbitrary number of nested named criteria items. The nested criteria place restrictions on the rows that satisfy the criteria under the nested criteria's parent named criteria group. For example, you might want to query both a list of employees with Salary > 3000 and belonging to DeptNo = 10 or DeptNo = 20. You can define a named criteria with the first group with one item (Salary > 3000) and a nested named criteria with the second group with two items (DeptNo = 10 and DeptNo =20).

Before you begin:

It may be helpful to have an understanding of named criteria. For information on named criteria, see Filtering Result Sets with Named Criteria.

You will need to complete these tasks:

To define a named criteria:

  1. In the Applications window, double-click the data control structure file for which you want to create the named criteria.
  2. In the overview editor, click the Named Criteria navigation tab.
  3. In the Named Criteria page, expand the Named Criteria section and click the Create new view criteria button.
  4. In the Create Named Criteria dialog, enter the name of the named criteria to identify its usage in your application.
  5. Click one of these Add buttons to define the named criteria.
    • Add Item to add a single criteria item. The editor will add the item to the hierarchy beneath the current group or named criteria selection. By default each time you add an item, the editor will choose the next attribute to define the criteria item. You can change the attribute to any attribute that the data control structure file defines.

    • Add Group to add a new group that will compose criteria items that you intend to add to it. When you add a new group, the editor inserts the OR conjunction into the hierarchy. You can change the conjunction as desired.

    • Add Criteria to add a named criteria that you intend to define. This selection is an alternative to adding a named criteria that already exists in the data control structure file. When you add a new named criteria, the editor inserts the AND conjunction into the hierarchy. You can change the conjunction as desired. Each time you add another named criteria, the editor nests the new named criteria beneath the current named criteria selection in the hierarchy. The root node of the hierarchy defines the named criteria that you are currently editing.

    • Add Named Criteria to add a named criteria that has already been defined in the data control structure file.

      Note:

      Search forms that the UI designer will create from named criteria are not able to use named criteria that contain other named criteria.

  6. Select a named criteria item node in the Named Criteria tree and define the added node in the Criteria Item section.
  7. Select the desired Attribute for the criteria item. By default the editor adds the first one in the list.
  8. Select the desired Operator.

    The list displays only the operators that are appropriate for the selected attribute. In the case of String and Date type attributes, the Between and Not between operators require you to supply two operand values to define the range. In the case of Date type attributes, you can select operators that test for a date or date range (with date values entered in the format YYYY-MM-DD). For example, for December 16th, 2010, enter 2010-12-16.

  9. Select the desired Operand for the named criteria item selection.
    • Select Literal when you want to supply a value for the attribute or when you want to define a default value for a user-specified search field for a Query-by-Example search form. When the named criteria defines a query search form for the user interface, you may leave the Value field empty. In this case, the user will supply the value. You may also provide a value that will act as a search field default value that the user will be able to override. The value you supply in the Value field can include the wildcard characters * or %.

    • Select Bind Variable when you want the value to be determined at runtime using a bind variable. Click New to display the Bind Variable dialog that lets you create a new bind variable for the data control structure file. For information on creating bind variables, see How to Use Bind Variables in Named Criteria.

  10. For each item, group, or nested named criteria that you define, optionally change the default conjunction to specify how the selection should be joined.
    • AND specifies that the query results meet both joined conditions. This is the default for each named criteria item or view nested named criteria that you add.

    • OR specifies that the query results meet either or both joined conditions. This is the default for named criteria groups.

  11. Optionally, to allow filtering based on the case of the runtime-supplied value, deselect the Ignore Case option. It is selected by default, preventing such filtering.

    The criteria item can be a literal value that you define or a runtime parameter that the end user supplies. This option is supported for attributes of type String only. The default disables case sensitive searches.

  12. In the Validation dropdown list, decide whether the named criteria item is a required or an optional part of the attribute value comparison in the generated WHERE clause.
    • Selectively Required means that the generated WHERE clause will ignore the named criteria item at runtime if no value is supplied and there exists at least one criteria item at the same level that has a criteria value. Otherwise, an exception is thrown.

    • Optional means the named criteria is added to the WHERE clause only if the value is non-NULL. The default Optional for each new named criteria item means no exception will be generated for null values.

    • Required means that the WHERE clause will fail to execute and an exception will be thrown when no value is supplied for the criteria item.

  13. If the named criteria uses a bind variable as the operand, decide whether the IS NULL condition is generated in the WHERE clause. This field is enabled only if you have selected Optional for the validation of the bind variable.
    • Leave Ignore Null Values selected (default) when you want to permit the named criteria to return a result even when the bind variable value is not supplied at runtime. When validation is set to Required or Optionally Required, the named criteria expects to receive a value and thus this option to ignore null values is disabled.

      For example, leaving this option selected for a bind variable that is used in a user search form would enable a user to see results from a search without having to fill in a value for the field with that bind variable.

    • Deselect Ignore Null Values when you expect the named criteria to return a null result when the bind variable value is not supplied at runtime.

      Note that the validation settings Required or Optionally Required also remove the null value condition but support a different use case. They should be used in combination with Ignore Null Values feature to achieve the desired runtime behavior.

  14. Click OK create the named criteria and return to the overview editor.

What Happens When You Create a Named Criteria

When you create a named criteria, the named criteria definition is added to the data control structure file and appears by name on the Named Criteria page of the overview editor.

To view XML code for the named criteria, open the source editor for the data control structure file. Each named criteria definition contains one or more <ViewCriteriaRow> elements corresponding to the number of groups that you define in the Create Named Criteria dialog.

How to Use Bind Variables in Named Criteria

Bind variables provide you with the means to supply attribute values that are calculated at runtime to the named criteria.

If the named criteria are to be used in a seeded search, you have the option of making the bind variable updatable by the end user. With this updatable option, end users will be expected to enter the value in the search form.

Named criteria execution need not require the bind variable value if the named criteria item for which the bind variable is assigned is not required. To enforce this desired behavior, the Bind Variable dialog lets you specify whether a bind variable is required or not.

You can define a default value for the bind variable or write scripting expressions for the bind variable that include dot notation access to attribute property values. Expressions are based on the Groovy scripting language, as described in Groovy Language Support.

To add a named bind variable to a named criteria, use the Named Criteria page of the overview editor for the data control structure file. You can define as many bind variables as you need.

Before you begin:

It may be helpful to have an understanding of named criteria. For information on named criteria, see Filtering Result Sets with Named Criteria.

You will need to complete this task:

To create a named bind variable

  1. In the Applications window, double-click the data control structure file.
  2. In the overview editor, click the Named Criteria navigation tab.
  3. On the Named Criteria page, expand the Bind Variables section and click the Create new bind variable button.
  4. In the New Variable dialog, enter the name and data type for the new bind variable.

    Because the bind variables share the same namespace as data control structure file attributes, specify names that don't conflict with existing attribute names.

  5. Optionally, specify a default value for the bind variable:
    • When you want the value to be determined at runtime using an expression, enter a Groovy scripting language expression, select the Expression value type and enter the expression in the Default Value field.

    • When you want to define a default value, select the Literal value type and enter the literal value in the Default Value field.

  6. Optionally, click the UI Hints tab and specify hints like Label Text, Format Type, Format mask, and others.

    The view layer will use bind variable control hints when you build user interfaces like search pages that allow the user to enter values for the named bind variables. The Updatable option controls whether the end user will be allowed to change the bind variable value through the user interface. If a bind variable is not updatable, then its value can only be changed programmatically by the developer.

  7. Click OK.

What Happens When You Use Bind Variables in Named Criteria

Once you've added one or more named bind variables to a data control structure file, you gain the ability to easily see and set the values of these variables at runtime. Information about the name, type, and default value of each bind variable is saved in the data object's data control structure file. If you have defined UI hints for the bind variables, this information is saved in the data model project's message bundle file along with other UI hints for the data control structure file.

What You May Need to Know About Nested Expressions

Search forms that the UI designer will create from named criteria are not able to work with all types of nested expressions. Specifically, search forms do not support expressions with directly nested named criteria. This type of nested expression defines one named criteria as a direct child of another named criteria. Query search forms do support nested expressions where you nest the named criteria as a child of a criteria item which is itself a child of a named criteria. For information on using named criteria to create search forms, see Creating ADF Databound Search Forms in Developing Fusion Web Applications with Oracle Application Development Framework.

How to Set User Interface Hints on Named Criteria

Named criteria that you create for data control structure file collections can be used by the web page designer to create Query-by-Example search forms. Web page designers select your named criteria from the Data Controls panel to create search forms for the web application. In the web page, the search form utilizes an ADF Faces query search component that will be bound initially to the named criteria selected in the Data Controls panel. At runtime, the end user may select among all other named criteria that appear in the Data Controls panel. Named criteria that the end user can select in a search form are known as developer-seeded searches. The query component automatically displays these seeded searches in its Saved Search dropdown list. For information on creating search forms and using the ADF query search component, see Creating ADF Databound Search Forms in Developing Fusion Web Applications with Oracle Application Development Framework.

Because developer-seeded searches are created in the data model project, the UI Hints page of the Edit View Criteria dialog lets you specify the default properties for the query component's runtime usage of individual named criteria. At runtime, the query component's behavior will conform to the selections you make for the following seeded search properties:

To create a seeded search for use by the ADF query search component, you select Show In List on the UI Hints page of the Edit View Criteria dialog. You deselect Show In List when you do not want the end user to see the named criteria in their search form.

Before you begin:

It may be helpful to have an understanding of named criteria. For information on named criteria, see Filtering Result Sets with Named Criteria.

You will need to complete this task:

To configure a named criteria for the user interface:

  1. In the Applications window, double-click the data control structure file that defines the named criteria you want to use as a seeded search.
  2. In the overview editor, click the Named Criteria navigation tab.
  3. On the Named Criteria page, select the named criteria that you want to allow in seeded searches and click the Edit icon.
  4. In the Edit View Criteria dialog, click the UI Hints tab and ensure that Show In List is selected.

    This selection determines whether or not the query component will display the seeded search in its Saved Search dropdown list.

  5. Enter a user-friendly display name for the seeded search to be added to the query component Saved Search dropdown list.

    When left empty, the named criteria name displayed in the Edit View Criteria dialog will be used by the query component.

  6. Optionally, enable Query Automatically when you want the query component to automatically display the search results whenever the end user selects the seeded search from the Saved Search dropdown list.

    By default, no search results will be displayed.

  7. Optionally, set the Rendered Mode property for each named criteria item in order to determine whether the item is displayed for the user in basic mode or advanced mode.

    Note:

    When your named criteria includes an item that should not be exposed to the user, use the Rendered Mode setting Never to prevent it from appearing in the search form. For example, a named criteria may be created to search for products in the logged-in customer's cart; however, you may want to prevent the user from changing the customer ID to display another customer's cart contents. In this scenario, the named criteria item corresponding to the customer ID would be set to the current customer ID using a named bind variable. Although the bind variable definition might specify the variable as not required and not updatable, with the UI hint property Display set to Hide, only the Rendered Mode setting determines whether or not the search form displays the value.

  8. Optionally, use the Show Operators dropdown list to configure whether the query component renders individual criteria items when the end user toggles the search from between basic and advanced mode.

    By default, all named criteria items defined by the seeded search will be displayed in either mode.

  9. If a rendered criteria item is of type Date, you must also define UI hints for the corresponding data object attribute. Set the data object attribute's Format Type hint to Simple Date and set the Format Mask to an appropriate value. This will allow the search form to accept date values. For information on setting UI hints on attributes, see How to Set UI Hints on Attributes.
  10. Click OK.

How to Create a Named Criteria Based on Multiple JPA Entities

When you create a named criteria for an entity class on a JPA-based data control, only attributes related to that particular entity are available for filtering. However, it is also possible to create a named criteria based on a custom bean and a JPA query that aggregates data from multiple tables that are related by foreign keys.

Before you begin:

It may be helpful to have an understanding of named criteria. For information on named criteria, see Filtering Result Sets with Named Criteria.

To create a named criteria based on multiple JPA entities:

  1. Create JPA entity classes for the tables that you want to filter and create an EJB session bean over those entities. For information on working with the EJB business services layer, see How to Work with an EJB Business Services Layer in Developing Applications with Oracle JDeveloper.
  2. Create a custom bean and populate it with simple getters and setters for the various attributes (from multiple entities) that you want to filter. For example, the getter and setter corresponding to the name attribute might look like the following:
    public void setName(String name) {
        this.name = name;
    }
     
    public String getName() {
        return name;
    }
    
  3. Add an accessor method to the session facade that creates a list of the custom beans based on a JPA query to the database.

    The following example shows a method that you might add to a session bean in order to create a list where each object consists of the id and name columns from the Customer entity and the dateOrdered and dateShipped columns from the Ord entity.

    public List<CustomBean> getCustomBeanFindAll() {
         String queryString =
                "select c.id, c.name, o.date_ordered, o.date_shipped \n" +
                "from s_customer c, s_ord o where o.customer_id = c.id";
         Query genericSearchQuery = em.createNativeQuery(queryString, "CustomQuery");
         List resultList = genericSearchQuery.getResultList();
         Iterator resultListIterator = resultList.iterator();
         List<CustomBean> customList = new ArrayList();
         while (resultListIterator.hasNext()) {
             Object col[] = (Object[])resultListIterator.next();
             CustomBean custom = new CustomBean();
             custom.setCustomerId((BigDecimal)col[0]);
             custom.setName((String)col[1]);
             custom.setDateOrdered((Date)col[2]);
             custom.setDateShipped((Date)col[3]);
    	     customList.add(custom);
         }
         return customList;
    }
    
  4. Create an EJB data control on the session bean and be sure to select the Support Named Criteria checkbox in the wizard when creating the data control.
  5. Create a data control structure file for the custom.
  6. Create the named criteria on the custom bean.

Creating List of Values Objects

Business services that you expose in the ADF data model of an ADF application support defining list of value (LOV) objects on the data control. JDeveloper enables the LOV as UI components that you drag and drop from the Data Controls panel into web pages of the ADF application.

In database applications, some columns in a given database table might have a restricted set of possible values that are defined in another database table. For example, an Orders database table might contain a Country column that must be filled in only with values derived from a Countries database table. To make it easier to work with such data from other tables, JDeveloper enables you to create list of value objects (LOVs) to reference data from one object in another object. By establishing these list of values relationships in the data model, you can then easily create selection lists, combo boxes, and other list of value UI components by dragging the LOV attribute from the Data Controls panel on to a page.

For JPA-based data controls, you can also apply any named criteria that you have defined on the object that is the list source in order to limit which objects appear in the list at runtime. To create named criteria, see Filtering Result Sets with Named Criteria.

How to an Create LOV for an Attribute

You define LOV objects in data control structure files.

Before you begin:

It may be helpful to have an understanding of list of value components. For information on list of value components, see Creating List of Values Objects.

You will need to complete this task:

  • Create data control structure files for both the object that will contain the LOV definition and the object which will be the data source for the LOV, as described in How to Edit a Data Control.

To create an LOV for an attribute

  1. In the overview editor for the data control structure file that will contain the LOV definition, click the List of Values navigation tab and click the Add list of values object.

  2. In the Create List of Values dialog, perform the following steps to apply the named criteria:

    1. In the List of Values Name field, type a name for the LOV object.

    2. In the Base Object Field tree, select the data control object that will be used to access the list of values. For example, you might choose a structured attribute node that has a OneToMany relationship with a collection.

    3. In the List Data Source tree, select the data control object for the source of the values.

      This accessor should not be otherwise used in the application. If this accessor is used elsewhere, create a new accessor method on the data control delegate that duplicates the functionality and use that as the list data source.

      Note:

      When using an LOV to select a JPA entity, the JPA entities returned by the list data source accessor will be compared, using equals(), to the property bound to the LOV. If the JPA entities in the list data source are guaranteed to be in a managed, and not detached, state by their EntityManager, the comparison will work correctly. If they might be in a detached state, then the default equals() method comparison may not work as expected and the entity class should override the equals() and hashCode() methods to at least include the entity's ID field.

      Similarly, you need to override the equals() method when the underlying session bean is stateless. Each method call in a stateless session bean employs its own persistence context, so the default equals() implementation will return false when comparing instances returned from separate method calls.

      You can generate code to override these two methods by selecting the entity class in the Applications window, right-clicking the entity's node in the Structure window, and choosing Generate equals() and hashCode(). However, this approach is not recommended because JPA also has dependencies on these methods. If you do override these methods, make sure that your implementation of equals() compares all non-transient properties in the entities to minimize any unexpected behavior. The recommended approach is to avoid the use of detached entities in your ADF web application, by using a stateful session bean with an extended persistence context. Using this model type, you can avoid multiple instances of the same logical entity, and the equals() method does not need to be overridden to compare entities based on their immutable identity.

    4. Click OK.

  3. Optionally, for JPA-based data controls, click the Edit View Attributes icon and apply any named criteria from the data source that you would like to use to limit the displayed values. This icon is located on the right side of the page between the List Data Source and List Return Values panels.

  4. In the overview editor, click List UI Hints tab and perform the following steps:

    1. In the Default List Type dropdown list, select the component to display the list of values.

    2. Optionally, in the Display Attributes section, change the attributes to be displayed in the list.

    3. Optionally, configure any of the other options that are available for the type of list you are using.

  5. Optionally, click the Accessor UI Hints tab to set UI hints for things such as the attributes displayed in the list and whether a user's selection is automatically submitted.

For information on List Type dropdown list, See the List Component Types for List Type UI Hint table in Developing Fusion Web Applications with Oracle Application Development Framework for a description of the types of components available.

What Happens When You Create an LOV

When you create an LOV object, the following things happen:

  • If not already present, an attribute node for the LOV object appears as a subnode of its base object in the Data Controls panel. You can use this node to create a model-driven list UI component by dragging it to the page. You can also drag the attribute's parent collection to the page and create a form or table in which that attribute is represented by a list component.

    Note:

    This attribute node might already appear in the Data Controls panel before the creation of the LOV object if a mapping to the list source is not already included for the attribute in the object definition.

    If the object definition includes mapping to the list source (such as in the form of a @JoinColumn annotation in a JPA entity class), by default the Data Controls panel represents the attribute as a structured attribute. However, by default, UI components for this structured attribute are not generated when you drag the parent collection to a page to create an ADF Form or an ADF Table. Therefore, creating the LOV object for an attribute that is mapped to another table simplifies the subsequent creation of forms and tables that you want to include model-driven selection lists.

  • The following elements are added to the data control structure file for the collection that contains the LOV attribute:

    • A <PDefAttribute> element, which specifies the attribute, points to the list binding element that defines the LOV behavior, and specifies the component type to display in the web page.

    • A <ViewAccessor> element, which is the mechanism that is used to obtain the list of possible values from the row set of the data source.

    • A <ListBinding> element which defines the behavior of the LOV, such as query limit and whether to display the list will include a blank entry.

Testing Data Object Metadata Using the Oracle ADF Model Tester

JDeveloper provides the Oracle ADF Model Tester to support exercising the data model that you expose for the business services of the ADF application. The tester lets developers verify data model functionality before they using the Data Controls panel to drag and drop databound UI components to design the web pages of the view layer.

Before you start designing the views for your application, you can use the Oracle ADF Model Tester to test various aspects of your model for EJB and bean data controls. For example, if you have added validation rules or UI hints to your model, you can test them before binding those objects to a page. Even after you have your UI pages constructed, the Oracle ADF Model Tester can assist you in diagnosing problems when they arise. You can use the Oracle ADF Model Tester to narrow down whether a problem lies in the business service layer or not.

How to Run the Oracle ADF Model Tester

To test the metadata that you have defined in your data control, use the Oracle ADF Model Tester, which is accessible from the Applications window.

Before you begin:

It may be helpful to have an understanding of the Oracle ADF Model Tester. For information on Oracle ADF Model Tester, see Testing Data Object Metadata Using the Oracle ADF Model Tester.

You need to complete this task:

Note:

For EJB data controls, the tester does not work for the local session bean interface. However, you can work around that limitation by creating a Java service facade class that is based on the same persistence unit as the session bean, creating a data control for that class, and using that data control in the tester. Since this Java service facade will use the same persistence unit as the EJB session bean, the two data controls will use the same data control structure files for the entities.

For information on creating a Java service facade class, see How to Create a Service Facade for a JPA-Based Bean Data Control.

Using this approach provides the additional benefit of reducing the overhead of the integrated WebLogic Server instance. The instance has to run a process for the tester, but it does not have to run the session bean itself.

To test the bean metadata in your application:

  1. In the Applications window, double-click the DataControls.dcx file.
  2. In the overview editor, right-click the node for the data control that you want to test and choose Run.

    The Oracle ADF Model Tester opens, as shown in Figure 7-6

    Figure 7-6 Oracle ADF Model Tester

    This image is described in the surrounding text
  3. Double-click a collection object to start testing the metadata for that object.

What Happens When You Use the Oracle ADF Model Tester

When you launch the Oracle ADF Model Tester, JDeveloper starts the tester in a separate process and the Oracle ADF Model Tester window appears. The tree at the left of the window displays all of the collections in your data model. If the data model defines master-detail view instance relationships, the tree displays them as parent and child nodes. After you double-click the desired collection, the Oracle ADF Model Tester displays a data view page to inspect the query results. For example, Figure 7-7 shows the customerFindAll collection that has been double-clicked to display the first record for this collection in the data view page on the right.

Figure 7-7 Oracle ADF Model Tester with the customerFindAll Collection Detail

This image is described in the surrounding text

The following are some of the features of the Oracle ADF Model Tester:

  • You can validate that the UI hints based on the Label Text hint and format masks are defined correctly. (For information on setting UI hints, see How to Set UI Hints on Attributes.)

  • You can also scroll through the data using the toolbar buttons.

  • You can enter Query-by-Example criteria to find a particular row whose data you want to inspect. By clicking the Specify View Criteria button in the toolbar, the View Criteria dialog displays the list of available Query-by-Example criteria.

    For example, you can select a named criteria like CustomerInfoCriteria and enter a query criteria like "H%" for a LastName attribute and click Find to narrow the search to only those users with a last name that begins with the letter H.

Table 7-2 gives an overview of the operations that the Oracle ADF Model Tester toolbar buttons perform.

Table 7-2 Oracle ADF Model Tester Toolbar Buttons

Button Operation Usage
Move to ... row icon

Move to ... row

Changes the current row displayed by the Oracle ADF Model Tester. Moves to the first, previous, next, or last row.

Insert a new row icon

Insert a new row

Creates and inserts a new row.

Delete the current row icon

Delete the current row

Deletes the current row.

Save changes to the database icon

Save changes to the database

Runs the commit operation on any pending transactions. However, for JPA-based data controls, the changes are not actually committed to the database.

This button is only available when transactional methods are implemented on the service.

Discard all changes since last save icon

Discard all changes since last save

Discards any pending transactions and restores the original values.

This button is only available when transactional methods are implemented on the service.

Specify view criteria icon

Specify view criteria

Displays the View Criteria dialog that you can use to create and apply named criteria to the result set.

Validate row icon

Validate row

Validates the current row by applying validation rules defined in the data control structure file. Disabled unless at least one field is editable.

How to Test Business Layer Validation

Depending on the validation rules you have defined, you can try entering invalid values to trigger and verify validation exceptions.

Before you begin:

It may be helpful to have an understanding of the Oracle ADF Model Tester. For information on Oracle ADF Model Tester, see Testing Data Object Metadata Using the Oracle ADF Model Tester.

You will need to complete this task:

To test business layer validation:

  • In the tester, enter a value for an attribute and click the Validate Row icon.

    For example, if you have defined a range validation rule for an attribute, enter a value outside that range, and click the Validate Row icon. You should see an error similar to following:

    (oracle.jbo.AttrSetValException) Valid product codes are between 100 and 999
    

How to Test Row Creation and Default Value Generation

You can use the Oracle ADF Model Tester to verify that any default values for attributes are properly generated when you create a new row.

Before you begin:

It may be helpful to have an understanding of the Oracle ADF Model Tester. For information on Oracle ADF Model Tester, see Testing Data Object Metadata Using the Oracle ADF Model Tester.

You may also find it helpful to understand attributes in data control structure files. For information on attributes, see Working with Attributes.

You will need to complete this task:

To test row creation and default value generation:

  1. In the Oracle ADF Model Tester toolbar, click the Insert a new row button to create the blank row.

    Any fields that have a declarative default value will appear with that value in the blank row.

  2. In the tester, enter all required fields and click the Commit button.

How to Test Named Criteria Using the Oracle ADF Model Tester

The Oracle ADF Model Tester enables you to test your data model using existing named criteria and by querying with ad hoc criteria.

Before you begin:

It may be helpful to have an understanding of the Oracle ADF Model Tester. For information on Oracle ADF Model Tester, see Testing Data Object Metadata Using the Oracle ADF Model Tester.

You may also find it helpful to understand named criteria. For information on named criteria, see Filtering Result Sets with Named Criteria.

You will need to complete this task:

To test named criteria and ad hoc query criteria using the Oracle ADF Model Tester:

  1. In the Oracle ADF Model Tester, double-click the collection that you want to filter.
  2. Click the Specify View Criteria toolbar button to test the named criteria.
  3. In the View Criteria dialog, perform one of the following tasks:
    • To test a named criteria that you added to a data control structure file in your project, shuttle that criteria to the Selected list and click Find. Any additional criteria that you enter in the Ad hoc criteria section will be added to the filter.

    • To test ad hoc criteria attributes from a single named criteria row, enter the desired values for the named criteria and click Find.

      For example, Figure 7-8 shows the filter to return all customers who possess a credit rating of POOR.

Figure 7-8 Oracle ADF Model Tester View Criteria Dialog

This image is described in the surrounding text

How to Update the Oracle ADF Model Tester to Display Project Changes

When you are testing your data control, you can iteratively modify the data control and retest it without redeploying your whole data model project. You can merely close and reopen the Oracle ADF Model Tester in order to reload changes that you have made to the data control structure files.

If you change Java code or any other files that are packaged in the data model project JAR file, you also need to rebuild and redeploy that JAR file to the internal application server.

Before you begin:

It may be helpful to have an understanding of the Oracle ADF Model Tester. For information on Oracle ADF Model Tester, see Testing Data Object Metadata Using the Oracle ADF Model Tester.

You will need to complete this task:

To reload the data model metadata in the running Oracle ADF Model Tester:

  1. In the Oracle ADF Model Tester, test the data model and determine any changes you want to make.
  2. In JDeveloper, make the desired changes to your project.
  3. If you have made any changes to Java classes or any other artifacts that are part of the session bean's JAR file, rebuild the project. (For example, you can right-click the data model project in the Applications window and choose Rebuild ProjectFileName The rebuilt JAR file is then deployed to the server.)

    If you have only made changes to data control structure files, you do not need to rebuild the project.

  4. Close the Oracle ADF Model Tester.
  5. Start the tester again.

How to Test Alternate Language Message Bundles and UI Hints

When your application defines alternative languages in your resource message bundles, you can configure the Oracle ADF Model Tester to recognize these languages. In the Oracle ADF Model Tester, you can then display the Locale menu and select among the available language choices.

Testing the language message bundles in the Oracle ADF Model Tester lets you verify that the translations of the data control UI hints are correctly located. Or, if the message bundle defines date formats for specific attributes, the tool lets you verify that date formats change (like 04/12/2007 to 12/04/2007).

Before you begin:

It may be helpful to have an understanding of the Oracle ADF Model Tester. For information on Oracle ADF Model Tester, see Testing Data Object Metadata Using the Oracle ADF Model Tester.

To specify a default language for the Oracle ADF Model Tester:

  1. From the Tools menu, choose Preferences.
  2. Expand ADF Business Components in the selection panel, and select Tester.
  3. In the Oracle ADF Model Tester page, add any locale for which you have created a resource message bundle to the Selected list.
  4. Start the tester.
  5. In the tester's Locale menu, select a locale.
For information on running the tester, see How to Run the Oracle ADF Model Tester.

Groovy Language Support

Business services that you expose in the ADF data model of an ADF application support defining Groovy scripting language expressions on data control objects. JDeveloper applies this script functionality to UI components that you drag and drop from the Data Controls panel into web pages of the ADF application.

Groovy is a scripting language with Java-like syntax for the Java platform. The Groovy scripting language simplifies the authoring of code by employing dot-separated notation, yet still supporting syntax to manipulate collections, Strings, and JavaBeans. Groovy language expressions are dynamically compiled and are executed at runtime. Any Groovy expressions that you create for an ADF application are stored in the data control structure files of the data objects for which they are defined.

Oracle ADF supports the use of the Groovy scripting language in places where access to data control objects is useful, including attribute validators, attribute default values, transient attribute value calculations, bind variable default values (in named criteria filters), and placeholders for error messages (in validation rules). Additionally, Oracle ADF provides a limited set of built-in keywords that can be used in Groovy expressions.

Specifically, Oracle ADF provides support for the use of Groovy language expressions to perform the following tasks:

To perform these tasks in JDeveloper, you use expression editor dialogs that are specific to the task. For example, when you want to create a default value for a transient attribute, you use the attribute's Edit Expression Editor dialog to enter an expression that determines a runtime value for the attribute. The same dialog also lets you specify when the value should be calculated (known as a recalculate condition). Although expressions cannot be verified at design time, all expression editors let you test the syntax of the expression before you save it.

For information on the Groovy language, refer to the following website:

How to Reference ADF Objects in Groovy Expressions

There is one top-level object named adf that allows you access to objects that the framework makes available to the Groovy script. The accessible Oracle ADF objects consist of the following:

  • adf.context - to reference the ADFContext object.

  • adf.object.dataProvider - to reference the data object on which the expression is being applied. Other accessible member names come from the context in which the Groovy script is applied.

    • Data object attributes and methods: The context is the data object's data control structure file. Through this object you can reference any attributes defined in the data control structure file as well as any attributes and methods that are inherited from the data object.

    • Script validation rules: The context is the validator object (JboValidatorContext) merged with the data object on which the validator is applied. For details about keywords that you can use in this context, see How to Reference ADF Methods and Attributes in Groovy Expressions.

  • adf.error - in validation rules, to access the error handler that allows the validation expression to generate exceptions or warnings

You can reference the current date (time truncated) or current date and time using the following expressions:

  • adf.currentDate

  • adf.currentDateTime

You can use the following built-in aggregate functions on rows of data:

  • rowSetAttr.sum(GroovyExpr)

  • rowSetAttr.count(GroovyExpr)

  • rowSetAttr.avg(GroovyExpr)

  • rowSetAttr.min(GroovyExpr)

  • rowSetAttr.max(GroovyExpr)

These aggregate functions accept a string-value argument that is interpreted as a Groovy expression that is evaluated in the context of each row in the row set as the aggregate is being computed. The Groovy expression must return a numeric value (or number domain).

How to Reference ADF Methods and Attributes in Groovy Expressions

The simplest example of referencing data control members, including methods and attributes that the data object and the data object's data control structure file define, is to reference attributes that exist in the same data object as the attribute that you apply the expression.

For example, you could define a Groovy expression to calculate the value of a transient attribute AnnualSalary on a data object with an attribute Sal that specifies the employee's monthly salary:

Sal * 12

Or, with Groovy you can write a simple validation rule to compare the attributes of a single data control structure file using syntax like:

PromotionDate > HireDate

Using Java, this same comparison would look like:

((Date)getAttribute("PromotionDate")).compareTo((Date)getAttribute("HireDate")) > 0

Note that the current object is passed in to the script as the this object, so you can reference an attribute in the current object by simply using the attribute name. For example, in an attribute-level or entity-level Script Expression validator, to refer to an attribute named "HireDate", the script can simply reference HireDate.

Similar to referencing attributes, you can invoke methods as part of your expression. For example, to define an attribute default value:

adf.object.dataProvider.getDefaultSalaryForGrade()

A method reference requires the prefix adf.object.dataProvider, which allows you to reference the same object that defines the attribute on which the expression is applied.

Note that when you want to reference the method of a data object in a validation rule, you use source instead of object.

adf.source.dataProvider.getDefaultSalaryForGrade()

Use of the source prefix is necessary in validators because the object keyword implies the validation rule object instead of the data object where the method is defined.

To allow you to reference members of the validator object (JboValidatorContext), you can use these keywords in your validation rule expression:

  • newValue: in an attribute-level validator, to access the attribute value being set

  • oldValue: in an attribute-level validator, to access the current value of the attribute being set

For example, you might use the following expression to specify a dynamic validation rule check of the salary for a salesman.

if (Job == "SALESMAN")
{
  return newValue < adf.source.dataProvider.getMaxSalaryForGrade(Job)
}
else
return true