Specifying Default Values (FireDAC)

From Appmethod Topics
Jump to: navigation, search

Go Up to Editing Data (FireDAC)

Using the OnNewRecord Event Handler

In Object Pascal, the standard way to assign default values to the new record fields is to use the OnNewRecord event handler. This event handler fires after the auto-incremental and detail record linking fields get their values and the automatic default values are assigned. The event handler may override the above values or assign initial values using complex custom logic.

The event handler may be assigned to the dataset at any time.

Specifying the Default Expression Value

FireDAC allows you to assign an expression to the TField.DefaultExpression property. This expression will be evaluated one time as part of the Insert / Append method call and assigned as an initial value to the corresponding field. Later this value may be overridden by the application. When a field has TField.FieldKind = fkInternalCalc, then the DefaultExpression will be used to calculate the field value.

If a value is assigned to a DefaultExpression field when a dataset is closed, then it will be actualized automatically. When a dataset is opened, call the UpdateAttributes method to actualize the changes. For example:

FDQuery1.Open;
...
FDQuery1.FieldByName('ObjGUID').DefaultExpression := 'NEWGUID()';
FDQuery1.UpdateAttributes;

FireDAC does not automatically fetch column default expressions from the database dictionary. The most simple way to assign an expression is to use the Fields Editor at design time:

FieldsEditorAssignExpr.png

Refreshing the Default Value

FireDAC automatically recognizes that a result set column has a default value for the following DBMS:

DBMS Description
Firebird fiMeta is in FetchOptions.Items and ExtendedMetadata = True
InterBase fiMeta is in FetchOptions.Items and ExtendedMetadata = True
MySQL
PostgreSQL fiMeta is in FetchOptions.Items and ExtendedMetadata = True


When FireDAC recognizes a column with a default value, TField.AutoGenerateValue is set to arDefault. If that does not happen, then AutoGenerateValue may be set manually. If a corresponding field value was not assigned when a new record is added, then FireDAC automatically refreshes the field value after posting a new record.