'Using working fileupload code inside a form with formki api

I have my form using formik. and I want to use the file upload logic in my form which is shown in the sandbox here.

Quick Description of what's in sandbox:

User uploads a file, and based on the # of files, they will see a datatable rows and answer some questions by editing that row using edit button and then saving their response using checkmark button.

Right now, when a user hits Save button, it prints in the console log the values of what user has selected as an array of object.

I don't want to have this additional Save button in my form and want to send these values when a user hits the Submit button of my form along with other values.

I was playing with my sandbox code by putting it at the location in my form where {uploadDocumentSection} is mentioned in my code below. However, I'm unable to get the data from the dynamicData variable which is storing the responses from the user.

Is it possible to achieve what I'm looking for?

return (
        <div>
            <style jsx>{`
            text-align: center;
            padding: 5px;
            #formEdwDiv {
                padding: 20px;
            }
        `}
            </style>
            <div id="formEdwDiv">
                <Growl ref={growl}/>
                <Form className="form-column-3">
                <div className="datarequest-form">                    
                    
                    <div className="form-field field-full-width">
                        <label className="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-animated custom-label">Title <span className="astrick">*</span></label>
                        <CustomTextField name="title" type="text"/>
                    </div>
                    <div className="form-field field-full-width">
                    <label className="MuiFormLabel-root MuiInputLabel-root MuiInputLabel-animated custom-label">Description <span className="astrick">*</span></label>                        
                        <CustomTextAreaField name = "description" type ="text" />
                        {touched.description && errors.description && <Message severity="error" text={errors.description}/>}
                    </div>
                  
                 </div>

                   {uploadDocumentSection}
                   <div className="btn-group-right">
                        <Button size="large" variant="contained" color="primary" id="edw-submit"
                                type="submit">Submit</Button>
                        <Button size="large" variant="contained" color="primary" onClick={handleReset}
                                style={{marginLeft: '5px'}} type="button">Reset</Button>
                        <Button size="large" variant="contained" color="primary" onClick={props.onCancel}
                                style={{marginLeft: '5px'}} type="button">Cancel</Button>
                    </div>
                </Form>
            </div>
        </div>
    )

};

export const RequestEnhancedForm = withFormik(
    
    
    
    {

        
    mapPropsToValues: props => {

              
        
        return {
            requestId: props.dataRequest && props.dataRequest.requestId || '',
            title: props.dataRequest && props.dataRequest.title || '',
           
        }
    },
    validationSchema:validationSchema,
    handleSubmit(values, {props, resetForm, setErrors, setSubmitting}) {
        console.log("submit data request form....")
        props.handleSubmit(values)
        setSubmitting(false)
    },
    setFieldValue(field, value, shouldVal) {
        console.log('In setFieldValue')
    },

    displayName: 'Data Request Form',
})(DataRequestForm)

Here is my code from Codesandbox if needed:

const answers = [
  { label: "Yes", value: "YES" },
  { label: "No", value: "NO" }
];

export const FileUploadDemo = () => {
  const toast = useRef(null);
  const fileUploadRef = useRef(null);
  const [dynamicData, setDynamicData] = useState([]);

  const getAnswerLabel = (answer) => {
    switch (answer) {
      case "YES":
        return "Yes";

      case "NO":
        return "No";

      default:
        return "NA";
    }
  };

  const onRowEditComplete1 = (e) => {
    console.log("Testing e");
    console.log(e);
    let _dynamicData = [...dynamicData];
    let { newData, index } = e;

    _dynamicData[index] = newData;

    setDynamicData(_dynamicData);
  };

  const textEditor = (options) => {
    return (
      <InputText
        type="text"
        value={options.value}
        onChange={(e) => options.editorCallback(e.target.value)}
      />
    );
  };
  const answerEditor = (options) => {
    return (
      <Dropdown
        value={options.value}
        options={answers}
        optionLabel="label"
        optionValue="value"
        onChange={(e) => options.editorCallback(e.value)}
        placeholder="Select an answer"
        itemTemplate={(option) => {
          return <span className={`product-badge`}>{option.label}</span>;
        }}
      />
    );
  };

  const answer1BodyTemplate = (rowData) => {
    return getAnswerLabel(rowData.answer1);
  };

  const answer2BodyTemplate = (rowData) => {
    return getAnswerLabel(rowData.answer2);
  };

  const onUpload = (e) => {
    // toast.current.show({
    //   severity: "info",
    //   summary: "Success",
    //   detail: "File Uploaded"
    // });
    console.log("File Upload event e");
    console.log(e);
    const newData = e.files.map((file) => ({
      filename: file.name,
      answer1: null,
      answer2: null,
      description: ""
    }));
    setDynamicData([...dynamicData, ...newData]);
  };

  return (
    <div>
      <Tooltip target=".custom-choose-btn" content="Choose" position="bottom" />
      <Tooltip target=".custom-upload-btn" content="Upload" position="bottom" />
      <Tooltip target=".custom-cancel-btn" content="Clear" position="bottom" />

      <div className="card">
        <h5>Advanced</h5>
        <FileUpload
          name="demo[]"
          url="https://primefaces.org/primereact/showcase/upload.php"
          onUpload={onUpload}
          customUpload
          uploadHandler={onUpload}
          multiple
          accept="image/*"
          maxFileSize={1000000}
          emptyTemplate={
            <p className="m-0">Drag and drop files to here to upload.</p>
          }
        />
      </div>

      <div className="datatable-editing-demo">
        {/* <Toast ref={toast} /> */}

        <div className="card p-fluid">
          <h5>Row Editing</h5>
          <DataTable
            value={dynamicData}
            editMode="row"
            dataKey="id"
            onRowEditComplete={onRowEditComplete1}
            responsiveLayout="scroll"
          >
            <Column
              field="filename"
              header="Filename"
              editor={(options) => textEditor(options)}
              style={{ width: "20%" }}
            ></Column>
            <Column
              field="answer1"
              header="Q1"
              body={answer1BodyTemplate}
              editor={(options) => answerEditor(options)}
              style={{ width: "20%" }}
            ></Column>
            <Column
              field="answer2"
              header="Q2"
              body={answer2BodyTemplate}
              editor={(options) => answerEditor(options)}
              style={{ width: "20%" }}
            ></Column>
            <Column
              field="description"
              header="Description"
              editor={(options) => textEditor(options)}
              style={{ width: "20%" }}
            ></Column>
            <Column
              rowEditor
              headerStyle={{ width: "10%", minWidth: "8rem" }}
              bodyStyle={{ textAlign: "center" }}
            ></Column>
          </DataTable>
        </div>
      </div>
      <Button label="Save" onClick={() => console.log(dynamicData)} />
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<FileUploadDemo />, rootElement);


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source