How to pass a parameter to the service used in AutoCrud

Hi Vaadin community!

I have a question on AutoCrud.

AutoCrud is a great component to display and edit data. I use it like so:

<AutoCrud
        service={DocumentService}
        model={DocumentDtoModel}
        gridProps={{
          ...
        }}
        formProps={{
          ...
        }}
/>

Is it possible to somehow pass a parameter to the service mentioned in the AutoCrud component. For Grids, I do something like this:

const myParameter = useSignal<String>("");

const documentDataProvider = useGridDataProvider(
        async (pageable) => DocumentService.listDocuments(pageable, myParameter.value.valueOf()),
        // Providing the search term as a dependency will automatically
        // refresh the data provider when the search term changes
        [myParameter.value]
    );

    return (
            <Grid dataProvider={documentDataProvider}>
                <GridSortColumn path="name" />
                <GridSortColumn path="description" />
            </Grid>
    );

Can I do something similar in AutoCrud?

Why would I need this? I would like to show only specific items in the AutoCrud (e.g. all Documents belonging to a certain person in the overview of that person).

Thanks for your help!

On the server side, I see no other way than using the session to store the current parameter value, to be set via a service call.

On the client side, if that’s enough for you, you can play with the CrudService interface and inject a filter. As an example, I used a route parameter to filter users by username. I created users/{search}.tsx with this code:

export default function CrudView() {
  const { search } = useParams<{ search: string }>();
  const service: CrudService<User> = {
    list: (pageable: Pageable, filter: Filter | undefined) => UserCrudService.list(pageable, {
      "@type": "and",
      children: [
        {
          "@type": "propertyString",
          propertyId: 'username',
          filterValue: search,
          matcher: Matcher.CONTAINS,
        },
        filter,
      ],
    }),
    save: UserCrudService.save,
    delete: UserCrudService.delete,
  };

  return <AutoCrud service={service} model={UserModel} />;
}

The same technique should work to filter users by manager id, for example (although those filters operate as strings).
Code should be improved to only insert the AndFilter when the filter parameter has a value, but you get the idea.
Let me know if that works for you.

1 Like

Thanks! Defining the service in Typescript makes a whole lot of sense! I didn’t even consider it. I will give it a try, but looks like it is exactly what I need.