if FIsGroup then
begin
SetupGroupControls(PANEL_SPACING, BUTTON_SIZE, CONTROL_HEIGHT);
end else begin
SetupFilterControls(PANEL_SPACING, BUTTON_SIZE, CONTROL_HEIGHT);
end;
// Create close button last so it's always on top
FCloseButton := TscGPCharGlyphButton.Create(FPanel);
with FCloseButton do
begin
Parent := FPanel;
Width := BUTTON_SIZE;
Height := BUTTON_SIZE;
Left := FPanel.Width - Width - PANEL_SPACING;
Top := (FPanel.Height - Height) div 2;
procedure TFilterPanel.HandleDragStart(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
begin
TORMSearchAdvForm(FPanel.Owner).FilterManager.BeginDrag(Self);
FPanel.BeginDrag(False);
end;
end;
procedure TFilterPanel.HandleDragOver(Sender, Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
var
SourcePanel: TFilterPanel;
begin
Accept := False;
if not (Source is TscGPPanel) then Exit;
SourcePanel := TORMSearchAdvForm(FPanel.Owner).FilterManager.FDragPanel;
if not Assigned(SourcePanel) or (SourcePanel = Self) then Exit;
// Prevent dropping parent into child
if IsGroup and SourcePanel.IsGroup then
begin
var TestPanel := ParentGroup;
while Assigned(TestPanel) do
begin
if TestPanel = SourcePanel then Exit;
TestPanel := TestPanel.ParentGroup;
end;
end;
Accept := True;
end;
procedure TFilterPanel.HandleDragDrop(Sender, Source: TObject; X, Y: Integer);
var
SourcePanel: TFilterPanel;
DropPos: TPoint;
begin
if not (Source is TscGPPanel) then Exit;
SourcePanel := TORMSearchAdvForm(FPanel.Owner).FilterManager.FDragPanel;
if not Assigned(SourcePanel) or (SourcePanel = Self) then Exit;
procedure TFilterPanel.ExpandButtonClick(Sender: TObject);
begin
ToggleExpanded;
end;
procedure TFilterPanel.GroupTypeButtonClick(Sender: TObject);
begin
if GroupType = fgtAnd then
GroupType := fgtOr
else
GroupType := fgtAnd;
UpdateGroupTypeVisuals;
end;
procedure TFilterPanel.CloseButtonClick(Sender: TObject);
begin
TORMSearchAdvForm(FPanel.Owner).FilterManager.RemoveFilter(Self);
end;
procedure TFilterPanel.UpdateGroupTypeVisuals;
begin
if not FIsGroup then Exit;
case GroupType of
fgtAnd:
begin
FGroupTypeButton.Caption := 'AND';
FGroupTypeButton.Options.NormalColor := RGB(238, 242, 255);
FGroupTypeButton.Options.FontNormalColor := RGB(79, 70, 229);
end;
fgtOr:
begin
FGroupTypeButton.Caption := 'OR';
FGroupTypeButton.Options.NormalColor := RGB(254, 242, 242);
FGroupTypeButton.Options.FontNormalColor := RGB(220, 38, 38);
end;
end;
end;
procedure TFilterPanel.ToggleExpanded;
begin
if not FIsGroup then Exit;
FIsExpanded := not FIsExpanded;
FContentPanel.Visible := FIsExpanded;
if Assigned(FExpandButton) then
begin
if FIsExpanded then
FExpandButton.GlyphOptions.Index := 263 // chevron down
else
FExpandButton.GlyphOptions.Index := 261; // chevron right
end;
procedure TFilterPanel.SetPosition(const Top: Integer);
begin
FPanel.Top := Top;
end;
function TFilterPanel.CalculateHeight: Integer;
begin
Result := FPanel.Height;
if FIsGroup and FIsExpanded and Assigned(FChildFilters) then
begin
for var Child in FChildFilters do
Inc(Result, Child.CalculateHeight + 4); // 4px spacing
end;
end;
function TFilterPanel.GetFilterCondition: string;
var
SelectedColumn: TSearchAdvColumn;
Form: TORMSearchAdvForm;
begin
Result := '';
if FIsGroup then Exit;
Form := TORMSearchAdvForm(FPanel.Owner);
if not Assigned(Form) then Exit;
// Find selected column
SelectedColumn := nil;
for var Column in Form.FSearchColumns do
begin
if Column.DisplayName = FFieldCombo.Text then
begin
SelectedColumn := Column;
Break;
end;
end;
if not Assigned(SelectedColumn) then Exit;
// Build condition based on operator
case FFilterInfo.OperationType of
fotEqual:
Result := Format('%s = %s', [SelectedColumn.FieldName, QuoteValue(FValueEdit.Text, SelectedColumn.DataType)]);
fotNotEqual:
Result := Format('%s <> %s', [SelectedColumn.FieldName, QuoteValue(FValueEdit.Text, SelectedColumn.DataType)]);
fotGreaterThan:
Result := Format('%s > %s', [SelectedColumn.FieldName, QuoteValue(FValueEdit.Text, SelectedColumn.DataType)]);
fotLessThan:
Result := Format('%s < %s', [SelectedColumn.FieldName, QuoteValue(FValueEdit.Text, SelectedColumn.DataType)]);
fotGreaterEqual:
Result := Format('%s >= %s', [SelectedColumn.FieldName, QuoteValue(FValueEdit.Text, SelectedColumn.DataType)]);
fotLessEqual:
Result := Format('%s <= %s', [SelectedColumn.FieldName, QuoteValue(FValueEdit.Text, SelectedColumn.DataType)]);
fotBetween:
Result := Format('(%s BETWEEN %s AND %s)', [SelectedColumn.FieldName,
QuoteValue(FFilterInfo.Value1, SelectedColumn.DataType),
QuoteValue(FFilterInfo.Value2, SelectedColumn.DataType)]);
fotContains:
Result := Format('%s LIKE ''%%%s%%''', [SelectedColumn.FieldName, QuoteEsc(FValueEdit.Text)]);
fotStartsWith:
Result := Format('%s LIKE ''%s%%''', [SelectedColumn.FieldName, QuoteEsc(FValueEdit.Text)]);
fotEndsWith:
Result := Format('%s LIKE ''%%%s''', [SelectedColumn.FieldName, QuoteEsc(FValueEdit.Text)]);
fotIsNull:
Result := Format('(%s IS NULL)', [SelectedColumn.FieldName]);
fotIsNotNull:
Result := Format('(%s IS NOT NULL)', [SelectedColumn.FieldName]);
end;
end;
function TFilterPanel.ValidateFilter: Boolean;
begin
Result := False;
if FIsGroup then Exit(True);
// Basic validation
if FFieldCombo.ItemIndex < 0 then Exit;
if FOperatorCombo.ItemIndex < 0 then Exit;
// Find selected column
var Form := TORMSearchAdvForm(FPanel.Owner);
var SelectedColumn: TSearchAdvColumn := nil;
for var Column in Form.FSearchColumns do
begin
if Column.DisplayName = FFieldCombo.Text then
begin
SelectedColumn := Column;
Break;
end;
end;
if not Assigned(SelectedColumn) then Exit;
// Skip value validation for null checks
if (FOperatorCombo.Text = 'Is Empty') or
(FOperatorCombo.Text = 'Is Not Empty') then
begin
Result := True;
Exit;
end;
// Validate based on data type
case SelectedColumn.DataType of
tiString:
// String values are always valid
Result := True;
tiInteger:
begin
var IntValue: Int64;
Result := TryStrToInt64(FValueEdit.Text, IntValue);
end;
tiFloat, tiMoney:
begin
var FloatValue: Extended;
Result := TryStrToFloat(FValueEdit.Text, FloatValue);
end;
tiDate, tiDateTime:
begin
Result := FDateValue.Date > 0;
end;
tiBoolean:
begin
var BoolStr := LowerCase(FValueEdit.Text);
Result := (BoolStr = 'true') or (BoolStr = 'false') or
(BoolStr = '1') or (BoolStr = '0') or
(BoolStr = 'yes') or (BoolStr = 'no');
end;
end;
end;
function TFilterPanel.QuoteValue(const Value: Variant; ADataType: TORMFormatType): string;
begin
if Value.Trim = '' then
Exit('NULL');
case ADataType of
tiString:
Result := QuotedStr(Value);
tiInteger, tiFloat, tiMoney:
begin
if ADataType = tiMoney then
Result := QuoteNum(GetMoney(Value))
else
Result := QuoteNum(Value);
end;
tiDate:
Result := QuotedStr(FormatDateTime('yyyy-mm-dd', FDateValue.Date));
tiDateTime:
Result := QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', FDateValue.Date));
tiBoolean:
begin
var BoolStr := LowerCase(Value);
if (BoolStr = 'true') or (BoolStr = '1') or (BoolStr = 'yes') then
Result := 'TRUE'
else
Result := 'FALSE';
end;
else
Result := QuotedStr(Value);
end;
end;
procedure TFilterPanel.UpdateLayout;
begin
if not FIsGroup then Exit;
var YPos := FPanel.Height;
if FIsExpanded and Assigned(FChildFilters) then
begin
for var Child in FChildFilters do
begin
Child.Panel.Top := YPos;
Inc(YPos, Child.Panel.Height + 4); // 4px spacing
Child.UpdateLayout;
end;
end;
if Assigned(FContentPanel) then
FContentPanel.Height := YPos;
end;
destructor TFilterManager.Destroy;
begin
FRootFilters.Free;
inherited;
end;
function TFilterManager.CreateUniqueId: Integer;
begin
Result := FNextId;
Inc(FNextId);
end;
function TFilterManager.CreateFilterGroup(GroupType: TFilterGroupType;
Parent: TFilterPanel = nil): TFilterPanel;
begin
if Assigned(Parent) then
Result := TFilterPanel.Create(FForm, Parent.Level + 1,
Parent, True)
else Result := TFilterPanel.Create(FForm, 0,
Parent, True);
Result.GroupType := GroupType;
if Assigned(Parent) then
Parent.AddChild(Result)
else
FRootFilters.Add(Result);
UpdateLayout;
end;
function TFilterManager.CreateFilter(Parent: TFilterPanel = nil): TFilterPanel;
begin
if Assigned(Parent) then
Result := TFilterPanel.Create(FForm, Parent.Level + 1,
Parent, False)
else Result := TFilterPanel.Create(FForm, 0,
Parent, False);
if Assigned(Parent) then
Parent.AddChild(Result)
else
FRootFilters.Add(Result);
UpdateLayout;
end;
procedure TFilterManager.RemoveFilter(Filter: TFilterPanel);
begin
if not Assigned(Filter) then Exit;
// First remove from parent if it has one
if Assigned(Filter.ParentGroup) then
Filter.ParentGroup.RemoveChild(Filter)
else
FRootFilters.Extract(Filter);
// Handle removal of child filters if this is a group
if Filter.IsGroup and Assigned(Filter.ChildFilters) then
begin
while Filter.ChildFilters.Count > 0 do
begin
var Child := Filter.ChildFilters[0];
Filter.RemoveChild(Child);
if not Assigned(Child.ParentGroup) then
Child.Free;
end;
end;
// Clean up the filter panel
Filter.Panel.Parent := nil;
Filter.Free;
UpdateLayout;
HandleFilterRemoved(Filter);
end;
procedure TFilterManager.HandleFilterRemoved(Filter: TFilterPanel);
begin
// Update UI state
FForm.UpdateLayout;
// Clear any active drag operation
if FDragPanel = Filter then
FDragPanel := nil;
end;
function TFilterManager.FindFilterById(Id: Integer): TFilterPanel;
function SearchInGroup(Group: TFilterPanel): TFilterPanel;
begin
Result := nil;
if not Assigned(Group) or not Group.IsGroup then Exit;
for var Child in Group.ChildFilters do
begin
if Child.Id = Id then
Exit(Child);
if Child.IsGroup then
begin
Result := SearchInGroup(Child);
if Assigned(Result) then
Exit;
end;
end;
end;
begin
Result := nil;
// Search in root filters first
for var Filter in FRootFilters do
begin
if Filter.Id = Id then
Exit(Filter);
if Filter.IsGroup then
begin
Result := SearchInGroup(Filter);
if Assigned(Result) then
Exit;
end;
end;
end;
procedure TFilterManager.MoveFilter(Source, Target: TFilterPanel; Position: TPoint);
var
OldParent: TFilterPanel;
InsertIndex: Integer;
begin
if not Assigned(Source) or not Assigned(Target) then Exit;
// Don't allow dropping on self or invalid hierarchy
if (Source = Target) or
(Target.IsGroup and IsFilterInHierarchy(Target, Source)) then
Exit;
OldParent := Source.ParentGroup;
// Remove from old parent
if Assigned(OldParent) then
OldParent.RemoveChild(Source)
else
FRootFilters.Extract(Source);
// Determine if dropping into group or between filters
if Target.IsGroup and (Position.Y < Target.Panel.Height) then
begin
// Dropping into group
Target.AddChild(Source);
end
else
begin
// Dropping between filters
if Assigned(Target.ParentGroup) then
begin
InsertIndex := Target.ParentGroup.ChildFilters.IndexOf(Target);
if Position.Y > Target.Panel.Height div 2 then
Inc(InsertIndex);
Source.ParentGroup := Target.ParentGroup;
Target.ParentGroup.ChildFilters.Insert(InsertIndex, Source);
end
else
begin
InsertIndex := FRootFilters.IndexOf(Target);
if Position.Y > Target.Panel.Height div 2 then
Inc(InsertIndex);
Source.ParentGroup := nil;
FRootFilters.Insert(InsertIndex, Source);
end;
end;
UpdateLayout;
end;
function TFilterManager.IsFilterInHierarchy(Parent, Child: TFilterPanel): Boolean;
var
Current: TFilterPanel;
begin
Result := False;
if not Assigned(Parent) or not Assigned(Child) then Exit;
Current := Child;
while Assigned(Current) do
begin
if Current = Parent then
Exit(True);
Current := Current.ParentGroup;
end;
end;
procedure TFilterManager.UpdateLayout;
var
TotalHeight: Integer;
begin
TotalHeight := 0;
for var Filter in FRootFilters do
begin
Filter.SetPosition(TotalHeight);
Inc(TotalHeight, Filter.CalculateHeight + 4); // 4px spacing
Filter.UpdateLayout;
end;
// Update container size
if TotalHeight > 0 then
Inc(TotalHeight, 8); // Add margins
// Force visual update
FForm.pnlFilterContainer.Invalidate;
Application.ProcessMessages;
end;
procedure TFilterManager.BeginDrag(Filter: TFilterPanel);
begin
FDragPanel := Filter;
end;
procedure TFilterManager.EndDrag;
begin
FDragPanel := nil;
end;
function TFilterManager.BuildFilterSQL: string;
var
SQL: TStringBuilder;
procedure AddGroupFilters(Group: TFilterPanel);
var
IsFirst: Boolean;
begin
if not Group.IsGroup then Exit;
IsFirst := True;
SQL.Append('(');
for var Child in Group.ChildFilters do
begin
if not IsFirst then
begin
if Group.GroupType = fgtAnd then
SQL.Append(' AND ')
else
SQL.Append(' OR ');
end;
if Child.IsGroup then
AddGroupFilters(Child)
else
begin
// Add individual filter condition
SQL.Append(Child.GetFilterCondition);
end;
IsFirst := False;
end;
SQL.Append(')');
end;
begin
SQL := TStringBuilder.Create;
try
var IsFirst := True;
for var Filter in FRootFilters do
begin
if not IsFirst then
SQL.Append(' AND ');
if Filter.IsGroup then
AddGroupFilters(Filter)
else
SQL.Append(Filter.GetFilterCondition);
IsFirst := False;
end;
Result := SQL.ToString;
finally
SQL.Free;
end;
end;
function TFilterManager.ValidateFilters: Boolean;
function ValidateGroup(Group: TFilterPanel): Boolean;
begin
Result := False;
if not Group.IsGroup then Exit;
// Group must have at least one child
if Group.ChildFilters.Count = 0 then Exit;
// Validate each child
for var Child in Group.ChildFilters do
begin
if Child.IsGroup then
begin
if not ValidateGroup(Child) then Exit;
end
else
begin
if not Child.ValidateFilter then Exit;
end;
end;
Result := True;
end;
begin
Result := True;
// Must have at least one filter
if FRootFilters.Count = 0 then
begin
Result := False;
Exit;
end;
// Validate all root filters
for var Filter in FRootFilters do
begin
if Filter.IsGroup then
begin
if not ValidateGroup(Filter) then
begin
Result := False;
Break;
end;
end
else
begin
if not Filter.ValidateFilter then
begin
Result := False;
Break;
end;
end;
end;
end;
{ TORMSearchAdvForm Implementation }
procedure TORMSearchAdvForm.SetupVisuals;
begin
// Configure form appearance
Font.Name := 'Segoe UI';
Font.Size := 9;
// Style the main container
pnlMain.FillColor := RGB(249, 250, 251);
pnlMain.FillColorAlpha := 255;
// Configure buttons
with btnAddAndGroup do
begin
GlyphOptions.Size := 16;
GlyphOptions.Index := 85; // Plus icon
Caption := 'Add AND Group';
Options.NormalColor := clWhite;
Options.NormalColorAlpha := 255;
Options.ShapeCornerRadius := 4;
end;
with btnAddOrGroup do
begin
GlyphOptions.Size := 16;
GlyphOptions.Index := 85; // Plus icon
Caption := 'Add OR Group';
Options.NormalColor := clWhite;
Options.NormalColorAlpha := 255;
Options.ShapeCornerRadius := 4;
end;
with btnClearAll do
begin
GlyphOptions.Size := 16;
GlyphOptions.Index := 13; // X icon
Caption := 'Clear All';
Options.NormalColor := clWhite;
Options.NormalColorAlpha := 255;
Options.ShapeCornerRadius := 4;
Enabled := False;
end;
// Copy search columns
for var Column in ASearchColumns do
FSearchColumns.Add(TSearchAdvColumn.Create(
Column.FieldName,
Column.DisplayName,
Column.Width,
Column.Visible,
Column.UsableAsFilter
));
SetupFieldTypes;
SetupGrid;
LoadData;
end;
procedure TORMSearchAdvForm.SetupFieldTypes;
begin
if not Assigned(FQuery) then
FQuery := TUniQuery.Create(nil);
for var i := 0 to FSearchColumns.Count - 1 do
begin
with SearchGrid do
begin
// Set column header
Cells[i, 0] := FSearchColumns[i].DisplayName;
// Configure column width
ColWidths[i] := FSearchColumns[i].Width;
// Hide column if not visible
if not FSearchColumns[i].Visible then
ColWidths[i] := 0;
// Set column alignment based on data type
case FSearchColumns[i].DataType of
tiInteger, tiFloat, tiMoney:
Columns[i].Alignment := taRightJustify;
tiDate, tiDateTime:
Columns[i].Alignment := taCenter;
else
Columns[i].Alignment := taLeftJustify;
end;
end;
end;
finally
SearchGrid.EndUpdate;
end;
end;
procedure TORMSearchAdvForm.LoadData;
begin
if not Assigned(FQuery) then
FQuery := TUniQuery.Create(nil);
function TORMSearchAdvForm.GetFilteredSQL: string;
var
FilterSQL: string;
begin
Result := FBaseQuery;
FilterSQL := FFilterManager.BuildFilterSQL;
if FilterSQL <> '' then
begin
if Pos('WHERE', UpperCase(Result)) > 0 then
Result := Result + ' AND (' + FilterSQL + ')'
else
Result := Result + ' WHERE ' + FilterSQL;
end;
end;
procedure TORMSearchAdvForm.UpdateGridData;
begin
SearchGrid.BeginUpdate;
try
SearchGrid.RowCount := FQuery.RecordCount + SearchGrid.FixedRows;
var Row := SearchGrid.FixedRows;
FQuery.First;
while not FQuery.Eof do
begin
for var i := 0 to FSearchColumns.Count - 1 do
begin
var Field := FQuery.FieldByName(FSearchColumns[i].FieldName);
if Assigned(Field) then
begin
if Field.IsNull then
SearchGrid.Cells[i, Row] := ''
else
case FSearchColumns[i].DataType of
tiDate:
SearchGrid.Cells[i, Row] := FormatDateTime('dd/mm/yyyy', Field.AsDateTime);
tiDateTime:
SearchGrid.Cells[i, Row] := FormatDateTime('dd/mm/yyyy hh:nn:ss', Field.AsDateTime);
tiFloat, tiMoney:
SearchGrid.Cells[i, Row] := FormatFloat('#,##0.00', Field.AsFloat);
else
SearchGrid.Cells[i, Row] := Field.AsString;
end;
end;
end;
Inc(Row);
FQuery.Next;
end;
finally
SearchGrid.EndUpdate;
end;
end;
procedure TORMSearchAdvForm.FormCreate(Sender: TObject);
begin
SetupVisuals;
end;
procedure TORMSearchAdvForm.FormDestroy(Sender: TObject);
begin
// Cleanup handled in destructor
end;
procedure TORMSearchAdvForm.btnAddAndGroupClick(Sender: TObject);
begin
FFilterManager.CreateFilterGroup(fgtAnd);
UpdateControlStates;
end;
procedure TORMSearchAdvForm.btnAddOrGroupClick(Sender: TObject);
begin
FFilterManager.CreateFilterGroup(fgtOr);
UpdateControlStates;
end;
procedure TORMSearchAdvForm.btnAddFilterClick(Sender: TObject);
begin
FFilterManager.CreateFilter;
UpdateControlStates;
end;
procedure TORMSearchAdvForm.btnClearAllClick(Sender: TObject);
begin
FFilterManager.FRootFilters.Clear;
FFilterManager.UpdateLayout;
LoadData;
UpdateControlStates;
end;
procedure TORMSearchAdvForm.btnApplyClick(Sender: TObject);
begin
if ValidateFilters then
begin
LoadData;
UpdateControlStates;
end;
end;
procedure TORMSearchAdvForm.UpdateControlStates;
var
HasFilters: Boolean;
begin
HasFilters := FFilterManager.FRootFilters.Count > 0;
btnApply.Enabled := HasFilters;
btnClearAll.Enabled := HasFilters;
end;
function TORMSearchAdvForm.ValidateFilters: Boolean;
begin
Result := FFilterManager.ValidateFilters;
if not Result then
begin
MessageDlg('Please ensure all filters are properly configured.',
mtWarning, [mbOK], 0);
end;
end;
procedure TORMSearchAdvForm.SearchGridDblClick(Sender: TObject);
begin
if SearchGrid.Row >= SearchGrid.FixedRows then
begin
UpdateSelectedSearch;
ModalResult := mrOk;
end;
end;
procedure TORMSearchAdvForm.UpdateSelectedSearch;
begin
if SearchGrid.Row < SearchGrid.FixedRows then Exit;
// Create new selected search
FreeAndNil(FSelectedSearch);
FSelectedSearch := TSelectedAdvSearch.Create;
// Calculate record number
var RecNo := SearchGrid.Row - SearchGrid.FixedRows;
// Move query to correct record
FQuery.First;
for var i := 0 to RecNo - 1 do
FQuery.Next;
// Get values from the record
for var i := 0 to FSearchColumns.Count - 1 do
begin
var Field := FQuery.FieldByName(FSearchColumns[i].FieldName);
if Assigned(Field) then
begin
var Value: TValue;
if Field.IsNull then
Value := TValue.Empty
else
case Field.DataType of
ftString, ftWideString:
Value := TValue.From(Field.AsString);
ftInteger, ftSmallint:
Value := TValue.From(Field.AsInteger);
ftFloat, ftCurrency:
Value := TValue.From(Field.AsFloat);
ftDateTime, ftDate:
Value := TValue.From(Field.AsDateTime);
ftBoolean:
Value := TValue.From(Field.AsBoolean);
else
Value := TValue.From(Field.AsString);
end;
class function TORMSearchAdvForm.Execute(
AConnection: TUniConnection;
const ABaseQuery: string;
const ASearchColumns: array of TSearchAdvColumn;
var ASelectedSearch: TSelectedAdvSearch;
ARecordClass: TClass = nil): Boolean;
var
SearchForm: TORMSearchAdvForm;
begin
Result := False;
SearchForm := TORMSearchAdvForm.Create(nil);
try
SearchForm.InitializeSearch(AConnection, ABaseQuery, ASearchColumns, ARecordClass);
if SearchForm.ShowModal = mrOk then
begin
ASelectedSearch := SearchForm.FSelectedSearch;
SearchForm.FSelectedSearch := nil; // Prevent double free
Result := True;
end;
function TSelectedAdvSearch.GetValue(const AFieldName: string): TValue;
begin
if not FValues.TryGetValue(AFieldName, Result) then
Result := TValue.Empty;
end;
function TSelectedAdvSearch.GetDisplayValue(const AFieldName: string): string;
begin
if not FDisplayValues.TryGetValue(AFieldName, Result) then
Result := '';
end;
{ TFilterPanel }
procedure TFilterPanel.FieldComboChange(Sender: TObject);
var
Form: TORMSearchAdvForm;
begin
if not Assigned(FFieldCombo) then Exit;
Form := TORMSearchAdvForm(FPanel.Owner);
// Update the filter info with new field
for var Column in Form.FSearchColumns do
begin
if Column.DisplayName = FFieldCombo.Text then
begin
FFilterInfo.FieldName := Column.FieldName;
FFilterInfo.DataType := Column.DataType;
Break;
end;
end;
UpdateOperators;
UpdateValueControls;
end;
procedure TFilterPanel.OperatorComboChange(Sender: TObject);
begin
if FOperatorCombo.Text =
'Equals' then FFilterInfo.OperationType := fotEqual
else if FOperatorCombo.Text =
'Not Equals' then FFilterInfo.OperationType := fotNotEqual
else if FOperatorCombo.Text =
'Greater Than'then FFilterInfo.OperationType := fotGreaterThan
else if FOperatorCombo.Text =
'Less Than' then FFilterInfo.OperationType := fotLessThan
else if FOperatorCombo.Text =
'Greater or Equal' then FFilterInfo.OperationType := fotGreaterEqual
else if FOperatorCombo.Text =
'Less or Equal' then FFilterInfo.OperationType := fotLessEqual
else if FOperatorCombo.Text =
'Between' then FFilterInfo.OperationType := fotBetween
else if FOperatorCombo.Text =
'Contains' then FFilterInfo.OperationType := fotContains
else if FOperatorCombo.Text =
'Starts With' then FFilterInfo.OperationType := fotStartsWith
else if FOperatorCombo.Text =
'Ends With' then FFilterInfo.OperationType := fotEndsWith
else if FOperatorCombo.Text =
'Is Empty' then FFilterInfo.OperationType := fotIsNull
else if FOperatorCombo.Text =
'Is Not Empty' then FFilterInfo.OperationType := fotIsNotNull;
UpdateValueControls;
end;
procedure TFilterPanel.UpdateOperators;
begin
if not Assigned(FOperatorCombo) then Exit;
FOperatorCombo.Items.Clear;
// Common operators for all types
FOperatorCombo.Items.Add('Is Empty');
FOperatorCombo.Items.Add('Is Not Empty');
case FFilterInfo.DataType of
tiString:
begin
FOperatorCombo.Items.AddStrings(['Equals', 'Not Equals',
'Contains', 'Starts With', 'Ends With']);
end;
tiInteger, tiFloat, tiMoney:
begin
FOperatorCombo.Items.AddStrings(['Equals', 'Not Equals',
'Greater Than', 'Less Than', 'Greater or Equal',
'Less or Equal', 'Between']);
end;
tiDate, tiDateTime:
begin
FOperatorCombo.Items.AddStrings(['Equals', 'Not Equals',
'Greater Than', 'Less Than', 'Greater or Equal',
'Less or Equal', 'Between']);
end;
tiBoolean:
begin
FOperatorCombo.Items.AddStrings(['Equals', 'Not Equals']);
end;
end;
if FOperatorCombo.Items.Count > 0 then
FOperatorCombo.ItemIndex := 0;
end;
procedure TFilterPanel.UpdateValueControls;
var
ShowValue1, ShowValue2: Boolean;
begin
if not (Assigned(FValueEdit) and Assigned(FDateValue)) then Exit;
// Determine which controls to show
ShowValue1 := not (FFilterInfo.OperationType in [fotIsNull, fotIsNotNull]);
ShowValue2 := FFilterInfo.OperationType = fotBetween;
// Show appropriate controls based on data type
case FFilterInfo.DataType of
tiDate, tiDateTime:
begin
FDateValue.Visible := ShowValue1;
FDateValue2.Visible := ShowValue2;
FValueEdit.Visible := False;
FValueEdit2.Visible := ShowValue2;
end;
else
begin
FDateValue.Visible := False;
FDateValue2.Visible := False;
FValueEdit.Visible := ShowValue1;
FValueEdit2.Visible := ShowValue2;
end;
end;
end;
function TFilterPanel.FormatValue(const Value: Variant): string;
begin
if VarIsNull(Value) or VarIsEmpty(Value) then
Exit('NULL');
case FFilterInfo.DataType of
tiString:
Result := QuotedStr(VarToStr(Value));
tiInteger:
Result := Value;
tiFloat, tiMoney:
Result := FormatFloat('#,##0.00', Value);
tiDate:
Result := QuotedStr(FormatDateTime('yyyy-mm-dd', VarToDateTime(Value)));
tiDateTime:
Result := QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', VarToDateTime(Value)));
tiBoolean:
Result := IfThen(Boolean(Value), 'TRUE', 'FALSE');
end;
end;
function TFilterPanel.GetFilterInfo: TFilterValueInfo;
begin
// Update values before returning
if FFilterInfo.DataType in [tiDate, tiDateTime] then
begin
if FDateValue.Visible then
FFilterInfo.Value1 := FDateValue.Date;
end
else
begin
if FValueEdit.Visible then
FFilterInfo.Value1 := FValueEdit.Text;
end;
Result := FFilterInfo;
end;
{ TORMSearchAdvForm }
procedure TORMSearchAdvForm.UpdateLayout;
begin
if Assigned(FFilterManager) then
FFilterManager.UpdateLayout;
end;
procedure TORMSearchAdvForm.BuildFilter;
begin
LoadData;
end;
{ TFilterManager }
procedure TFilterManager.UpdateFilterLayout;
begin
var TotalHeight := 0;
for var Filter in FRootFilters do
begin
Filter.SetPosition(TotalHeight);
Inc(TotalHeight, Filter.CalculateHeight + 4); // 4px spacing
Filter.UpdateLayout;
end;
// Update container size
if TotalHeight > 0 then
Inc(TotalHeight, 8); // Add margins
// Group type button (AND/OR)
FGroupTypeButton := TscGPCharGlyphButton.Create(FPanel);
with FGroupTypeButton do
begin
Parent := FPanel;
Width := 60;
Height := ControlHeight;
Left := FExpandButton.Left + FExpandButton.Width + PanelSpacing;
Top := (FPanel.Height - Height) div 2;
ShowCaption := True;
Caption := IfThen(GroupType = fgtAnd, 'AND', 'OR');
Font.Style := [fsBold];
Options.ShapeStyle := scgpRect;
Options.ShapeCornerRadius := 4;
Options.NormalColor := IfThen(GroupType = fgtAnd,
RGB(238, 242, 255), // Light indigo for AND
RGB(254, 242, 242)); // Light red for OR
Options.NormalColorAlpha := 255;
Options.FontNormalColor := IfThen(GroupType = fgtAnd,
RGB(79, 70, 229), // Indigo for AND
RGB(220, 38, 38)); // Red for OR
OnClick := GroupTypeButtonClick;
end;
// Content panel for child filters
FContentPanel := TscGPPanel.Create(FPanel);
with FContentPanel do
begin
Parent := FPanel;
Left := INDENT_WIDTH;
Top := FPanel.Height;
Width := FPanel.Width - Left - PanelSpacing;
Align := alCustom;
Visible := FIsExpanded;
procedure TFilterPanel.SetupFilterControls(PanelSpacing, ButtonSize, ControlHeight: Integer);
const
FIELD_WIDTH = 150;
OPERATOR_WIDTH = 120;
VALUE_WIDTH = 150;
begin
// Field selector
FFieldCombo := TscComboBox.Create(FPanel);
with FFieldCombo do
begin
Parent := FPanel;
Width := FIELD_WIDTH;
Height := ControlHeight;
Left := FDragHandle.Left + FDragHandle.Width + PanelSpacing;
Top := (FPanel.Height - Height) div 2;
Style := csDropDownList;
// Style the dropdown
StyleKind := scscbPushButton;
{
Options.ShapeCornerRadius := 4;
Options.FrameNormalColor := RGB(209, 213, 219);
Options.FrameWidth := 1;
}
// Populate with available fields
Items.Clear;
for var Column in TORMSearchAdvForm(FPanel.Owner).FSearchColumns do
if Column.UsableAsFilter then
Items.Add(Column.DisplayName);
if Items.Count > 0 then
ItemIndex := 0;
OnChange := FieldComboChange;
end;
// Operator selector
FOperatorCombo := TscComboBox.Create(FPanel);
with FOperatorCombo do
begin
Parent := FPanel;
Width := OPERATOR_WIDTH;
Height := ControlHeight;
Left := FFieldCombo.Left + FFieldCombo.Width + PanelSpacing;
Top := (FPanel.Height - Height) div 2;
Style := csDropDownList;
// Value input
FValueEdit := TscGPEdit.Create(FPanel);
with FValueEdit do
begin
Parent := FPanel;
Width := VALUE_WIDTH;
Height := ControlHeight;
Left := FOperatorCombo.Left + FOperatorCombo.Width + PanelSpacing;
Top := (FPanel.Height - Height) div 2;
// Date picker (initially hidden)
FDateValue := TscGPDateEdit.Create(FPanel);
with FDateValue do
begin
Parent := FPanel;
Width := VALUE_WIDTH;
Height := ControlHeight;
Left := FValueEdit.Left;
Top := FValueEdit.Top;
Visible := False;
// Second Value input (hidden by default)
FValueEdit2 := TscGPEdit.Create(FPanel);
with FValueEdit2 do
begin
Parent := FPanel;
Width := VALUE_WIDTH;
Height := ControlHeight;
Left := FValueEdit.Left + FValueEdit.Width + PanelSpacing;
Top := FValueEdit.Top;
// Date picker for second value (hidden by default)
FDateValue2 := TscGPDateEdit.Create(FPanel);
with FDateValue2 do
begin
Parent := FPanel;
Width := VALUE_WIDTH;
Height := ControlHeight;
Left := FDateValue.Left + FDateValue.Width + PanelSpacing;
Top := FDateValue.Top;
Visible := False;
After carefully reviewing your Delphi unit orm_advsearch, I have identified several bugs and potential issues that need to be addressed to ensure the code functions correctly. Below is a detailed analysis of these issues along with the necessary corrections.
1. Incorrect Handling of Value2 in TFilterPanel.GetFilterInfo
Issue:
The GetFilterInfo method does not set FFilterInfo.Value2 when the filter operation is fotBetween. This leads to incomplete filter conditions, especially for operations that require two values.
Location:
function TFilterPanel.GetFilterCondition: string;
begin
// ...
end;
function TFilterPanel.GetFilterInfo: TFilterValueInfo;
begin
// Update values before returning
if FFilterInfo.DataType in [tiDate, tiDateTime] then
begin
if FDateValue.Visible then
FFilterInfo.Value1 := FDateValue.Date;
end
else
begin
if FValueEdit.Visible then
FFilterInfo.Value1 := FValueEdit.Text;
end;
Result := FFilterInfo;
end;
Correction:
Modify the GetFilterInfo method to set both Value1 and Value2 when the operation is fotBetween. Additionally, ensure that date controls (FDateValue and FDateValue2) and edit controls (FValueEdit and FValueEdit2) are properly handled based on their visibility.
Updated GetFilterInfo:
function TFilterPanel.GetFilterInfo: TFilterValueInfo;
begin
// Update values before returning
if FFilterInfo.DataType in [tiDate, tiDateTime] then
begin
if FDateValue.Visible then
FFilterInfo.Value1 := FDateValue.Date;
if (FFilterInfo.OperationType = fotBetween) and FDateValue2.Visible then
FFilterInfo.Value2 := FDateValue2.Date;
end
else
begin
if FValueEdit.Visible then
FFilterInfo.Value1 := FValueEdit.Text;
if (FFilterInfo.OperationType = fotBetween) and FValueEdit2.Visible then
FFilterInfo.Value2 := FValueEdit2.Text;
end;
Result := FFilterInfo;
end;
Additional Update in GetFilterCondition:
Ensure that Value2 is properly quoted and formatted:
function TFilterPanel.GetFilterCondition: string;
var
SelectedColumn: TSearchAdvColumn;
Form: TORMSearchAdvForm;
begin
Result := '';
if FIsGroup then Exit;
Form := TORMSearchAdvForm(FPanel.Owner);
if not Assigned(Form) then Exit;
// Find selected column
SelectedColumn := nil;
for var Column in Form.FSearchColumns do
begin
if Column.DisplayName = FFieldCombo.Text then
begin
SelectedColumn := Column;
Break;
end;
end;
if not Assigned(SelectedColumn) then Exit;
// Build condition based on operator
case FFilterInfo.OperationType of
fotEqual:
Result := Format('%s = %s', [SelectedColumn.FieldName, QuoteValue(FFilterInfo.Value1, SelectedColumn.DataType)]);
fotNotEqual:
Result := Format('%s <> %s', [SelectedColumn.FieldName, QuoteValue(FFilterInfo.Value1, SelectedColumn.DataType)]);
fotGreaterThan:
Result := Format('%s > %s', [SelectedColumn.FieldName, QuoteValue(FFilterInfo.Value1, SelectedColumn.DataType)]);
fotLessThan:
Result := Format('%s < %s', [SelectedColumn.FieldName, QuoteValue(FFilterInfo.Value1, SelectedColumn.DataType)]);
fotGreaterEqual:
Result := Format('%s >= %s', [SelectedColumn.FieldName, QuoteValue(FFilterInfo.Value1, SelectedColumn.DataType)]);
fotLessEqual:
Result := Format('%s <= %s', [SelectedColumn.FieldName, QuoteValue(FFilterInfo.Value1, SelectedColumn.DataType)]);
fotBetween:
Result := Format('(%s BETWEEN %s AND %s)', [SelectedColumn.FieldName,
QuoteValue(FFilterInfo.Value1, SelectedColumn.DataType),
QuoteValue(FFilterInfo.Value2, SelectedColumn.DataType)]);
fotContains:
Result := Format('%s LIKE ''%%%s%%''', [SelectedColumn.FieldName, QuoteEsc(FFilterInfo.Value1)]);
fotStartsWith:
Result := Format('%s LIKE ''%s%%''', [SelectedColumn.FieldName, QuoteEsc(FFilterInfo.Value1)]);
fotEndsWith:
Result := Format('%s LIKE ''%%%s''', [SelectedColumn.FieldName, QuoteEsc(FFilterInfo.Value1)]);
fotIsNull:
Result := Format('(%s IS NULL)', [SelectedColumn.FieldName]);
fotIsNotNull:
Result := Format('(%s IS NOT NULL)', [SelectedColumn.FieldName]);
end;
end;
2. Incomplete Validation for fotBetween Operations in TFilterPanel.ValidateFilter
Issue:
The ValidateFilter method does not check whether both Value1 and Value2 are properly set and valid when the operation is fotBetween. This could allow incomplete or invalid filter conditions to be applied.
Location:
function TFilterPanel.ValidateFilter: Boolean;
begin
Result := False;
if FIsGroup then Exit(True);
// Basic validation
if FFieldCombo.ItemIndex < 0 then Exit;
if FOperatorCombo.ItemIndex < 0 then Exit;
// Find selected column
var Form := TORMSearchAdvForm(FPanel.Owner);
var SelectedColumn: TSearchAdvColumn := nil;
for var Column in Form.FSearchColumns do
begin
if Column.DisplayName = FFieldCombo.Text then
begin
SelectedColumn := Column;
Break;
end;
end;
if not Assigned(SelectedColumn) then Exit;
// Skip value validation for null checks
if (FOperatorCombo.Text = 'Is Empty') or
(FOperatorCombo.Text = 'Is Not Empty') then
begin
Result := True;
Exit;
end;
// Validate based on data type
case SelectedColumn.DataType of
tiString:
// String values are always valid
Result := True;
tiInteger:
begin
var IntValue: Int64;
Result := TryStrToInt64(FValueEdit.Text, IntValue);
end;
tiFloat, tiMoney:
begin
var FloatValue: Extended;
Result := TryStrToFloat(FValueEdit.Text, FloatValue);
end;
tiDate, tiDateTime:
begin
Result := FDateValue.Date > 0;
end;
tiBoolean:
begin
var BoolStr := LowerCase(FValueEdit.Text);
Result := (BoolStr = 'true') or (BoolStr = 'false') or
(BoolStr = '1') or (BoolStr = '0') or
(BoolStr = 'yes') or (BoolStr = 'no');
end;
end;
end;
Correction:
Enhance the ValidateFilter method to include additional checks for fotBetween operations, ensuring both Value1 and Value2 are valid and set.
Updated ValidateFilter:
function TFilterPanel.ValidateFilter: Boolean;
begin
Result := False;
if FIsGroup then Exit(True);
// Basic validation
if FFieldCombo.ItemIndex < 0 then Exit;
if FOperatorCombo.ItemIndex < 0 then Exit;
// Find selected column
var Form := TORMSearchAdvForm(FPanel.Owner);
var SelectedColumn: TSearchAdvColumn := nil;
for var Column in Form.FSearchColumns do
begin
if Column.DisplayName = FFieldCombo.Text then
begin
SelectedColumn := Column;
Break;
end;
end;
if not Assigned(SelectedColumn) then Exit;
// Update FFilterInfo with current values
GetFilterInfo;
// Skip value validation for null checks
if (FFilterInfo.OperationType = fotIsNull) or
(FFilterInfo.OperationType = fotIsNotNull) then
begin
Result := True;
Exit;
end;
// Validate based on data type
case SelectedColumn.DataType of
tiString:
// String values are always valid, but ensure non-empty for operations needing a value
if FFilterInfo.OperationType in [fotContains, fotStartsWith, fotEndsWith, fotEqual, fotNotEqual] then
Result := FFilterInfo.Value1.ToString.Trim <> ''
else
Result := True;
tiInteger:
begin
var IntValue: Int64;
Result := TryStrToInt64(FFilterInfo.Value1.ToString, IntValue);
if FFilterInfo.OperationType = fotBetween then
begin
var IntValue2: Int64;
Result := Result and TryStrToInt64(FFilterInfo.Value2.ToString, IntValue2);
end;
end;
tiFloat, tiMoney:
begin
var FloatValue: Extended;
Result := TryStrToFloat(FFilterInfo.Value1.ToString, FloatValue);
if FFilterInfo.OperationType = fotBetween then
begin
var FloatValue2: Extended;
Result := Result and TryStrToFloat(FFilterInfo.Value2.ToString, FloatValue2);
end;
end;
tiDate, tiDateTime:
begin
Result := FFilterInfo.Value1.AsType<TDateTime> > 0;
if FFilterInfo.OperationType = fotBetween then
Result := Result and (FFilterInfo.Value2.AsType<TDateTime> > 0);
end;
tiBoolean:
begin
var BoolStr := LowerCase(FFilterInfo.Value1.ToString);
Result := (BoolStr = 'true') or (BoolStr = 'false') or
(BoolStr = '1') or (BoolStr = '0') or
(BoolStr = 'yes') or (BoolStr = 'no');
if FFilterInfo.OperationType = fotBetween then
begin
var BoolStr2 := LowerCase(FFilterInfo.Value2.ToString);
Result := Result and ((BoolStr2 = 'true') or (BoolStr2 = 'false') or
(BoolStr2 = '1') or (BoolStr2 = '0') or
(BoolStr2 = 'yes') or (BoolStr2 = 'no'));
end;
end;
else
Result := False;
end;
end;
3. Unsafe Casting of AOwner to TORMSearchAdvForm in TFilterPanel
Issue:
The constructor of TFilterPanel casts AOwner (which is of type TComponent) directly to TORMSearchAdvForm without ensuring that AOwner is indeed an instance of TORMSearchAdvForm. This can lead to access violations if AOwner is not the expected type.
Enhance the constructor to safely cast AOwner to TORMSearchAdvForm using the as operator and raise an exception if the cast fails. Alternatively, modify the constructor to explicitly require a reference to TFilterManager.
Option 1: Safe Casting and Validation
constructor TFilterPanel.Create(AOwner: TComponent; ALevel: Integer;
AParent: TFilterPanel = nil; AIsGroup: Boolean = False);
var
SearchForm: TORMSearchAdvForm;
begin
inherited Create;
if not (AOwner is TORMSearchAdvForm) then
raise Exception.Create('Owner must be an instance of TORMSearchAdvForm');
SearchForm := TORMSearchAdvForm(AOwner);
FId := SearchForm.FilterManager.CreateUniqueId;
FLevel := ALevel;
FParentGroup := AParent;
FIsGroup := AIsGroup;
FIsExpanded := True;
CreateGUID(FFilterID);
if FIsGroup then
FChildFilters := TObjectList<TFilterPanel>.Create(False)
else
FChildFilters := nil;
SetupVisuals(AOwner);
end;
Option 2: Passing TFilterManager Directly
Modify the constructor to accept a TFilterManager instance instead of relying on AOwner.
constructor TFilterPanel.Create(AOwner: TComponent; ALevel: Integer;
AParent: TFilterPanel = nil; AIsGroup: Boolean = False;
AFilterManager: TFilterManager);
begin
inherited Create;
if not Assigned(AFilterManager) then
raise Exception.Create('AFilterManager must be assigned');
FId := AFilterManager.CreateUniqueId;
FLevel := ALevel;
FParentGroup := AParent;
FIsGroup := AIsGroup;
FIsExpanded := True;
CreateGUID(FFilterID);
if FIsGroup then
FChildFilters := TObjectList<TFilterPanel>.Create(False)
else
FChildFilters := nil;
SetupVisuals(AOwner);
end;
Update Calls to the Constructor:
Ensure all instantiations of TFilterPanel pass the TFilterManager:
// Example in TFilterManager.CreateFilterGroup
Result := TFilterPanel.Create(AOwner, Parent.Level + 1, Parent, True, Self);
// Similarly in TFilterManager.CreateFilter
Result := TFilterPanel.Create(AOwner, Parent.Level + 1, Parent, False, Self);
4. Potential Undefined Functions: QuoteNum and QuoteEsc
Issue:
The functions QuoteNum and QuoteEsc are used within the TFilterPanel class but are not defined within the provided unit. If these functions are not defined in any of the included units (orm_utils, pixel_utils, etc.), this will lead to compiler errors.
Location:
function TFilterPanel.FormatValue(const Value: Variant; ADataType: TORMFormatType): string;
begin
// ...
tiMoney:
Result := QuoteNum(GetMoney(Value))
// ...
function TFilterPanel.GetFilterCondition: string;
begin
// ...
Result := Format('%s LIKE ''%%%s%%''', [SelectedColumn.FieldName, QuoteEsc(FValueEdit.Text)]);
// ...
end;
Correction:
Option 1: Define QuoteNum and QuoteEsc Locally
If orm_utils or other utility units do not provide these functions, define them within the orm_advsearch unit.
function QuoteNum(const Num: Double): string;
begin
Result := FormatFloat('0.00', Num);
end;
function QuoteEsc(const Str: string): string;
begin
Result := StringReplace(Str, '''', '''''', [rfReplaceAll]);
end;
Option 2: Replace with Standard Delphi Functions
Alternatively, replace QuoteNum and QuoteEsc with standard Delphi functions like QuotedStr and proper formatting.
Replace QuoteNum with FormatFloat:
function TFilterPanel.QuoteValue(const Value: Variant; ADataType: TORMFormatType): string;
begin
if Value.Trim = '' then
Exit('NULL');
case ADataType of
tiString:
Result := QuotedStr(Value);
tiInteger, tiFloat, tiMoney:
begin
if ADataType = tiMoney then
Result := FormatFloat('0.00', Value)
else
Result := FormatFloat('0.00', Value);
end;
tiDate:
Result := QuotedStr(FormatDateTime('yyyy-mm-dd', FDateValue.Date));
tiDateTime:
Result := QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', FDateValue.Date));
tiBoolean:
begin
var BoolStr := LowerCase(Value);
if (BoolStr = 'true') or (BoolStr = '1') or (BoolStr = 'yes') then
Result := 'TRUE'
else
Result := 'FALSE';
end;
else
Result := QuotedStr(Value);
end;
end;
Replace QuoteEsc with a Local Function or QuotedStr:
function QuoteEsc(const Str: string): string;
begin
Result := StringReplace(Str, '''', '''''', [rfReplaceAll]);
end;
Add this function to the implementation section:
function QuoteEsc(const Str: string): string;
begin
Result := StringReplace(Str, '''', '''''', [rfReplaceAll]);
end;
5. Accessing FilterManager in TFilterPanel After Refactoring Constructor
Issue:
After modifying the TFilterPanel constructor to accept a TFilterManager, ensure that the FilterManager is properly accessed within the class. Previously, it accessed via TORMSearchAdvForm(AOwner).FilterManager, which might no longer be valid.
Correction:
If you refactored the constructor to accept TFilterManager, store it in a private field.
Add Private Field:
type
TFilterPanel = class
private
// Existing fields...
FFilterManagerRef: TFilterManager; // New field
// ...
public
constructor Create(AOwner: TComponent; ALevel: Integer;
AParent: TFilterPanel = nil; AIsGroup: Boolean = False;
AFilterManager: TFilterManager); reintroduce;
// ...
end;
Update the Constructor:
constructor TFilterPanel.Create(AOwner: TComponent; ALevel: Integer;
AParent: TFilterPanel = nil; AIsGroup: Boolean = False;
AFilterManager: TFilterManager);
begin
inherited Create;
if not Assigned(AFilterManager) then
raise Exception.Create('AFilterManager must be assigned');
FFilterManagerRef := AFilterManager;
FId := FFilterManagerRef.CreateUniqueId;
FLevel := ALevel;
FParentGroup := AParent;
FIsGroup := AIsGroup;
FIsExpanded := True;
CreateGUID(FFilterID);
if FIsGroup then
FChildFilters := TObjectList<TFilterPanel>.Create(False)
else
FChildFilters := nil;
SetupVisuals(AOwner);
end;
Replace All References to FilterManager:
Ensure that throughout the TFilterPanel class, you use FFilterManagerRef instead of accessing it via the owner.
For example, in TFilterPanel.AddChild:
procedure TFilterPanel.AddChild(Child: TFilterPanel);
begin
if not FIsGroup then Exit;
Child.ParentGroup := Self;
FFilterManagerRef.RootFilters.Add(Child);
if Assigned(FContentPanel) then
Child.Panel.Parent := FContentPanel;
FFilterManagerRef.UpdateLayout;
end;
Ensure similar updates are made wherever FilterManager is accessed.
6. Missing Initialization of FFilterManager and Other Components in TORMSearchAdvForm
Issue:
The constructor of TORMSearchAdvForm initializes several components, but the TFilterManager instance's lifecycle and interactions might not be fully handled, especially during form destruction.
Ensure that all dynamically created objects are properly freed and that the form's components are correctly owned to avoid memory leaks.
Ensure Proper Ownership:
If FFilterManager or other objects are responsible for managing child components, verify that they correctly assign ownership.
Example:
constructor TFilterManager.Create(AForm: TORMSearchAdvForm);
begin
inherited Create;
FForm := AForm;
FRootFilters := TObjectList<TFilterPanel>.Create(True); // Owns the filters
FNextId := 1;
FDragPanel := nil;
end;
destructor TFilterManager.Destroy;
begin
FRootFilters.Free;
inherited;
end;
Ensure that TFilterPanel instances are owned by FRootFilters or their respective parent groups.
7. Potential Issues with Event Handlers in TFilterPanel
Issue:
The event handlers, such as HandleDragOver and HandleDragDrop, assume certain states and may not handle all edge cases, potentially leading to unexpected behavior during drag-and-drop operations.
Correction:
Ensure Proper Event Assignment:
Verify that all relevant events are assigned correctly and that handlers are robust against invalid states.
Enhance Drag-and-Drop Validation:
Add additional checks to prevent invalid drops, such as dropping a filter into itself or creating circular references.
Example Enhancement in HandleDragDrop:
procedure TFilterPanel.HandleDragDrop(Sender, Source: TObject; X, Y: Integer);
var
SourcePanel: TFilterPanel;
DropPos: TPoint;
begin
if not (Source is TscGPPanel) then Exit;
SourcePanel := TORMSearchAdvForm(FPanel.Owner).FilterManager.FDragPanel;
if not Assigned(SourcePanel) or (SourcePanel = Self) then Exit;
// Prevent dropping a parent into a child or dropping into itself
if FFilterManagerRef.IsFilterInHierarchy(SourcePanel, Self) then Exit;
DropPos := Point(X, Y);
FFilterManagerRef.MoveFilter(SourcePanel, Self, DropPos);
end;
Ensure Safe Dragging:
Modify IsFilterInHierarchy to prevent circular references effectively.
function TFilterManager.IsFilterInHierarchy(Parent, Child: TFilterPanel): Boolean;
var
Current: TFilterPanel;
begin
Result := False;
if not Assigned(Parent) or not Assigned(Child) then Exit;
Current := Child;
while Assigned(Current) do
begin
if Current = Parent then
Exit(True);
Current := Current.ParentGroup;
end;
end;
8. Handling Empty or Null Queries Gracefully in TORMSearchAdvForm.LoadData
Issue:
If the base query combined with filters results in no records, the application should handle this gracefully without causing runtime errors or displaying improper data.
Correction:
Modify the LoadData method to check if the query returned any records and handle the grid accordingly.
Updated LoadData:
procedure TORMSearchAdvForm.LoadData;
begin
if not Assigned(FQuery) then
FQuery := TUniQuery.Create(nil);
Screen.Cursor := crHourGlass;
try
FQuery.Close;
FQuery.SQL.Text := GetFilteredSQL;
FQuery.Connection := FConnection;
FQuery.Open;
if FQuery.RecordCount > 0 then
begin
UpdateGridData;
UpdateControlStates;
end
else
begin
// Clear grid and notify user
SearchGrid.BeginUpdate;
try
SearchGrid.RowCount := SearchGrid.FixedRows;
SearchGrid.ClearRows(SearchGrid.FixedRows, SearchGrid.RowCount - 1);
finally
SearchGrid.EndUpdate;
end;
MessageDlg('No records found for the applied filters.', mtInformation, [mbOK], 0);
UpdateControlStates;
end;
finally
Screen.Cursor := crDefault;
end;
end;
9. Ensuring Proper Event Handler Cleanup in TFilterPanel.Destroy
Issue:
If event handlers are dynamically assigned to controls within TFilterPanel, they should be properly cleaned up to prevent dangling references which can lead to access violations.
Correction:
In the destructor of TFilterPanel, ensure that all event handlers are unset before freeing the controls.
Updated Destructor:
destructor TFilterPanel.Destroy;
begin
if Assigned(FChildFilters) then
FreeAndNil(FChildFilters);
if Assigned(FPanel) then
begin
// Unassign event handlers
FPanel.OnDragOver := nil;
FPanel.OnDragDrop := nil;
FPanel.Parent := nil;
FreeAndNil(FPanel);
end;
inherited;
end;
Ensure that all dynamically created controls have their event handlers unassigned in their respective destructors.
10. Additional Recommendations
Use Enumerations Instead of Strings for Operators:
Replace string comparisons for operators with enumerated types to reduce errors due to typos.
Consistent Naming Conventions:
Ensure consistent naming for variables and methods to improve code readability.
Error Handling Enhancements:
Add more comprehensive error handling throughout the code to manage unexpected states gracefully.
Code Documentation:
Add comments and documentation to complex methods and classes to aid future maintenance.
Unit Testing:
Implement unit tests for critical components like TFilterManager and TFilterPanel to ensure reliability.
Final Corrected Unit
Below is the corrected version of your unit incorporating all the fixes mentioned above. Note that I've included only the modified sections for brevity. Ensure you integrate these changes appropriately into your existing codebase.
unit orm_advsearch;
interface
uses
// ... [existing uses]
type
TFilterManager = class;
// ... [other type declarations]
TFilterPanel = class
private
FFilterManagerRef: TFilterManager; // New field
// ... [other fields]
public
constructor Create(AOwner: TComponent; ALevel: Integer;
AParent: TFilterPanel = nil; AIsGroup: Boolean = False;
AFilterManager: TFilterManager); reintroduce;
// ... [other methods]
end;
// ... [other type declarations]
implementation
// Define QuoteEsc if not defined in util units
function QuoteEsc(const Str: string): string;
begin
Result := StringReplace(Str, '''', '''''', [rfReplaceAll]);
end;
// Optionally define QuoteNum or use standard functions as per Correction 4
{ TFilterPanel Implementation }
constructor TFilterPanel.Create(AOwner: TComponent; ALevel: Integer;
AParent: TFilterPanel = nil; AIsGroup: Boolean = False;
AFilterManager: TFilterManager);
begin
inherited Create;
if not Assigned(AFilterManager) then
raise Exception.Create('AFilterManager must be assigned');
FFilterManagerRef := AFilterManager;
FId := FFilterManagerRef.CreateUniqueId;
FLevel := ALevel;
FParentGroup := AParent;
FIsGroup := AIsGroup;
FIsExpanded := True;
CreateGUID(FFilterID);
if FIsGroup then
FChildFilters := TObjectList<TFilterPanel>.Create(False)
else
FChildFilters := nil;
SetupVisuals(AOwner);
end;
destructor TFilterPanel.Destroy;
begin
if Assigned(FChildFilters) then
FreeAndNil(FChildFilters);
if Assigned(FPanel) then
begin
// Unassign event handlers
FPanel.OnDragOver := nil;
FPanel.OnDragDrop := nil;
FPanel.Parent := nil;
FreeAndNil(FPanel);
end;
inherited;
end;
// ... [other method implementations]
function TFilterPanel.GetFilterInfo: TFilterValueInfo;
begin
// Update values before returning
if FFilterInfo.DataType in [tiDate, tiDateTime] then
begin
if FDateValue.Visible then
FFilterInfo.Value1 := FDateValue.Date;
if (FFilterInfo.OperationType = fotBetween) and FDateValue2.Visible then
FFilterInfo.Value2 := FDateValue2.Date;
end
else
begin
if FValueEdit.Visible then
FFilterInfo.Value1 := FValueEdit.Text;
if (FFilterInfo.OperationType = fotBetween) and FValueEdit2.Visible then
FFilterInfo.Value2 := FValueEdit2.Text;
end;
Result := FFilterInfo;
end;
procedure TFilterPanel.OperatorComboChange(Sender: TObject);
begin
if FOperatorCombo.Text =
'Equals' then FFilterInfo.OperationType := fotEqual
else if FOperatorCombo.Text =
'Not Equals' then FFilterInfo.OperationType := fotNotEqual
else if FOperatorCombo.Text =
'Greater Than'then FFilterInfo.OperationType := fotGreaterThan
else if FOperatorCombo.Text =
'Less Than' then FFilterInfo.OperationType := fotLessThan
else if FOperatorCombo.Text =
'Greater or Equal' then FFilterInfo.OperationType := fotGreaterEqual
else if FOperatorCombo.Text =
'Less or Equal' then FFilterInfo.OperationType := fotLessEqual
else if FOperatorCombo.Text =
'Between' then FFilterInfo.OperationType := fotBetween
else if FOperatorCombo.Text =
'Contains' then FFilterInfo.OperationType := fotContains
else if FOperatorCombo.Text =
'Starts With' then FFilterInfo.OperationType := fotStartsWith
else if FOperatorCombo.Text =
'Ends With' then FFilterInfo.OperationType := fotEndsWith
else if FOperatorCombo.Text =
'Is Empty' then FFilterInfo.OperationType := fotIsNull
else if FOperatorCombo.Text =
'Is Not Empty' then FFilterInfo.OperationType := fotIsNotNull;
UpdateValueControls;
end;
function TFilterPanel.ValidateFilter: Boolean;
begin
Result := False;
if FIsGroup then Exit(True);
// Basic validation
if FFieldCombo.ItemIndex < 0 then Exit;
if FOperatorCombo.ItemIndex < 0 then Exit;
// Find selected column
var Form := TORMSearchAdvForm(FPanel.Owner);
var SelectedColumn: TSearchAdvColumn := nil;
for var Column in Form.FSearchColumns do
begin
if Column.DisplayName = FFieldCombo.Text then
begin
SelectedColumn := Column;
Break;
end;
end;
if not Assigned(SelectedColumn) then Exit;
// Update FFilterInfo with current values
GetFilterInfo;
// Skip value validation for null checks
if (FFilterInfo.OperationType = fotIsNull) or
(FFilterInfo.OperationType = fotIsNotNull) then
begin
Result := True;
Exit;
end;
// Validate based on data type
case SelectedColumn.DataType of
tiString:
// String values are always valid, but ensure non-empty for operations needing a value
if FFilterInfo.OperationType in [fotContains, fotStartsWith, fotEndsWith, fotEqual, fotNotEqual] then
Result := FFilterInfo.Value1.ToString.Trim <> ''
else
Result := True;
tiInteger:
begin
var IntValue: Int64;
Result := TryStrToInt64(FFilterInfo.Value1.ToString, IntValue);
if FFilterInfo.OperationType = fotBetween then
begin
var IntValue2: Int64;
Result := Result and TryStrToInt64(FFilterInfo.Value2.ToString, IntValue2);
end;
end;
tiFloat, tiMoney:
begin
var FloatValue: Extended;
Result := TryStrToFloat(FFilterInfo.Value1.ToString, FloatValue);
if FFilterInfo.OperationType = fotBetween then
begin
var FloatValue2: Extended;
Result := Result and TryStrToFloat(FFilterInfo.Value2.ToString, FloatValue2);
end;
end;
tiDate, tiDateTime:
begin
Result := FFilterInfo.Value1.AsType<TDateTime> > 0;
if FFilterInfo.OperationType = fotBetween then
Result := Result and (FFilterInfo.Value2.AsType<TDateTime> > 0);
end;
tiBoolean:
begin
var BoolStr := LowerCase(FFilterInfo.Value1.ToString);
Result := (BoolStr = 'true') or (BoolStr = 'false') or
(BoolStr = '1') or (BoolStr = '0') or
(BoolStr = 'yes') or (BoolStr = 'no');
if FFilterInfo.OperationType = fotBetween then
begin
var BoolStr2 := LowerCase(FFilterInfo.Value2.ToString);
Result := Result and ((BoolStr2 = 'true') or (BoolStr2 = 'false') or
(BoolStr2 = '1') or (BoolStr2 = '0') or
(BoolStr2 = 'yes') or (BoolStr2 = 'no'));
end;
end;
else
Result := False;
end;
end;
Conclusion
By addressing the issues outlined above, your Delphi unit orm_advsearch should function more reliably and handle advanced search operations with greater robustness. Ensure that all dependencies, such as oom_utils, pixel_utils, and other third-party components, are correctly integrated and provide the necessary functions used within this unit.
Additionally, consider implementing comprehensive testing to validate the functionality of the search and filter mechanisms, especially after making these changes.
If you encounter further issues or require additional assistance with specific parts of the code, feel free to ask!