Dynamic template logics frontend
1. Key Features
The provided code implements a dynamic form with various input fields, data fetching, validation, and submission functionality. The primary features include:
-
Dynamic Field Rendering: Based on
dynamicFields.fields, the form dynamically renders different types of input fields like text, date, number, dropdowns, image upload, and tables. Each field type is rendered using a specificrenderFieldfunction. -
Field Rendering: Specific rendering logic for different input types (
text,number,date,dropdown,table, etc.) is provided by dedicated functions likerenderTextField,renderDropdownField,renderNumberField, etc. -
Validation: A validation check is performed on each required field before submitting the form. If any required fields are empty, an error message is displayed.
-
Data Submission: On form submission, the form data is collected and sent to an API for updating tender details. The submission process includes validation, error handling, and updating the UI state.
-
Image Upload: The ability to upload an image and store its path in the form data.
-
Step Navigation: The code includes functionality to move between steps of a process (e.g., using
nextStep()and routing withrouter.replace()).
2. Key Functionalities
The essential operations in the code that contribute to its behavior include:
-
Rendering Dynamic Fields:
renderFielddecides which input field to render based on the type defined in thedynamicFields.fieldsarray (e.g.,renderTextField,renderDatePicker,renderDropdownField, etc.).- These render methods handle different types of inputs like text, number, date, image, dropdown, and table.
-
Field-Specific Handlers:
- For fields like numbers or text,
renderTextField,renderNumberField, and similar functions provide the necessary input components with associated validation messages. - For image fields,
uploadTheImagehandles file uploads and updates the state with the file path.
- For fields like numbers or text,
-
Data Validation:
- The
submitfunction validates the fields marked as required before sending the data. It collects any errors and prevents submission if validation fails.
- The
-
Submission and API Interaction:
- The
submitfunction assembles the form data (formDataEOI), validates it, and sends it to an API endpoint usingtenderService.updateTenderBySerialId(). - Upon successful submission, the form navigates to the next step (
nextStep()) and updates the procurement process (updateCqsProcurementProcess).
- The
-
Step Navigation:
- After successful submission, the app updates the URL to indicate the current step using
router.replace(), moving the user to the next step in the process.
- After successful submission, the app updates the URL to indicate the current step using
3. Data Fetching and Step Handling
-
Data Fetching:
- The
dynamicFieldsobject is expected to contain a list of fields for rendering, though the code does not explicitly show how this data is fetched. Presumably,dynamicFieldsis populated from an API or some external source. - When the form is submitted, the data in
formDataEOIis sent to an API to update the tender details. Thesubmitfunction sends a payload that includes the form data (formDataEOI) and astepvalue (set to3in this case).
- The
-
Step Handling:
- The flow of steps is managed using the
nextStep()function, which is called after successful submission. The app usesrouter.replace()to update the URL, passing thedraftIdandstepas query parameters, indicating that the user has moved to the next step in the process.
- The flow of steps is managed using the
-
Dynamic State Updates:
- The form data (
formDataEOI) is dynamically updated based on user interactions with the form fields. This data is used in the form submission process and also passed to other methods likeupdateCqsProcurementProcess. - The
setGenerateWordDocxfunction is used to accumulate a list of key-value pairs that could be used later (likely for generating a document). These pairs are added on the fly as the form data is processed.
- The form data (
-
Image Upload and Table Handling:
- For image fields, the
uploadTheImagefunction uploads the file and updatesformDataEOIwith the file path. - For table fields, the
renderTableFieldmethod ensures that the appropriate table rendering logic is invoked, and it also makes use of thehandleInputChangeTableto modify the table data dynamically.
submit Function
- For image fields, the
const submit = async () => { setIsSubmitting(true) const validationErrors: { [key: string]: string } = {}; console.log("submit funtion", dynamicFields) // Validate required fields dynamicFields.fields.forEach((field: any) => { const value = formDataEOI[field.column_name]; console.log(' dynamicFields value :::::', field) if (field.is_required && !formDataEOI[field.column_name]) { validationErrors[field.column_name] = `${field.display_name} is required.`; }
if (value != undefined) { const newValue = { [field.value_to_replace]: value }; console.log('newValue :::::', newValue) setGenerateWordDocx((prevState: any) => [...prevState, newValue]); } });
console.log("submit funtion inside", validationErrors)
if (Object.keys(validationErrors).length > 0) { setErrors(validationErrors); setIsSubmitting(false) return; } try { console.log('Form Data:', formDataEOI); // Prepare the data to send to the API const dataToSubmit = { serial_id: draftId, detailsEOI: formDataEOI, template_id_eoi: dynamicFields._id || null, step:3
}; const updatedTenderDetails = await tenderService.updateTenderBySerialId(dataToSubmit); console.log("EoI data>>>>", updatedTenderDetails) // const newValue = { [dynamicFields.value_to_replace]: value }; // setGenerateWordDocx((prevState: any) => [...prevState, newValue]); updateCqsProcurementProcess({ detailsEOI: formDataEOI }); router.replace(`/create-request?draft-id=${draftId}&step=3&type=${activityType}`); nextStep(); setIsSubmitting(false)
} catch (error) { console.error('Error during submission:', error); setIsSubmitting(false) } };In summary, the code facilitates dynamic form rendering, data validation, API submission, and step-based navigation, allowing users to interact with various types of fields and proceed through a multi-step process.