Skip to content

(feat): Enable external form Submission #550

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 28 additions & 24 deletions src/components/sidebar/sidebar.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ interface SidebarProps {
onCancel: () => void;
handleClose: () => void;
hideFormCollapseToggle: () => void;
hideControls?: boolean;
}

const Sidebar: React.FC<SidebarProps> = ({
Expand All @@ -25,6 +26,7 @@ const Sidebar: React.FC<SidebarProps> = ({
onCancel,
handleClose,
hideFormCollapseToggle,
hideControls,
}) => {
const { t } = useTranslation();
const { pages, pagesWithErrors, activePages, evaluatedPagesVisibility } = usePageObserver();
Expand Down Expand Up @@ -53,32 +55,34 @@ const Sidebar: React.FC<SidebarProps> = ({
requestPage={requestPage}
/>
))}
{sessionMode !== 'view' && <hr className={styles.divider} />}
{sessionMode !== 'view' && !hideControls && <hr className={styles.divider} />}

<div className={styles.sideNavActions}>
{sessionMode !== 'view' && (
<Button className={styles.saveButton} disabled={isFormSubmitting} type="submit" size={responsiveSize}>
{isFormSubmitting ? (
<InlineLoading description={t('submitting', 'Submitting') + '...'} />
) : (
<span>{`${t('save', 'Save')}`}</span>
)}
{!hideControls && (
<div className={styles.sideNavActions}>
{sessionMode !== 'view' && (
<Button className={styles.saveButton} disabled={isFormSubmitting} type="submit" size={responsiveSize}>
{isFormSubmitting ? (
<InlineLoading description={t('submitting', 'Submitting') + '...'} />
) : (
<span>{`${t('save', 'Save')}`}</span>
)}
</Button>
)}
<Button
className={classNames(styles.closeButton, {
[styles.topMargin]: sessionMode === 'view',
})}
kind="tertiary"
onClick={() => {
onCancel?.();
handleClose?.();
hideFormCollapseToggle();
}}
size={responsiveSize}>
{sessionMode === 'view' ? t('close', 'Close') : t('cancel', 'Cancel')}
</Button>
)}
<Button
className={classNames(styles.closeButton, {
[styles.topMargin]: sessionMode === 'view',
})}
kind="tertiary"
onClick={() => {
onCancel?.();
handleClose?.();
hideFormCollapseToggle();
}}
size={responsiveSize}>
{sessionMode === 'view' ? t('close', 'Close') : t('cancel', 'Cancel')}
</Button>
</div>
</div>
)}
</div>
);
};
Expand Down
12 changes: 9 additions & 3 deletions src/form-engine.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import MarkdownWrapper from './components/inputs/markdown/markdown-wrapper.compo
import PatientBanner from './components/patient-banner/patient-banner.component';
import Sidebar from './components/sidebar/sidebar.component';
import styles from './form-engine.scss';
import { useExternalSubmitListener } from './hooks/useExternalSubmitListener';

interface FormEngineProps {
patientUUID: string;
Expand All @@ -33,6 +34,7 @@ interface FormEngineProps {
handleClose?: () => void;
handleConfirmQuestionDeletion?: (question: Readonly<FormField>) => Promise<void>;
markFormAsDirty?: (isDirty: boolean) => void;
hideControls?: boolean;
}

const FormEngine = ({
Expand All @@ -48,6 +50,7 @@ const FormEngine = ({
handleClose,
handleConfirmQuestionDeletion,
markFormAsDirty,
hideControls = false,
}: FormEngineProps) => {
const { t } = useTranslation();
const session = useSession();
Expand Down Expand Up @@ -107,11 +110,13 @@ const FormEngine = ({
markFormAsDirty?.(isFormDirty);
}, [isFormDirty]);

const handleSubmit = useCallback((e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const handleSubmit = useCallback((e?: React.FormEvent<HTMLFormElement>) => {
e?.preventDefault();
setIsSubmitting(true);
}, []);

useExternalSubmitListener(handleSubmit);

return (
<form ref={ref} noValidate className={classNames('cds--form', styles.form)} onSubmit={handleSubmit}>
{isLoadingPatient || isLoadingFormJson ? (
Expand Down Expand Up @@ -152,6 +157,7 @@ const FormEngine = ({
onCancel={onCancel}
handleClose={handleClose}
hideFormCollapseToggle={hideFormCollapseToggle}
hideControls={hideControls}
/>
)}
<div className={styles.formContentInner}>
Expand All @@ -167,7 +173,7 @@ const FormEngine = ({
setIsLoadingFormDependencies={setIsLoadingDependencies}
/>
</div>
{showBottomButtonSet && (
{showBottomButtonSet && !hideControls && (
<ButtonSet className={styles.minifiedButtons}>
<Button
kind="secondary"
Expand Down
57 changes: 57 additions & 0 deletions src/hooks/useExternalSubmitListener.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { useEffect } from 'react';
import { createGlobalStore, getGlobalStore, useStore } from '@openmrs/esm-framework';

interface SubmitEventDetail {
formUuid: string;
patientUuid: string;
action: string;
}

type FormSession = 'formUuid' | 'patientUuid';

type InternalSubmitHandler = () => void;

//State that holds the current formUuid and patientUuid.
createGlobalStore<Record<FormSession, string>>('rfe-FormSession', {
formUuid: '',
patientUuid: '',
});

const formSessionStore = getGlobalStore('rfe-FormSession');

/**
* useExternalSubmitListener
*
* A custom React hook that enables triggering form submission externally via a global custom event.
*
* This is particularly useful in environments where the FormEngine
* is embedded inside another application or UI shell, and you need to trigger submission from outside
* the form (e.g., from a toolbar button, modal footer, or iframe parent).
*
* The supplied `internalSubmitHandler` fires **only** when the event's `formUuid` and
* `patientUuid` match the values held in the global FormSession store.
*
* @param internalSubmitHandler - A function that triggers the form submission. This will be called when the event is received. *
* @example
* useExternalSubmitListener(() => handleSubmit());
*/

export function useExternalSubmitListener(internalSubmitHandler: InternalSubmitHandler) {
const { formUuid, patientUuid } = useStore(formSessionStore) as { formUuid: string; patientUuid: string };

useEffect(() => {
const handleSubmitWrapper = (event: Event) => {
const customEvent = event as CustomEvent<SubmitEventDetail>;
const detail = customEvent.detail;

if (detail?.formUuid === formUuid && detail?.patientUuid === patientUuid) {
internalSubmitHandler();
}
};

window.addEventListener('rfe-form-submit-action', handleSubmitWrapper);
return () => {
window.removeEventListener('rfe-form-submit-action', handleSubmitWrapper);
};
}, [internalSubmitHandler]);
}
Loading