I need this code to operate to perform bidirectional update, following some rules:
if the TQryRecInfo descendant property is mapped to a TEdit, then this property maps to the TEdit.Text
if the TQryRecInfo descendant property is mapped to a TLabel, then this property maps to the TLabel.Caption
if the TQryRecInfo descendant property is mapped to a TDatePicker, then this property maps to the TDatePicker.Date
and so on...
When the TQryRecInfo descendant property is not a string, but it should map to a string TComponent property, then use GetFormattedText to convert to its string representation
Then create some methods to perform the bidirectional binding between the TComponent property changes and its corresponding TQryRecInfo descendant property.
procedure TMainForm.Button1Click(Sender: TObject);
begin
var MyComp:= RetrieveComponent(FQueryRec2, 'password');
if Assigned(MyComp) then
showmessage(MyComp.Name)
else showmessage('Componente não encontrado');
end;
procedure TMainForm.Button2Click(Sender: TObject);
begin
UnRegisterORMComponent(EditPassword);
// Automatically register components where the Hint matches a field in FQueryRec1
RegisterComponentsByHint(FQueryRec2);
begin
var MyComp:= RetrieveComponent(FQueryRec2, 'employeeNAme');
if Assigned(MyComp) then
showmessage(MyComp.Name)
else showmessage('Componente employeeName não encontrado');
end;
begin;
var MyComp:= RetrieveComponent(FQueryRec2, 'employeeId');
if Assigned(MyComp) then
showmessage(MyComp.Name)
else showmessage('Componente EmployeeID não encontrado');
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
// Initialize the ORM record instances
FQueryRec1 := TEmployeeProject.Create;
FQueryRec2 := TEmployeeProject.Create;
// Setup components with ORM properties and register them
SetupComponents;
end;
procedure TMainForm.SetupComponents;
begin
// Register EditUserName with ORMRec and FieldName
RegisterORMComponent(EditUserName, FQueryRec1, 'UserName');
// Register EditPassword with ORMRec and FieldName
RegisterORMComponent(EditPassword, FQueryRec2, 'Password');
// Register LabelUserName with ORMRec and FieldName
RegisterORMComponent(LabelUserName, FQueryRec1, 'UserLabel');
end;
function TMainForm.RetrieveComponent(ORMRec: TQryRecInfo; FieldName: string): TComponent;
begin
// Find and return the component based on ORMRec and FieldName
Result := FindComponentByORMRec(ORMRec, FieldName);
end;
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
///
/// Attribute to specify the database table associated with a class or field.
///
TableAttribute = class(TCustomAttribute)
private
FTableName: string;
public
constructor Create(const ATableName: string);
property TableName: string read FTableName;
end;
///
/// Attribute to mark a field as a primary key.
///
PrimaryKeyAttribute = class(TCustomAttribute)
public
constructor Create;
end;
///
/// Attribute to specify the database column associated with a field.
///
RefColumnAttribute = class(TCustomAttribute)
private
FColumnName: string;
public
constructor Create(const AColumnName: string);
property ColumnName: string read FColumnName;
end;
///
/// Attribute to specify the formatting of a field.
///
FmtPropAttribute = class(TCustomAttribute)
private
FFormatType: TFormatType;
public
constructor Create(AFormatType: TFormatType);
property FormatType: TFormatType read FFormatType;
end;
///
/// Attribute to specify the column index of a property in a TStringGrid.
///
GridColumnAttribute = class(TCustomAttribute)
private
FColumnIndex: Integer;
public
constructor Create(AColumnIndex: Integer);
property ColumnIndex: Integer read FColumnIndex;
end;
///
/// Attribute to specify the TComponent a property is mapped to.
///
ComponentMappingAttribute = class(TCustomAttribute)
private
FComponentName: string;
public
constructor Create(const AComponentName: string);
property ComponentName: string read FComponentName;
end;
TNullable<T{: record}> = record
public
Value: T;
HasValue: Boolean;
class operator Implicit(const AValue: T): TNullable<T>;
class operator Implicit(const AValue: TNullable<T>): T;
class operator Implicit(const AValue: TNullValue): TNullable<T>;
class operator Explicit(const AValue: T): TNullable<T>;
// add these...
class operator Equal(const A: TNullable<T>; const B: TNullValue): Boolean;
class operator NotEqual(const A: TNullable<T>; const B: TNullValue): Boolean;
end;
var NullValue: TNullValue;
implementation
class operator TNullable.Implicit(const AValue: T): TNullable;
begin
Result.Value := AValue;
Result.HasValue := True;
end;
class operator TNullable.Implicit(const AValue: TNullable): T;
begin
if AValue.HasValue then
Result := AValue.Value
else
Result := Default(T); // or raise an exception
end;
class operator TNullable.Implicit(const AValue: TNullValue): TNullable;
begin
Result.Value := Default(T);
Result.HasValue := False;
end;
class operator TNullable.Explicit(const AValue: T): TNullable;
begin
Result.Value := AValue;
Result.HasValue := True;
end;
class operator TNullable.Equal(const A: TNullable; const B: TNullValue): Boolean;
begin
Result := not A.HasValue;
end;
class operator TNullable.NotEqual(const A: TNullable; const B: TNullValue): Boolean;
begin
Result := A.HasValue;
end;
///
/// Base class for query record information
/// Use descendants of this class to represent specific database records.
///
TQryRecInfo = class
private
FDirtyFields: TDictionary<string, Boolean>;
FPreviousValues: TDictionary<string, TValue>;
procedure SetInfo(Index: Integer; const Value: TValue);
public
constructor Create;
destructor Destroy; override;
// Methods to set nullable fields
procedure SetInfoNullableString(Index: Integer; const Value: TNullable<string>);
procedure SetInfoNullableInteger(Index: Integer; const Value: TNullable<Integer>);
procedure SetInfoNullableInt64(Index: Integer; const Value: TNullable<Int64>);
procedure SetInfoNullableExtended(Index: Integer; const Value: TNullable<Extended>);
procedure SetInfoNullableCurrency(Index: Integer; const Value: TNullable<Currency>);
procedure SetInfoNullableDateTime(Index: Integer; const Value: TNullable<TDateTime>);
procedure SetInfoNullableBoolean(Index: Integer; const Value: TNullable<Boolean>);
procedure SetInfoNullableVariant(Index: Integer; const Value: TNullable<Variant>);
// Methods to set non-nullable simple types
procedure SetInfoCurrency(Index: Integer; const Value: Currency);
procedure SetInfoString(Index: Integer; const Value: string);
procedure SetInfoInteger(Index: Integer; const Value: Integer);
procedure SetInfoInt64(Index: Integer; const Value: Int64);
procedure SetInfoExtended(Index: Integer; const Value: Extended);
procedure SetInfoDateTime(Index: Integer; const Value: TDateTime);
procedure SetInfoBoolean(Index: Integer; const Value: Boolean);
procedure SetInfoVariant(Index: Integer; const Value: Variant);
// Methods to handle dirty fields
function IsFieldDirty(const FieldName: string): Boolean;
procedure ClearDirtyFlags;
property DirtyFields: TDictionary<string, Boolean> read FDirtyFields;
// Methods to handle previous values
function GetPreviousValue(const FieldName: string): TValue;
procedure ClearPreviousValues;
property PreviousValues: TDictionary<string, TValue> read FPreviousValues;
/// <summary>
/// Retrieves the formatted text for a given field based on the FmtProp attribute.
/// </summary>
function GetFormattedText(const FieldName: string): string;
/// <summary>
/// Fetches data for this record from the database based on the provided SQL.
/// </summary>
procedure Fetch(DBConn: TUniConnection; const QryTxt: string);
end;
///
/// Generic class to handle arrays of TQryRecInfo descendants.
///
TQryRecArray<T: class, constructor> = class
private
FQryRecInfoList: TObjectList;
FFilterSQL: string;
FDBConn: TUniConnection;
function GetCount: Integer;
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// Fetches all records based on the provided SQL text and populates the array.
/// </summary>
/// <param name="QryTxt">The base SQL query text.</param>
procedure FetchAllInstance(DBConn: TUniConnection; const QryTxt: string);
/// <summary>
/// Clears any SQL filters applied.
/// </summary>
procedure ClearFilter;
/// <summary>
/// Accesses a record at the specified index.
/// </summary>
/// <param name="Index">The zero-based index of the record.</param>
/// <returns>The record at the specified index.</returns>
function Rec(Index: Integer): T;
/// <summary>
/// Number of records in the array.
/// </summary>
property RecCount: Integer read GetCount;
/// <summary>
/// Database connection used for fetching records.
/// </summary>
property DBConn: TUniConnection read FDBConn write FDBConn;
/// <summary>
/// Additional SQL filter to apply to the query.
/// </summary>
property SQLFilter: string read FFilterSQL write FFilterSQL;
/// <summary>
/// Provides support for for-in loops by returning an enumerator.
/// </summary>
function GetEnumerator: TEnumerator<T>;
/// <summary>
/// Factory method to create and fetch records in a single step.
/// </summary>
/// <param name="DBConn">Database connection.</param>
/// <param name="QryTxt">SQL query text.</param>
/// <returns>Populated instance of TQryRecArray<T>.</returns>
class function FetchAll(DBConn: TUniConnection; const QryTxt: string): TQryRecArray<T>; static;
end;
// Example descendant of TQryRecInfo (You can create your own)
TDynRec = class(TQryRecInfo)
// Define additional properties as needed
end;
implementation
uses
System.Variants,
StrUtils,
pixel_utils; // Ensure this unit is in your project and properly implemented
destructor TQryRecInfo.Destroy;
begin
FDirtyFields.Free;
FPreviousValues.Free;
inherited;
end;
procedure TQryRecInfo.ClearDirtyFlags;
begin
FDirtyFields.Clear;
end;
procedure TQryRecInfo.ClearPreviousValues;
begin
FPreviousValues.Clear;
end;
function TQryRecInfo.IsFieldDirty(const FieldName: string): Boolean;
begin
Result := FDirtyFields.ContainsKey(FieldName) and FDirtyFields[FieldName];
end;
function TQryRecInfo.GetPreviousValue(const FieldName: string): TValue;
begin
if not FPreviousValues.TryGetValue(FieldName, Result) then
raise EORMUtilsException.CreateFmt('No previous value found for field "%s".', [FieldName]);
end;
function FormataInfo(info: Variant; tipo: TFormatType): string;
begin
if VarIsNull(info) or VarIsEmpty(info) then
Exit('');
case tipo of
tiString:
Result := VarToStr(info);
tiInteger:
Result := IntToStr(Integer(info));
tiMoney:
Result := FormatFloat(FMT_MONEY, Currency(info));
tiFloat:
Result := FloatToStr(info);
tiDate:
if VarIsType(info, [varDate, varDouble]) then
begin
if VarToDateTime(info) < EncodeDate(1900, 1, 1) then
Result := ''
else
Result := FormatDateTime('dd/mm/yyyy', VarToDateTime(info));
end
else
raise EORMUtilsException.CreateFmt('FormataInfo: Cannot treat information [%s] as tiDate.', [VarToStr(info)]);
tiDateTime:
if VarIsType(info, [varDate, varDouble]) then
begin
if VarToDateTime(info) = 0 then
Result := ''
else
Result := FormatDateTime('dd/mm/yyyy hh:mm:ss', VarToDateTime(info));
end
else
raise EORMUtilsException.CreateFmt('FormataInfo: Cannot treat information [%s] as tiDateTime.', [VarToStr(info)]);
tiBoolean:
Result := IfThen(Boolean(info), 'S', 'N');
tiByteArray:
Result := ByteArrayToHex(info);
tiNone:
Result := '';
else
raise EORMUtilsException.CreateFmt('FormataInfo: Format type [%s] not recognized.', [GetEnumName(TypeInfo(TFormatType), Integer(tipo))]);
end;
end;
// Find the property by name
Prop := RttiType.GetProperty(FieldName);
if not Assigned(Prop) then
raise EORMUtilsException.CreateFmt('Property "%s" not found.', [FieldName]);
// Get the value of the property
Value := Prop.GetValue(Self);
FmtType := tiNone;
// Check for FmtProp attribute on the property
for Attr in Prop.GetAttributes do
begin
if Attr is FmtPropAttribute then
begin
FmtAttr := FmtPropAttribute(Attr);
FmtType := FmtAttr.FormatType;
Break;
end;
end;
// If not found on property, check on the corresponding field
if FmtType = tiNone then
begin
Field := RttiType.GetField('_' + FieldName);
if Assigned(Field) then
begin
for Attr in Field.GetAttributes do
begin
if Attr is FmtPropAttribute then
begin
FmtAttr := FmtPropAttribute(Attr);
FmtType := FmtAttr.FormatType;
Break;
end;
end;
end;
end;
// Determine default FmtType based on property type if not set by attribute
if FmtType = tiNone then
begin
UnderlyingType := Prop.PropertyType;
// Handle TNullable<T>
if UnderlyingType.TypeKind = tkRecord then
begin
ValueField := UnderlyingType.GetField('Value');
if Assigned(ValueField) then
UnderlyingType := ValueField.FieldType;
end;
case UnderlyingType.TypeKind of
tkInteger, tkInt64:
FmtType := tiInteger;
tkFloat:
if UnderlyingType.Handle = TypeInfo(TDateTime) then
FmtType := tiDateTime
else
FmtType := tiFloat;
tkString, tkLString, tkWString, tkUString:
FmtType := tiString;
tkEnumeration:
if UnderlyingType.Handle = TypeInfo(Boolean) then
FmtType := tiBoolean
else
FmtType := tiString;
tkVariant:
FmtType := tiString;
else
FmtType := tiNone;
end;
end;
// Extract actual value from TNullable<T> if necessary
if Value.Kind = tkRecord then
begin
// Assuming TNullable<T> has 'HasValue' and 'Value' fields
UnderlyingType := Prop.PropertyType;
HasValueField := UnderlyingType.GetField('HasValue');
ValueField := UnderlyingType.GetField('Value');
if Assigned(HasValueField) and Assigned(ValueField) then
begin
HasValue := HasValueField.GetValue(Value.GetReferenceToRawData).AsBoolean;
if HasValue then
begin
ActualValue := ValueField.GetValue(Value.GetReferenceToRawData);
// Format the actual value
Result := FormataInfo(ActualValue.AsVariant, FmtType);
end
else
Result := '';
end
else
begin
// Not TNullable<T>, handle value directly
if not Value.IsEmpty then
Result := FormataInfo(Value.AsVariant, FmtType)
else
Result := '';
end;
end
else
begin
// Not a record, handle value directly
if not Value.IsEmpty then
Result := FormataInfo(Value.AsVariant, FmtType)
else
Result := '';
end;
finally
// No need to free TRttiContext as it's a record
end;
end;
procedure TQryRecInfo.Fetch(DBConn: TUniConnection; const QryTxt: string);
var
qr: TUniQuery;
Ctx: TRttiContext;
ObjType: TRttiType;
Prop: TRttiProperty;
Field: TField;
ORMFieldName: string;
begin
if not Assigned(DBConn) or Trim(QryTxt).IsEmpty then
Exit;
if qr.RecordCount > 0 then
begin
Ctx := TRttiContext.Create;
try
ObjType := Ctx.GetType(Self.ClassType);
for Prop in ObjType.GetProperties do
begin
if not Prop.IsWritable then
Continue;
// Attempt to find the corresponding field in the query
Field := qr.FindField(Prop.Name);
if not Assigned(Field) then
Continue; // Field not found, skip
ORMFieldName := '_' + Prop.Name;
// Handle TNullable<T> types
if Prop.PropertyType.TypeKind = tkRecord then
begin
// Expecting TNullable<T>
// Attempt to find the backing field for the nullable property
if ObjType.GetField(ORMFieldName) = nil then
Continue; // Backing field not found, skip
if Prop.PropertyType.Name.StartsWith('TNullable<') then
begin
// Use RTTI to determine the generic type parameter
if Field.IsNull then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<string>>(NullValue))
else
begin
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<string>>(Field.AsString))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Integer>>(Field.AsInteger))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Int64>>(Field.AsLargeInt))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Extended>>(Field.AsFloat))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Currency>>(Field.AsCurrency))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<TDateTime>>(Field.AsDateTime))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Boolean>>(Field.AsBoolean))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.From<TNullable<Variant>>(Field.Value))
else
raise EORMUtilsException.CreateFmt('Unsupported TNullable type: %s', [Prop.PropertyType.Name]);
end;
end
else
raise EORMUtilsException.CreateFmt('Unsupported record type: %s', [Prop.PropertyType.Name]);
end
else
begin
// Handle non-nullable types
case Prop.PropertyType.TypeKind of
tkString, tkLString, tkWString, tkUString:
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsString);
tkInteger:
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsInteger);
tkInt64:
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsLargeInt);
tkFloat:
if Prop.PropertyType.Handle = TypeInfo(Currency) then
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsCurrency)
else
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsFloat);
tkVariant:
ObjType.GetField(ORMFieldName).SetValue(Self, TValue.FromVariant(Field.AsVariant));
tkEnumeration:
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
ObjType.GetField(ORMFieldName).SetValue(Self, Field.AsBoolean)
else
raise EORMUtilsException.CreateFmt('Unsupported enumeration type: %s', [Prop.PropertyType.Name]);
else
// Add additional handling for other types if necessary
end;
end;
end;
finally
// No need to free TRttiContext as it's a record
end;
end;
finally
qr.Free;
end;
end;
procedure TQryRecInfo.SetInfo(Index: Integer; const Value: TValue);
var
PropName: string;
PropKind: TTypeKind;
Ctx: TRttiContext;
Prop: TRttiProperty;
Field: TRttiField;
OldValue: TValue;
begin
// Retrieve property name and kind based on index
// Assuming that the index corresponds to the property order
Ctx := TRttiContext.Create;
try
Prop := Ctx.GetType(Self.ClassType).GetProperties()[Index];
if not Assigned(Prop) then
raise EORMUtilsException.CreateFmt('Error: The index "%d" does not correspond to any property in class "%s".', [Index, ClassName]);
PropName := Prop.Name;
PropKind := Prop.PropertyType.TypeKind;
Field := Ctx.GetType(Self.ClassType).GetField('_' + PropName);
if not Assigned(Field) then
raise EORMUtilsException.CreateFmt('Error: Field "_%s" not found in class "%s".', [PropName, ClassName]);
// If the field is not yet dirty, store the previous value
if not FDirtyFields.ContainsKey(PropName) then
begin
OldValue := Field.GetValue(Self);
FPreviousValues.AddOrSetValue(PropName, OldValue);
end;
// Set the new value
Field.SetValue(Self, Value);
// Mark the property as dirty
FDirtyFields.AddOrSetValue(PropName, True);
finally
// No need to free TRttiContext as it's a record
end;
end;
procedure TQryRecInfo.SetInfoCurrency(Index: Integer; const Value: Currency);
begin
SetInfo(Index, TValue.From(Value));
end;
procedure TQryRecInfo.SetInfoString(Index: Integer; const Value: string);
begin
SetInfo(Index, TValue.From(Value));
end;
procedure TQryRecInfo.SetInfoInteger(Index: Integer; const Value: Integer);
begin
SetInfo(Index, TValue.From(Value));
end;
procedure TQryRecInfo.SetInfoInt64(Index: Integer; const Value: Int64);
begin
SetInfo(Index, TValue.From(Value));
end;
procedure TQryRecInfo.SetInfoExtended(Index: Integer; const Value: Extended);
begin
SetInfo(Index, TValue.From(Value));
end;
procedure TQryRecInfo.SetInfoDateTime(Index: Integer; const Value: TDateTime);
begin
SetInfo(Index, TValue.From(Value));
end;
procedure TQryRecInfo.SetInfoBoolean(Index: Integer; const Value: Boolean);
begin
SetInfo(Index, TValue.From(Value));
end;
procedure TQryRecInfo.SetInfoVariant(Index: Integer; const Value: Variant);
begin
SetInfo(Index, TValue.From(Value));
end;
procedure TQryRecInfo.SetInfoNullableBoolean(Index: Integer; const Value: TNullable);
begin
SetInfo(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.SetInfoNullableCurrency(Index: Integer; const Value: TNullable);
begin
SetInfo(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.SetInfoNullableDateTime(Index: Integer; const Value: TNullable);
begin
SetInfo(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.SetInfoNullableExtended(Index: Integer; const Value: TNullable);
begin
SetInfo(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.SetInfoNullableInteger(Index: Integer; const Value: TNullable);
begin
SetInfo(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.SetInfoNullableInt64(Index: Integer; const Value: TNullable);
begin
SetInfo(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.SetInfoNullableString(Index: Integer; const Value: TNullable);
begin
SetInfo(Index, TValue.From<TNullable>(Value));
end;
procedure TQryRecInfo.SetInfoNullableVariant(Index: Integer; const Value: TNullable);
begin
SetInfo(Index, TValue.From<TNullable>(Value));
end;
destructor TQryRecArray.Destroy;
begin
FQryRecInfoList.Free;
inherited;
end;
procedure TQryRecArray.ClearFilter;
begin
FFilterSQL := '';
end;
function TQryRecArray.GetCount: Integer;
begin
Result := FQryRecInfoList.Count;
end;
function TQryRecArray.Rec(Index: Integer): T;
begin
if (Index < 0) or (Index >= FQryRecInfoList.Count) then
raise EORMUtilsException.CreateFmt('Index %d out of bounds.', [Index]);
Result := FQryRecInfoList[Index];
end;
procedure TQryRecArray.FetchAllInstance(DBConn: TUniConnection; const QryTxt: string);
var
qr: TUniQuery;
RecInstance: T;
Ctx: TRttiContext;
ObjType: TRttiType;
Prop: TRttiProperty;
Field: TField;
ORMFieldName: string;
begin
if not Assigned(DBConn) then
raise EORMUtilsException.Create('Database connection (DBConn) is not assigned.');
if Trim(QryTxt).IsEmpty then
raise EORMUtilsException.Create('Query text (QryTxt) cannot be empty.');
if qr.IsEmpty then
Exit; // No records to fetch
Ctx := TRttiContext.Create;
ObjType := Ctx.GetType(T);
try
while not qr.Eof do
begin
RecInstance := T.Create;
try
// Iterate over each property of T and assign values from the query
for Prop in ObjType.GetProperties do
begin
if not Prop.IsWritable then
Continue;
// Attempt to find the corresponding field in the query
Field := qr.FindField(Prop.Name);
if not Assigned(Field) then
Continue; // Field not found, skip
ORMFieldName := '_' + Prop.Name;
// Handle TNullable<T> types
if Prop.PropertyType.TypeKind = tkRecord then
begin
// Expecting TNullable<T>
// Attempt to find the backing field for the nullable property
if ObjType.GetField(ORMFieldName) = nil then
Continue; // Backing field not found, skip
if Prop.PropertyType.Name.StartsWith('TNullable<') then
begin
// Use RTTI to determine the generic type parameter
if Field.IsNull then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<Variant>>(NullValue))
else
begin
// Determine the generic type and set the value accordingly
if Prop.PropertyType.Name = 'TNullable<System.string>' then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<string>>(Field.AsString))
else if Prop.PropertyType.Name = 'TNullable<System.Integer>' then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<Integer>>(Field.AsInteger))
else if Prop.PropertyType.Name = 'TNullable<System.Int64>' then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<Int64>>(Field.AsLargeInt))
else if Prop.PropertyType.Name = 'TNullable<System.Extended>' then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<Extended>>(Field.AsFloat))
else if Prop.PropertyType.Name = 'TNullable<System.Currency>' then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<Currency>>(Field.AsCurrency))
else if Prop.PropertyType.Name = 'TNullable<System.TDateTime>' then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<TDateTime>>(Field.AsDateTime))
else if Prop.PropertyType.Name = 'TNullable<System.Boolean>' then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<Boolean>>(Field.AsBoolean))
else if Prop.PropertyType.Name = 'TNullable<System.Variant>' then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.From<TNullable<Variant>>(Field.Value))
else
raise EORMUtilsException.CreateFmt('Unsupported TNullable type: %s', [Prop.PropertyType.Name]);
end;
end
else
raise EORMUtilsException.CreateFmt('Unsupported record type: %s', [Prop.PropertyType.Name]);
end
else
begin
// Handle non-nullable types
case Prop.PropertyType.TypeKind of
tkString, tkLString, tkWString, tkUString:
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), Field.AsString);
tkInteger:
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), Field.AsInteger);
tkInt64:
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), Field.AsLargeInt);
tkFloat:
if Prop.PropertyType.Handle = TypeInfo(Currency) then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), Field.AsCurrency)
else if Prop.PropertyType.Handle = TypeInfo(TDateTime) then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), Field.AsDateTime)
else
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), Field.AsFloat);
tkVariant:
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), TValue.FromVariant(Field.AsVariant));
tkEnumeration:
if Prop.PropertyType.Handle = TypeInfo(Boolean) then
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), Field.AsBoolean)
else
ObjType.GetField(ORMFieldName).SetValue(Pointer(RecInstance), Field.AsString);
else
// Unsupported type; you can extend this as needed
Continue;
end;
end;
end;
// Add the populated record to the list
FQryRecInfoList.Add(RecInstance);
except
RecInstance.Free;
raise; // Re-raise the exception after cleanup
end;
qr.Next;
end;
finally
// No need to free TRttiContext as it's a record
end;
finally
qr.Free;
end;
end;
function TQryRecArray.GetEnumerator: TEnumerator;
begin
Result := FQryRecInfoList.GetEnumerator;
end;
class function TQryRecArray.FetchAll(DBConn: TUniConnection; const QryTxt: string): TQryRecArray;
var
Instance: TQryRecArray;
begin
Instance := TQryRecArray.Create;
try
Instance.FetchAllInstance(DBConn, QryTxt);
Result := Instance;
except
Instance.Free;
raise;
end;
end;
type
TORMKey = record
ORMRec: TQryRecInfo;
FieldName: string;
end;
TComponentHelper = class helper for TComponent
private
function GetORMRec: TQryRecInfo;
function GetORMRecField: string;
public
property ORMRec: TQryRecInfo read GetORMRec;
property ORMRecField: string read GetORMRecField;
end;
// Helper function for RTTI component registration
procedure TForm.RegisterComponentsByHint(ORMRec: TQryRecInfo);
var
Context: TRttiContext;
RttiType: TRttiType;
RttiProperty: TRttiProperty;
Component: TComponent;
HintValue: TValue;
begin
Context := TRttiContext.Create;
try
for Component in Self do
begin
RttiType := Context.GetType(Component.ClassType);
RttiProperty := RttiType.GetProperty('Hint');
if Assigned(RttiProperty) then
begin
HintValue := RttiProperty.GetValue(Component);
if HintValue.IsEmpty then
Continue;
// Use property names of the ORMRec object
RttiType := Context.GetType(ORMRec.ClassType);
for RttiProperty in RttiType.GetProperties do
begin
if (RttiProperty.Visibility = mvPublished) then
begin
// Register component if its Hint matches a property name in ORMRec
if SameText(HintValue.AsString, RttiProperty.Name) then
begin
RegisterORMComponent(Component, ORMRec, RttiProperty.Name);
Break; // Once registered, no need to check other properties for the same component
end;
end;
end;
end;
end;
finally
Context.Free;
end;
end;
// Existing function definitions...
function TORMKeyHash(const Key: TORMKey): Integer;
begin
Result := Integer(NativeUInt(Key.ORMRec)) xor THashBobJenkins.GetHashValue(LowerCase(Key.FieldName));
end;
function TORMKeyEquals(const Key1, Key2: TORMKey): Boolean;
begin
Result := (Key1.ORMRec = Key2.ORMRec) and SameText(Key1.FieldName, Key2.FieldName);
end;
var
GORMRecDictionary: TDictionary<TComponent, TQryRecInfo>;
GORMRecFieldDictionary: TDictionary<TComponent, string>;
// Methods for TComponentHelper
function TComponentHelper.GetORMRec: TQryRecInfo;
begin
if not GORMRecDictionary.TryGetValue(Self, Result) then
Result := nil;
end;
function TComponentHelper.GetORMRecField: string;
begin
if not GORMRecFieldDictionary.TryGetValue(Self, Result) then
Result := '';
end;
// Methods for TForm
constructor TForm.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TForm.Destroy;
begin
inherited;
end;
procedure TForm.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
StrPCopy(Params.WinClassName, 'ZPro');
end;
procedure TForm.RegisterORMComponent(Component: TComponent; ORMRec: TQryRecInfo; const FieldName: string);
var
Key: TORMKey;
begin
Key.ORMRec := ORMRec;
Key.FieldName := FieldName;
if (Key.ORMRec <> nil) and (Key.FieldName <> '') then
begin
GORMRecDictionary.AddOrSetValue(Component, ORMRec);
GORMRecFieldDictionary.AddOrSetValue(Component, LowerCase(FieldName)); // Store lowercase for consistent hashing
GORMToComponentDict.AddOrSetValue(Key, Component);
end;
end;
procedure TForm.UnregisterORMComponent(Component: TComponent);
var
ORMRec: TQryRecInfo;
FieldName: string;
Key: TORMKey;
begin
if GORMRecDictionary.TryGetValue(Component, ORMRec) and GORMRecFieldDictionary.TryGetValue(Component, FieldName) then
begin
Key.ORMRec := ORMRec;
Key.FieldName := LowerCase(FieldName);
GORMToComponentDict.Remove(Key);
GORMRecDictionary.Remove(Component);
GORMRecFieldDictionary.Remove(Component);
end;
end;
function TForm.FindComponentByORMRec(ORMRec: TQryRecInfo; const FieldName: string): TComponent;
var
Key: TORMKey;
begin
Key.ORMRec := ORMRec;
Key.FieldName := LowerCase(FieldName); // Use lowercase for lookup
if not GORMToComponentDict.TryGetValue(Key, Result) then
Result := nil;
end;
// Other class methods remain unchanged...
procedure TsPanel.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
StrPCopy(Params.WinClassName, 'Painel');
end;
procedure TsEdit.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
StrPCopy(Params.WinClassName, 'Editor');
end;
procedure TsPageControl.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
StrPCopy(Params.WinClassName, 'PagCtrl');
end;
procedure TsPageControl.TCMAdjustRect(var Msg: TMessage);
begin
inherited;
case TabPosition of
tpTop:
begin
PRect(Msg.LParam)^.Left := 0;
PRect(Msg.LParam)^.Right := ClientWidth;
PRect(Msg.LParam)^.Bottom := ClientHeight;
end;
end;
end;
procedure TAdvColumnGrid.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
StrPCopy(Params.WinClassName, 'Grid');
end;
function TAdvColumnGrid.GetCellz(ACol, ARow: Integer): TZString;
begin
Result := Self.Cells[ACol, ARow];
end;
function TAdvColumnGrid.GetBypassAF(ACol: Integer): Boolean;
begin
Result := FByPassAF[ACol];
end;
procedure TAdvColumnGrid.SetBypassAF(ACol: Integer; const Value: Boolean);
begin
if Length(FByPassAF) < ACol + 1 then
SetLength(FByPassAF, ACol + 1);
FByPassAF[ACol] := Value;
end;
function TAdvColumnGrid.CriaLinha: Integer;
begin
Self.RowCount := Self.RowCount + 1;
Self.ClearRows(Self.RowCount - 1, 1);
Result := Self.RowCount - 1;
end;
function TAdvColumnGrid.CriaLinhaObjeto(MyObject: TObject): Integer;
begin
Self.RowCount := Self.RowCount + 1;
Self.ClearRows(Self.RowCount - 1, 1);
Self.Objects[0, Self.RowCount - 1] := MyObject;
Result := Self.RowCount - 1;
end;
function TAdvColumnGrid.GetColumnIndexByName(const nome: string): Integer;
begin
Result := 0;
for var i := 1 to Pred(Self.ColCount) do
if Self.Columns[i].Name = nome then
Exit(i);
end;
procedure TAdvColumnGrid.SetBasicColumnConfig;
var
i: Integer;
begin
with Self do
begin
SuppressColumn(0);
for i := 1 to ColCount - 1 do
if Columns[i].Tag = 0 then
begin
Columns[i].HeaderAlignment := taCenter;
Columns[i].HeaderFont.Name := 'Tahoma';
Columns[i].HeaderFont.Size := MulDiv(8, 96, Self.CurrentPPI);
Columns[i].HeaderFont.Color := clWhite;
Columns[i].HeaderFont.Style := [fsBold];
end;
for i := 1 to ColCount - 1 do
if Columns[i].Tag = 0 then
begin
Columns[i].Font.Name := 'Verdana';
Columns[i].Font.Size := MulDiv(10, 96, Self.CurrentPPI);
Columns[i].Font.Style := [];
end;
for i := 1 to ColCount - 1 do
if Columns[i].Tag = 0 then
begin
Columns[i].ShowBands := True;
Colors[i, 0] := RGB(41,3F, $42);
end;
To implement bidirectional binding between your ORM records (TQryRecInfo descendants) and UI components (TEdit, TLabel, TDatePicker, etc.), you'll need to establish a systematic way to:
Map ORM properties to component properties based on component types.
Synchronize changes from ORM to components and from components to ORM.
Handle type conversions where necessary, especially when mapping non-string ORM properties to string-based component properties using GetFormattedText.
Below, I'll guide you through the necessary modifications and additions to your existing codebase to achieve this functionality.
Overview of the Approach
Extend TQryRecInfo to include an event mechanism that notifies when a property changes.
Modify RegisterORMComponent to:
Assign event handlers to components based on their types.
Assign ORM's OnPropertyChanged event to update component properties when ORM data changes.
Implement Synchronization Methods to handle updates from ORM to components and vice versa.
Utilize RTTI (Run-Time Type Information) to generically handle different component types and property mappings.
Handle Type Conversions using GetFormattedText when necessary.
Step-by-Step Implementation
1. Extend TQryRecInfo with Event Mechanism
To notify UI components when an ORM property changes, we'll add an event to TQryRecInfo. This event will be triggered whenever a property is updated.
Modify orm_utils Unit:
unit orm_utils;
interface
uses
System.SysUtils,
System.Classes,
System.Generics.Collections,
System.Rtti,
System.TypInfo,
Data.DB,
Uni,
pixel_classes,
orm_customattributes;
type
EORMUtilsException = class(Exception);
// Define the event type
TPropertyChangedEvent = procedure(Sender: TObject; const FieldName: string) of object;
/// <summary>
/// Base class for query record information
/// Use descendants of this class to represent specific database records.
/// </summary>
TQryRecInfo = class
private
FDirtyFields: TDictionary<string, Boolean>;
FPreviousValues: TDictionary<string, TValue>;
procedure SetInfo(Index: Integer; const Value: TValue);
public
// Event to notify when a property changes
OnPropertyChanged: TPropertyChangedEvent;
constructor Create;
destructor Destroy; override;
// ... [Existing methods]
/// <summary>
/// Retrieves the formatted text for a given field based on the FmtProp attribute.
/// </summary>
function GetFormattedText(const FieldName: string): string;
// ... [Existing methods]
end;
// ... [Rest of the unit remains unchanged]
implementation
uses
System.Variants,
StrUtils,
pixel_utils; // Ensure this unit is in your project and properly implemented
{ TQryRecInfo }
// ... [Existing constructor, destructor, and methods]
procedure TQryRecInfo.SetInfo(Index: Integer; const Value: TValue);
var
PropName: string;
PropKind: TTypeKind;
Ctx: TRttiContext;
Prop: TRttiProperty;
Field: TRttiField;
OldValue: TValue;
begin
// [Existing code to set the property]
// After setting the value, trigger the OnPropertyChanged event
if Assigned(OnPropertyChanged) then
OnPropertyChanged(Self, PropName);
end;
// ... [Rest of the unit remains unchanged]
end.
Explanation:
Event Declaration: Added OnPropertyChanged of type TPropertyChangedEvent to notify listeners when a property changes.
Triggering Event: In the SetInfo method (and implicitly in all SetInfo... methods), after updating a property, the OnPropertyChanged event is triggered with the FieldName.
2. Modify interposer_class to Handle Binding
We'll update the interposer_class unit to handle the binding between ORM properties and UI component properties. This involves:
Assigning event handlers to components based on their types.
Responding to ORM property changes to update component properties.
Responding to component property changes to update ORM properties.
Modify interposer_class Unit:
unit interposer_class;
interface
uses
Vcl.Forms, Vcl.Controls, CommCtrl, Messages, sPanel, sEdit, sPageControl,
System.Classes, AdvCGrid, Uni, pixel_classes, ORM_utils, SysUtils, Dialogs,
Generics.Collections, System.Hash, System.Rtti, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls;
{$TYPEINFO ON}
type
TORMKey = record
ORMRec: TQryRecInfo;
FieldName: string;
end;
// Hash and equality functions for TORMKey
function TORMKeyHash(const Key: TORMKey): Integer;
function TORMKeyEquals(const Key1, Key2: TORMKey): Boolean;
TComponentHelper = class helper for TComponent
private
function GetORMRec: TQryRecInfo;
function GetORMRecField: string;
public
property ORMRec: TQryRecInfo read GetORMRec;
property ORMRecField: string read GetORMRecField;
end;
TForm = class(Vcl.Forms.TForm)
private
class var GORMToComponentDict: TDictionary<TORMKey, TComponent>;
// Helper dictionaries
class var GORMRecDictionary: TDictionary<TComponent, TQryRecInfo>;
class var GORMRecFieldDictionary: TDictionary<TComponent, string>;
// Event handler for ORM property changes
procedure ORMPropertyChanged(Sender: TObject; const FieldName: string);
// Event handler for component property changes
procedure ComponentPropertyChanged(Sender: TObject);
protected
procedure CreateParams(var Params: TCreateParams); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function FindComponentByORMRec(ORMRec: TQryRecInfo; const FieldName: string): TComponent;
procedure RegisterORMComponent(Component: TComponent; ORMRec: TQryRecInfo; const FieldName: string);
procedure UnregisterORMComponent(Component: TComponent);
procedure RegisterComponentsByHint(ORMRec: TQryRecInfo);
// Method to update component from ORM
procedure UpdateComponentFromORM(Component: TComponent; ORMRec: TQryRecInfo; const FieldName: string);
// Method to update ORM from component
procedure UpdateORMFromComponent(Component: TComponent; ORMRec: TQryRecInfo; const FieldName: string);
end;
// ... [TsPanel, TsEdit, TsPageControl, TAdvColumnGrid remain unchanged]
implementation
uses
pixel_utils, System.Math, System.Types, Windows, TypInfo, System.Generics.Defaults,
Data.DB, Vcl.Graphics, ComCtrls, Vcl.Grids;
// Helper functions for TORMKey
function TORMKeyHash(const Key: TORMKey): Integer;
begin
Result := Integer(NativeUInt(Key.ORMRec)) xor THashBobJenkins.GetHashValue(LowerCase(Key.FieldName));
end;
function TORMKeyEquals(const Key1, Key2: TORMKey): Boolean;
begin
Result := (Key1.ORMRec = Key2.ORMRec) and SameText(Key1.FieldName, Key2.FieldName);
end;
// Initialize helper dictionaries
initialization
TForm.GORMRecDictionary := TDictionary<TComponent, TQryRecInfo>.Create;
TForm.GORMRecFieldDictionary := TDictionary<TComponent, string>.Create;
// Initialize dictionary with custom equality and hash functions
TForm.GORMToComponentDict := TDictionary<TORMKey, TComponent>.Create(
TEqualityComparer<TORMKey>.Construct(TORMKeyEquals, TORMKeyHash)
);
finalization
TForm.GORMRecDictionary.Free;
TForm.GORMRecFieldDictionary.Free;
TForm.GORMToComponentDict.Free;
end.
Explanation:
Helper Functions: Implemented TORMKeyHash and TORMKeyEquals to uniquely identify components based on their ORM record and field name.
Class Variables: Defined GORMRecDictionary and GORMRecFieldDictionary to map components to their corresponding ORM records and field names.
Event Handlers: Declared ORMPropertyChanged and ComponentPropertyChanged methods to handle synchronization between ORM and components.
3. Implement Event Handlers for Synchronization
Continue Modifying interposer_class Unit:
type
// ... [Existing declarations]
implementation
// ... [Existing uses and helper functions]
{ TForm }
constructor TForm.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TForm.Destroy;
begin
inherited;
end;
procedure TForm.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
StrPCopy(Params.WinClassName, 'ZPro');
end;
// Event handler: ORM property changed, update component
procedure TForm.ORMPropertyChanged(Sender: TObject; const FieldName: string);
var
Key: TORMKey;
Component: TComponent;
begin
Key.ORMRec := TQryRecInfo(Sender);
Key.FieldName := LowerCase(FieldName);
if TForm.GORMToComponentDict.TryGetValue(Key, Component) then
begin
UpdateComponentFromORM(Component, Key.ORMRec, FieldName);
end;
end;
// Event handler: Component property changed, update ORM
procedure TForm.ComponentPropertyChanged(Sender: TObject);
var
Component: TComponent;
ORMRec: TQryRecInfo;
FieldName: string;
begin
Component := Sender as TComponent;
if TForm.GORMRecDictionary.TryGetValue(Component, ORMRec) and
TForm.GORMRecFieldDictionary.TryGetValue(Component, FieldName) then
begin
UpdateORMFromComponent(Component, ORMRec, FieldName);
end;
end;
// Register ORM Component and assign event handlers
procedure TForm.RegisterORMComponent(Component: TComponent; ORMRec: TQryRecInfo; const FieldName: string);
var
Key: TORMKey;
begin
Key.ORMRec := ORMRec;
Key.FieldName := LowerCase(FieldName);
if (Key.ORMRec <> nil) and (Key.FieldName <> '') then
begin
// Map component to ORMRec and FieldName
GORMRecDictionary.AddOrSetValue(Component, ORMRec);
GORMRecFieldDictionary.AddOrSetValue(Component, FieldName);
GORMToComponentDict.AddOrSetValue(Key, Component);
// Assign ORM's OnPropertyChanged to handle ORM to component updates
if not Assigned(ORMRec.OnPropertyChanged) then
ORMRec.OnPropertyChanged := ORMPropertyChanged;
// Assign component event handlers based on component type
if Component is TEdit then
begin
// Prevent recursive updates by using OnChanging flag if needed
(Component as TEdit).OnChange := ComponentPropertyChanged;
// Initialize component with ORM data
UpdateComponentFromORM(Component, ORMRec, FieldName);
end
else if Component is TLabel then
begin
// Labels typically don't change via user interaction; update from ORM only
UpdateComponentFromORM(Component, ORMRec, FieldName);
end
else if Component is TDatePicker then
begin
(Component as TDatePicker).OnChange := ComponentPropertyChanged;
// Initialize component with ORM data
UpdateComponentFromORM(Component, ORMRec, FieldName);
end
else
begin
// Handle other component types as needed
// Example for TComboBox:
if Component is TComboBox then
begin
(Component as TComboBox).OnChange := ComponentPropertyChanged;
UpdateComponentFromORM(Component, ORMRec, FieldName);
end;
// Add more component types and their event assignments here
end;
end;
end;
// Unregister ORM Component
procedure TForm.UnregisterORMComponent(Component: TComponent);
var
ORMRec: TQryRecInfo;
FieldName: string;
Key: TORMKey;
begin
if GORMRecDictionary.TryGetValue(Component, ORMRec) and
GORMRecFieldDictionary.TryGetValue(Component, FieldName) then
begin
Key.ORMRec := ORMRec;
Key.FieldName := LowerCase(FieldName);
GORMToComponentDict.Remove(Key);
GORMRecDictionary.Remove(Component);
GORMRecFieldDictionary.Remove(Component);
// Remove event handlers
if Component is TEdit then
(Component as TEdit).OnChange := nil
else if Component is TDatePicker then
(Component as TDatePicker).OnChange := nil
else if Component is TComboBox then
(Component as TComboBox).OnChange := nil;
// Remove other component types' event handlers as needed
// If no more components are registered with this ORMRec, remove the ORM's event handler
if not GORMToComponentDict.ContainsKey(TORMKey.Create(ORMRec, '')) then
ORMRec.OnPropertyChanged := nil;
end;
end;
// Find component by ORMRec and FieldName
function TForm.FindComponentByORMRec(ORMRec: TQryRecInfo; const FieldName: string): TComponent;
var
Key: TORMKey;
begin
Key.ORMRec := ORMRec;
Key.FieldName := LowerCase(FieldName); // Use lowercase for lookup
if not GORMToComponentDict.TryGetValue(Key, Result) then
Result := nil;
end;
// Update component property based on ORM value
procedure TForm.UpdateComponentFromORM(Component: TComponent; ORMRec: TQryRecInfo; const FieldName: string);
var
FormattedText: string;
Value: TValue;
Prop: TRttiProperty;
Ctx: TRttiContext;
begin
Ctx := TRttiContext.Create;
try
// Determine based on component type
if Component is TEdit then
begin
// Use GetFormattedText for non-string ORM properties
FormattedText := ORMRec.GetFormattedText(FieldName);
(Component as TEdit).Text := FormattedText;
end
else if Component is TLabel then
begin
FormattedText := ORMRec.GetFormattedText(FieldName);
(Component as TLabel).Caption := FormattedText;
end
else if Component is TDatePicker then
begin
// Assuming ORM property is TNullable<TDateTime>
Value := ORMRec.GetPreviousValue(FieldName);
if Value.IsEmpty or not Value.IsType<TDateTime> then
(Component as TDatePicker).Date := Date; // Or some default
else
(Component as TDatePicker).Date := Value.AsType<TDateTime>;
end
else if Component is TComboBox then
begin
FormattedText := ORMRec.GetFormattedText(FieldName);
(Component as TComboBox).Text := FormattedText;
end
else
begin
// Handle other component types as needed
// Example: TCheckBox.Caption, etc.
// Use RTTI to set property if generic handling is required
// For brevity, it's handled explicitly above
end;
finally
Ctx.Free;
end;
end;
// Update ORM property based on component value
procedure TForm.UpdateORMFromComponent(Component: TComponent; ORMRec: TQryRecInfo; const FieldName: string);
var
NewValue: TValue;
FormattedText: string;
Ctx: TRttiContext;
Prop: TRttiProperty;
FmtType: TFormatType;
FormattedDate: TDateTime;
begin
Ctx := TRttiContext.Create;
try
// Determine based on component type
if Component is TEdit then
begin
// Assume ORM property is string or use obtained value
FormattedText := (Component as TEdit).Text;
// Update ORM property via RTTI
Prop := Ctx.GetType(ORMRec.ClassType).GetProperty(FieldName);
if Assigned(Prop) and Prop.IsWritable then
begin
// Determine property type
if Prop.PropertyType.TypeKind in [tkString, tkLString, tkWString, tkUString] then
ORMRec.SetInfoNullableString(Prop.GetIndex, TZString(FormattedText))
else
begin
// If ORM property is not string, you may need to parse the text
// Alternatively, handle via GetFormattedText and similar methods
// For simplicity, assuming it's nullable string
ORMRec.SetInfoNullableString(Prop.GetIndex, TNullable<string>(FormattedText));
end;
end;
end
else if Component is TLabel then
begin
// Typically, labels are read-only from user input; no action needed
// If needed, implement similar to TEdit
end
else if Component is TDatePicker then
begin
// Assume ORM property is TNullable<TDateTime>
FormattedDate := (Component as TDatePicker).Date;
Prop := Ctx.GetType(ORMRec.ClassType).GetProperty(FieldName);
if Assigned(Prop) and Prop.IsWritable then
begin
ORMRec.SetInfoNullableDateTime(Prop.GetIndex, TNullable<TDateTime>(FormattedDate));
end;
end
else if Component is TComboBox then
begin
FormattedText := (Component as TComboBox).Text;
Prop := Ctx.GetType(ORMRec.ClassType).GetProperty(FieldName);
if Assigned(Prop) and Prop.IsWritable then
begin
if Prop.PropertyType.TypeKind in [tkString, tkLString, tkWString, tkUString] then
ORMRec.SetInfoNullableString(Prop.GetIndex, TNullable<string>(FormattedText))
else
// Handle other types as needed
ORMRec.SetInfoNullableString(Prop.GetIndex, TNullable<string>(FormattedText));
end;
end
else
begin
// Handle other component types as needed
end;
finally
Ctx.Free;
end;
end;
// Implement GetORMRec and GetORMRecField in TComponentHelper
function TComponentHelper.GetORMRec: TQryRecInfo;
begin
if not TForm.GORMRecDictionary.TryGetValue(Self, Result) then
Result := nil;
end;
function TComponentHelper.GetORMRecField: string;
begin
if not TForm.GORMRecFieldDictionary.TryGetValue(Self, Result) then
Result := '';
end;
// Implement UpdateComponentFromORM and UpdateORMFromComponent methods as shown above
// ... [Rest of the unit remains unchanged]
end.
Explanation:
Event Handlers:
ORMPropertyChanged: Triggered when an ORM property changes. It finds the associated component and updates its property accordingly.
ComponentPropertyChanged: Triggered when a component's property changes (e.g., user edits a TEdit). It updates the corresponding ORM property.
RegisterORMComponent Modifications:
After linking a component to an ORM property, assigns the OnPropertyChanged event of ORM to ORMPropertyChanged.
Assigns component-specific event handlers (OnChange, etc.) to ComponentPropertyChanged. This allows capturing user interactions.
Initializes the component's display based on the current ORM values via UpdateComponentFromORM.
Synchronization Methods:
UpdateComponentFromORM: Updates the component's property based on the ORM's current value. Utilizes GetFormattedText where necessary.
UpdateORMFromComponent: Updates the ORM's property based on the component's current value. Handles type conversions as needed.
Note:
The above implementation explicitly handles specific component types (TEdit, TLabel, TDatePicker, TComboBox). You can extend this pattern to include other component types by adding additional else if blocks.
Ensure that the SetInfo methods in TQryRecInfo correctly handle type assignments and trigger the OnPropertyChanged event as shown earlier.
To prevent recursive updates (e.g., component change triggering ORM change, which then triggers component change), you might need to implement flags or checks to disable handling temporarily during updates.
4. Implement Initial Synchronization in Main Form
Ensure that upon form creation, the components are correctly initialized based on the ORM data.
Modify Main Unit:
unit Main;
interface
uses
Vcl.Forms, System.Classes, Vcl.Controls, Vcl.StdCtrls, ORM_utils, interposer_class, SysUtils, Dialogs, formgerenc_Classes, Vcl.ComCtrls;
type
TMainForm = class(TForm)
EditUserName: TEdit;
EditPassword: TEdit;
LabelUserName: TLabel;
DatePickerProjectDate: TDatePicker; // Example DatePicker component
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FQueryRec1: TEmployeeProject;
FQueryRec2: TEmployeeProject;
procedure SetupComponents;
public
function RetrieveComponent(ORMRec: TQryRecInfo; FieldName: string): TComponent;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
uses
interposer_class;
{ TMainForm }
procedure TMainForm.Button1Click(Sender: TObject);
begin
var MyComp := RetrieveComponent(FQueryRec2, 'password');
if Assigned(MyComp) then
ShowMessage(MyComp.Name)
else
ShowMessage('Componente não encontrado');
end;
procedure TMainForm.Button2Click(Sender: TObject);
begin
UnRegisterORMComponent(EditPassword);
// Automatically register components where the Hint matches a field in FQueryRec2
RegisterComponentsByHint(FQueryRec2);
begin
var MyComp := RetrieveComponent(FQueryRec2, 'employeeName');
if Assigned(MyComp) then
ShowMessage(MyComp.Name)
else
ShowMessage('Componente employeeName não encontrado');
end;
begin
var MyComp := RetrieveComponent(FQueryRec2, 'employeeId');
if Assigned(MyComp) then
ShowMessage(MyComp.Name)
else
ShowMessage('Componente EmployeeID não encontrado');
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
// Initialize the ORM record instances
FQueryRec1 := TEmployeeProject.Create;
FQueryRec2 := TEmployeeProject.Create;
// Setup components with ORM properties and register them
SetupComponents;
end;
procedure TMainForm.SetupComponents;
begin
// Register EditUserName with FQueryRec1 and FieldName 'UserName'
RegisterORMComponent(EditUserName, FQueryRec1, 'UserName');
// Register EditPassword with FQueryRec2 and FieldName 'Password'
RegisterORMComponent(EditPassword, FQueryRec2, 'Password');
// Register LabelUserName with FQueryRec1 and FieldName 'UserLabel'
RegisterORMComponent(LabelUserName, FQueryRec1, 'UserLabel');
// Register DatePickerProjectDate with FQueryRec2 and FieldName 'ProjectDate'
RegisterORMComponent(DatePickerProjectDate, FQueryRec2, 'ProjectDate');
// Add more component registrations as needed
end;
function TMainForm.RetrieveComponent(ORMRec: TQryRecInfo; FieldName: string): TComponent;
begin
// Find and return the component based on ORMRec and FieldName
Result := FindComponentByORMRec(ORMRec, FieldName);
end;
end.
Explanation:
Component Registration: In SetupComponents, each UI component is registered with its corresponding ORM record and field name using RegisterORMComponent. This establishes the binding and sets up the necessary event handlers.
Initialization: Upon form creation (FormCreate), ORM records are instantiated, and components are set up and bound to ORM properties.
Example DatePicker: Added an example TDatePicker component (DatePickerProjectDate) and registered it. Ensure you have this component on your form and properly named.
5. Ensure GetFormattedText is Properly Implemented
The GetFormattedText method in the TQryRecInfo class is crucial for converting non-string ORM properties to their string representations when mapping to string-based component properties.
Review GetFormattedText in orm_utils Unit:
function TQryRecInfo.GetFormattedText(const FieldName: string): string;
var
Ctx: TRttiContext;
RttiType: TRttiType;
Prop: TRttiProperty;
Field: TRttiField;
Value: TValue;
FmtType: TFormatType;
// ... [Other variables]
begin
Result := '';
Ctx := TRttiContext.Create;
try
RttiType := Ctx.GetType(Self.ClassType);
// Find the property by name
Prop := RttiType.GetProperty(FieldName);
if not Assigned(Prop) then
raise EORMUtilsException.CreateFmt('Property "%s" not found.', [FieldName]);
// Get the value of the property
Value := Prop.GetValue(Self);
FmtType := tiNone;
// Check for FmtProp attribute on the property
for Attr in Prop.GetAttributes do
begin
if Attr is FmtPropAttribute then
begin
FmtAttr := FmtPropAttribute(Attr);
FmtType := FmtAttr.FormatType;
Break;
end;
end;
// If not found on property, check on the corresponding field
if FmtType = tiNone then
begin
Field := RttiType.GetField('_' + FieldName);
if Assigned(Field) then
begin
for Attr in Field.GetAttributes do
begin
if Attr is FmtPropAttribute then
begin
FmtAttr := FmtPropAttribute(Attr);
FmtType := FmtAttr.FormatType;
Break;
end;
end;
end;
end;
// Determine default FmtType based on property type if not set by attribute
if FmtType = tiNone then
begin
// ... [Existing type determination logic]
end;
// Extract actual value from TNullable<T> if necessary
if Value.Kind = tkRecord then
begin
// Handle TNullable<T> types
// ... [Existing logic]
end
else
begin
// Not a record, handle value directly
if not Value.IsEmpty then
Result := FormataInfo(Value.AsVariant, FmtType)
else
Result := '';
end;
finally
// TRttiContext is a record; no need to free
end;
end;
Ensure Correct Implementation:
Formatting Logic: The FormataInfo function converts the ORM's variant value to a string based on the FmtPropAttribute or the property's type.
Property and Field Handling: The method checks both the property and its underlying field (e.g., _EmployeeName) for formatting attributes.
Type Safety: Ensure that the format types (tiString, tiInteger, etc.) correctly correspond to the property types.
Note:
Make sure that all ORM properties meant to be displayed as strings have appropriate FmtPropAttribute decorations or inherit sensible default formatting based on their types.
6. Example Usage and Testing
With the above implementations, here's how the components and ORM records interact:
Initialization:
When the form is created, FQueryRec1 and FQueryRec2 are instantiated.
SetupComponents registers UI components (TEdit, TLabel, TDatePicker, etc.) with their corresponding ORM fields using RegisterORMComponent.
Upon registration, components are initialized with ORM data via UpdateComponentFromORM.
ORM to Component:
If an ORM property's value changes (e.g., via SetInfo), the OnPropertyChanged event is triggered.
The ORMPropertyChanged event handler updates the linked component's property accordingly.
Component to ORM:
When a user modifies a component's property (e.g., edits a TEdit), the component's event handler (ComponentPropertyChanged) updates the corresponding ORM property via RTTI and SetInfo... methods.
Example Scenario:
User Updates EditUserName:
User types into EditUserName (TEdit).
OnChange event triggers ComponentPropertyChanged.
UpdateORMFromComponent reads EditUserName.Text and updates FQueryRec1.UserName.
ORM Record Updates UserName:
Somewhere in the code, FQueryRec1.UserName is updated via SetInfoNullableString.
SetInfo triggers OnPropertyChanged.
ORMPropertyChanged handles the event and updates EditUserName.Text accordingly.
Final Remarks
This implementation establishes a robust bidirectional binding system between your ORM records and UI components. It leverages Delphi's RTTI to handle various component types and ensures that any changes in either the ORM or the UI are appropriately synchronized.
Key Points to Consider:
Event Handling: Ensure that events are correctly assigned and that updating one side of the binding doesn't unintentionally trigger recursive updates.
Thread Safety: If ORM records are manipulated from threads other than the main UI thread, ensure that component updates are marshaled to the main thread using TThread.Synchronize or TThread.Queue.
Error Handling: Implement comprehensive error handling, especially in type conversions and RTTI operations, to prevent runtime exceptions.
Scalability: For larger applications, consider abstracting the binding logic further or using existing data binding frameworks to simplify maintenance.
By following the above steps and ensuring thorough testing, your application will have a reliable and maintainable bidirectional binding mechanism between ORM records and UI components.