Dependent fields / Cascading lookups

Make a field's options depend on the value of another field, such as the cities of the selected country

A field's options can depend on the value of another field on the same form, such as a city that must be in the selected country. Use DependsOn() to declare a dependency on another field, and filter its options by the other field's value.

The example below registers countries and cities as resources, and adds a country and a city to the destination create page. The city field depends on the country, and the delegate in Where() filters the cities where the country matches the current country from the Destination model:

admin.AddEfCoreResource<Country>(resource => { /* ... */ });
admin.AddEfCoreResource<City>(resource => { /* ... */ });

admin.AddEfCoreResource<Destination>(resource =>
{
    resource.AllowCreate(create => create.Fields(fields =>
    {
        fields.Add(destination => destination.CountryId);

        fields.Add(destination => destination.CityId)
            .DependsOn(destination => destination.CountryId)
            .UseLookupSheetEditor(lookup =>
            {
                lookup.UseResource<City>(items => items.Where((city, destination) =>
                    city.CountryId == destination.CountryId));
            });
    }));
});

The Where() is called for each city and receives the city and the form's model. The expression must return true if you want to include the city in the lookup.

When a user changes the country, the city field's value will be reset and its options reloaded based on the new country. When no country is selected, the city field is disabled, and displays "Select Country first".

Choosing Japan in the country lookup enables the city lookup, whose sheet lists only Japan's cities, and Kyoto is chosen

DependsOn() works with every choice editor and lookup, on the create and edit pages, and in inline rows. To make a field depend on several fields, call DependsOn() once for each of them. A field can also depend on a field that depends on another, such as a neighborhood that depends on the city.

Depending on more than one field

A field must declare all the fields it depends on. Let's expand on the previous example and say that, when the user checked the RequiresAirport field, we only want to list the cities with airports.

fields.Add(destination => destination.CityId)
    .DependsOn(destination => destination.CountryId)
    .UseLookupSheetEditor(lookup =>
    {
        lookup.UseResource<City>(items => items.Where((city, destination) =>
            city.CountryId == destination.CountryId
            && (!destination.RequiresAirport || city.HasAirport)));
    });

This will work correctly on initial page load, but not once the user changes the country. The reason for this is that StellarAdmin performs an AJAX postback to refresh the list of cities and will only pass the current values for the fields on which you have explicitly declared a dependency.

The model passed to the Where() delegate (i.e. the destination parameter) will therefore contain a sparse instance with only the the property values for the fields that you explicitly declare a dependency on. All other properties will contain their default value. So, in the example above, HasAirport will always be false.

The solution to this is to ensure you declare all your field dependencies. The example below fixes this problem by adding a call to DependsOn(destination => destination.RequiresAirport).

fields.Add(destination => destination.CityId)
    .DependsOn(destination => destination.CountryId)
    .DependsOn(destination => destination.RequiresAirport)
    .UseLookupSheetEditor(lookup =>
    {
        lookup.UseResource<City>(items => items.Where((city, destination) =>
            city.CountryId == destination.CountryId
            && (!destination.RequiresAirport || city.HasAirport)));
    });

A field can only depend on an editable field of the same form.

Changing the text of a disabled dependent field

While a field it depends on has no value, a dependent field is disabled, and displays a text that asks for that value first, such as "Select Country first". To change this text, set EmptyText in the callback of DependsOn().

fields.Add(destination => destination.CityId)
    .DependsOn(destination => destination.CountryId, country =>
    {
        country.EmptyText = "Select a country to see its cities";
    })
    .UseLookupSheetEditor(/* ... */);

Loading dependent options from a service

The previous examples all used EF Core, so StellarAdmin knows how to load the lookup values from the referenced resource. However, when you want to load options from an external (or non-EF Core) service, you will have to supply the items for the lookup by calling UseItems on the lookup editor builder.

To access your model, you can use the UseItems() overload that takes the model as the first parameter of the delegate. The example below loads the cities of the selected country from a CityDirectory service:

using StellarAdmin.Resources.Editors;

fields.Add(destination => destination.CityId)
    .DependsOn(destination => destination.CountryId)
    .UseSelectEditor(select =>
    {
        select.UseItems(async (destination, services, cancellationToken) =>
        {
            var cities = await services.GetRequiredService<CityDirectory>()
                .ListAsync(destination.CountryId, cancellationToken);

            return cities
                .Select(city => new ChoiceItem(city.Id.ToString(), city.Name))
                .ToList();
        });
    });

For a lookup, derive the lookup source from LookupSource<TItem, TValue, TArgument>, where TArgument is the type of the value the search takes from the form.

using StellarAdmin.Resources.Editors;

public class CountryAirportSource(AirportClient client) : LookupSource<Airport, string, int>
{
    public override string GetValue(Airport airport) => airport.Code;

    public override string GetTitle(Airport airport) => airport.City;

    public override Task<IReadOnlyCollection<Airport>> FindAsync(
        IReadOnlyCollection<string> values,
        CancellationToken cancellationToken)
    {
        return client.FindAsync(values, cancellationToken);
    }

    public override async Task<LookupPage<Airport>> SearchAsync(
        int countryId,
        LookupQuery query,
        CancellationToken cancellationToken)
    {
        var airports = await client.SearchAsync(
            countryId, query.Term, query.Skip, query.Take + 1, cancellationToken);

        return new LookupPage<Airport>(
            airports.Take(query.Take).ToList(),
            airports.Count > query.Take);
    }
}

To pass the value, call UseSource() with an expression that reads it from the form's model:

fields.Add(guide => guide.HomeAirport)
    .DependsOn(guide => guide.CountryId)
    .UseLookupSheetEditor(lookup =>
    {
        lookup.UseSource<CountryAirportSource>(guide => guide.CountryId);
    });

The value must have the type of TArgument, or its nullable type. If the search needs several values, pass a record that holds them.

On this page