import React, { useCallback, useMemo } from "react"; import { Entity, EntityCollection, EntityReference, FieldProps } from "../../types"; import { useNavigationController, useReferenceDialog } from "../../hooks"; import { ReadOnlyFieldBinding } from "./ReadOnlyFieldBinding"; import { FieldHelperText, LabelWithIcon } from "../components"; import { ErrorView } from "../../components"; import { ReferencePreview } from "../../preview"; import { getIconForProperty, getReferenceFrom } from "../../util"; import { Button } from "@firecms/ui"; import { useClearRestoreValue } from "../useClearRestoreValue"; /** * Field that opens a reference selection dialog. * * This is one of the internal components that get mapped natively inside forms * and tables to the specified properties. * @group Form fields */ export function ReferenceFieldBinding>(props: FieldProps) { if (typeof props.property.path !== "string") { return } return ; } function ReferenceFieldBindingInternal>({ value, setValue, error, showError, isSubmitting, disabled, touched, autoFocus, property, includeDescription, context }: FieldProps) { if (!property.path) { throw new Error("Property path is required for ReferenceFieldBinding"); } useClearRestoreValue({ property, value, setValue }); const validValue = value && value.isEntityReference && value.isEntityReference(); const navigationController = useNavigationController(); const collection: EntityCollection | undefined = useMemo(() => { return property.path ? navigationController.getCollection(property.path) : undefined; }, [property.path]); if (!collection) { throw Error(`Couldn't find the corresponding collection for the path: ${property.path}`); } const onSingleEntitySelected = useCallback((e: Entity | null) => { setValue(e ? getReferenceFrom(e) : null); }, [setValue]); const referenceDialogController = useReferenceDialog({ multiselect: false, path: property.path, collection, onSingleEntitySelected, selectedEntityIds: validValue ? [value.id] : undefined, forceFilter: property.forceFilter } ); const onEntryClick = useCallback((e: React.SyntheticEvent) => { e.preventDefault(); referenceDialogController.open(); }, [referenceDialogController]); return ( <> {!collection && } {collection && <> {value && } {!value &&
} } ); }