Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

Allow to create a company from its autocomplete input when creating a contact.

Matthieu Hochlander31bf13547c06
diff --git a/src/atomic-crm/contacts/ContactInputs.tsx b/src/atomic-crm/contacts/ContactInputs.tsx
index 72b9854f..60f0cf94 100644
--- a/src/atomic-crm/contacts/ContactInputs.tsx
+++ b/src/atomic-crm/contacts/ContactInputs.tsx
@@ -1,6 +1,6 @@
import { Separator } from "@/components/ui/separator";
import { useIsMobile } from "@/hooks/use-mobile";
-import { email, required } from "ra-core";
+import { email, required, useGetIdentity, useCreate, useNotify } from "ra-core";
import * as React from "react";
import { useFormContext } from "react-hook-form";
@@ -64,12 +64,42 @@ const ContactIdentityInputs = () => {
};
const ContactPositionInputs = () => {
+ const [create] = useCreate();
+ const { identity } = useGetIdentity();
+ const notify = useNotify();
+ const handleCreateCompany = async (name?: string) => {
+ if (!name) return;
+ try {
+ const newCompany = await create(
+ "companies",
+ {
+ data: {
+ name,
+ sales_id: identity?.id,
+ created_at: new Date().toISOString(),
+ },
+ },
+ { returnPromise: true },
+ );
+ return newCompany;
+ } catch {
+ notify("An error occurred while creating the company", {
+ type: "error",
+ });
+ }
+ };
+
return (
<div className="flex flex-col gap-4">
<h6 className="text-lg font-semibold">Position</h6>
<TextInput source="title" helperText={false} />
<ReferenceInput source="company_id" reference="companies">
- <AutocompleteInput optionText="name" helperText={false} />
+ <AutocompleteInput
+ optionText="name"
+ helperText={false}
+ onCreate={handleCreateCompany}
+ createItemLabel="Create %{item}"
+ />
</ReferenceInput>
</div>
);
diff --git a/src/components/admin/autocomplete-input.tsx b/src/components/admin/autocomplete-input.tsx
index 21c05769..edff9606 100644
--- a/src/components/admin/autocomplete-input.tsx
+++ b/src/components/admin/autocomplete-input.tsx
@@ -1,5 +1,5 @@
-
import * as React from "react";
+import { useCallback } from "react";
import { Check, ChevronsUpDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
@@ -33,10 +33,14 @@ import {
useEvent,
} from "ra-core";
import { InputHelperText } from "./input-helper-text";
-import { useCallback } from "react";
+import {
+ SupportCreateSuggestionOptions,
+ useSupportCreateSuggestion,
+} from "@/hooks/useSupportCreateSuggestion";
export const AutocompleteInput = (
props: Omit<InputProps, "source"> &
+ Omit<SupportCreateSuggestionOptions, "handleChange" | "filter"> &
Partial<Pick<InputProps, "source">> &
ChoicesProps & {
className?: string;
@@ -49,7 +53,17 @@ export const AutocompleteInput = (
| ((option: any | undefined) => React.ReactNode);
},
) => {
- const { filterToQuery = DefaultFilterToQuery, inputText } = props;
+ const {
+ filterToQuery = DefaultFilterToQuery,
+ inputText,
+ create,
+ createValue,
+ createLabel,
+ createHintValue,
+ createItemLabel,
+ onCreate,
+ optionText,
+ } = props;
const {
allChoices = [],
source,
@@ -99,92 +113,147 @@ export const AutocompleteInput = (
}
});
+ const handleChange = useCallback(
+ (choice: any) => {
+ if (field.value === getChoiceValue(choice) && !isRequired) {
+ field.onChange("");
+ setFilterValue("");
+ if (isFromReference) {
+ setFilters(filterToQuery(""));
+ }
+ setOpen(false);
+ return;
+ }
+ field.onChange(getChoiceValue(choice));
+ setOpen(false);
+ },
+ [
+ field.value,
+ field.onChange,
+ getChoiceValue,
+ isRequired,
+ setFilterValue,
+ isFromReference,
+ setFilters,
+ filterToQuery,
+ setOpen,
+ ],
+ );
+
+ const {
+ getCreateItem,
+ handleChange: handleChangeWithCreateSupport,
+ createElement,
+ getOptionDisabled,
+ } = useSupportCreateSuggestion({
+ create,
+ createLabel,
+ createValue,
+ createHintValue,
+ createItemLabel,
+ onCreate,
+ handleChange,
+ optionText,
+ filter: filterValue,
+ });
+
+ const createItem =
+ (create || onCreate) && (filterValue !== "" || createLabel)
+ ? getCreateItem(filterValue)
+ : null;
+ let finalChoices = allChoices;
+ if (createItem) {
+ finalChoices = [...finalChoices, createItem];
+ }
+
return (
- <FormField className={props.className} id={id} name={source}>
- {props.label !== false && (
- <FormLabel>
- <FieldTitle
- label={props.label}
- source={props.source ?? source}
- resource={resource}
- isRequired={isRequired}
- />
- </FormLabel>
- )}
- <FormControl>
- <Popover open={open} onOpenChange={handleOpenChange}>
- <PopoverTrigger asChild>
- <Button
- variant="outline"
- role="combobox"
- aria-expanded={open}
- className="w-full justify-between h-auto py-1.75 font-normal"
- >
- {selectedChoice ? (
- getInputText(selectedChoice)
- ) : (
- <span className="text-muted-foreground">{placeholder}</span>
- )}
- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-full p-0">
- {/* We handle the filtering ourselves */}
- <Command shouldFilter={!isFromReference}>
- <CommandInput
- placeholder="Search..."
- value={filterValue}
- onValueChange={(filter) => {
- setFilterValue(filter);
- // We don't want the ChoicesContext to filter the choices if the input
- // is not from a reference as it would also filter out the selected values
- if (isFromReference) {
- setFilters(filterToQuery(filter));
- }
- }}
- />
- <CommandEmpty>No matching item found.</CommandEmpty>
- <CommandGroup>
- {allChoices.map((choice) => (
- <CommandItem
- key={getChoiceValue(choice)}
- value={getChoiceValue(choice)}
- onSelect={() => {
- if (
- field.value === getChoiceValue(choice) &&
- !isRequired
- ) {
- field.onChange("");
- setFilterValue("");
- if (isFromReference) {
- setFilters(filterToQuery(""));
+ <>
+ <FormField className={props.className} id={id} name={source}>
+ {props.label !== false && (
+ <FormLabel>
+ <FieldTitle
+ label={props.label}
+ source={props.source ?? source}
+ resource={resource}
+ isRequired={isRequired}
+ />
+ </FormLabel>
+ )}
+ <FormControl>
+ <Popover open={open} onOpenChange={handleOpenChange}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ role="combobox"
+ aria-expanded={open}
+ className="w-full justify-between h-auto py-1.75 font-normal"
+ >
+ {selectedChoice ? (
+ getInputText(selectedChoice)
+ ) : (
+ <span className="text-muted-foreground">{placeholder}</span>
+ )}
+ <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-full p-0">
+ {/* We handle the filtering ourselves */}
+ <Command shouldFilter={!isFromReference}>
+ <CommandInput
+ placeholder="Search..."
+ value={filterValue}
+ onValueChange={(filter) => {
+ setFilterValue(filter);
+ // We don't want the ChoicesContext to filter the choices if the input
+ // is not from a reference as it would also filter out the selected values
+ if (isFromReference) {
+ setFilters(filterToQuery(filter));
+ }
+ }}
+ />
+ <CommandEmpty>No matching item found.</CommandEmpty>
+ <CommandGroup>
+ {finalChoices.map((choice) => {
+ const isCreateItem =
+ !!createItem && choice?.id === createItem.id;
+ const disabled = getOptionDisabled(choice);
+
+ return (
+ <CommandItem
+ key={getChoiceValue(choice)}
+ value={
+ isCreateItem
+ ? // if it's the create option, include the filter value so it is shown in the command input
+ // characters before and after the filter value are required
+ // to show the option when the filter value starts or ends with a space
+ `?${filterValue}?`
+ : getChoiceValue(choice)
}
- setOpen(false);
- return;
- }
- field.onChange(getChoiceValue(choice));
- setOpen(false);
- }}
- >
- <Check
- className={cn(
- "mr-2 h-4 w-4",
- field.value === getChoiceValue(choice)
- ? "opacity-100"
- : "opacity-0",
- )}
- />
- {getChoiceText(choice)}
- </CommandItem>
- ))}
- </CommandGroup>
- </Command>
- </PopoverContent>
- </Popover>
- </FormControl>
- <InputHelperText helperText={props.helperText} />
- <FormError />
- </FormField>
+ onSelect={() => handleChangeWithCreateSupport(choice)}
+ disabled={disabled}
+ >
+ <Check
+ className={cn(
+ "mr-2 h-4 w-4",
+ field.value === getChoiceValue(choice)
+ ? "opacity-100"
+ : "opacity-0",
+ )}
+ />
+ {getChoiceText(isCreateItem ? createItem : choice)}
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ </FormControl>
+ <InputHelperText helperText={props.helperText} />
+ <FormError />
+ </FormField>
+ {createElement}
+ </>
);
};