blue pink
blue pink

Reputation: 9

Mud Blazor datagrid filters for datetime column

Is there a way to turn off the toolbar of datepicker when it's displayed for simple filter mode in the data grid for the datetime column filter? Way to make it editable as well? Basically want to set the properties of datepicker.

Data grid's filter mode is set to Simple. When the data grid has template column, filter isn't showing up. How to make the filter work for template column? Thanks

Upvotes: 0

Views: 101

Answers (1)

Qiang Fu
Qiang Fu

Reputation: 8811

The <CellTemplate> can be placed in PropertyColumn instead of TemplateColumn to make filter available. As per you demand, built in filter datetime cannot change to a "editable" text format. But you could custom the filter to meet your requirment. (Just note that custom filter has to use the DataGridFilterMode.ColumnFilterMenu which is similar to simple mode.) Such as following:

<MudDataGrid Items="@employees" Filterable="true" SortMode="@SortMode.None" Groupable="false" FilterMode="DataGridFilterMode.ColumnFilterMenu">
    <Columns>
        <PropertyColumn Property="x => x.Name" />
        <PropertyColumn Property="x => x.date" >
            <FilterTemplate>
                <MudTextField @bind-Value="filterDate" Placeholder="Enter date" />
                <MudButton Color="@Color.Primary" OnClick="@(() => ClearFilterAsync(context))">Clear</MudButton>
                <MudButton Color="@Color.Primary" OnClick="@(() => ApplyFilterAsync(context))">Filter</MudButton>
            </FilterTemplate>
            <CellTemplate>
                @context.Item.date
            </CellTemplate>
        </PropertyColumn>
    </Columns>
</MudDataGrid>

@code {  
    public record Employee(string Name, DateTime date);
    public IEnumerable<Employee> employees;

    string filterDate = string.Empty;
    FilterDefinition<Employee> _filterDefinition;

    protected override void OnInitialized()
    {
        _filterDefinition = new FilterDefinition<Employee>
        {
            //The filtering logic
            FilterFunction = x =>
            {
                return x.date.ToString().Contains(filterDate);
            }
        };

        employees = new List<Employee>
        {
            new Employee("Sam" ,new DateTime(2024,11,2)),
            new Employee("Alicia",new DateTime(2024,11,3)),
            new Employee("Ira",new DateTime(2024,12,3)),
            new Employee("John",new DateTime(2024,12,4)),
        };
    }

    private async Task ApplyFilterAsync(FilterContext<Employee> context)
    {
        await context.Actions.ApplyFilterAsync(_filterDefinition);
    }

    private async Task ClearFilterAsync(FilterContext<Employee> context)
    {
        await context.Actions.ClearFilterAsync(_filterDefinition);
    }
}

enter image description here

Upvotes: 1

Related Questions