Skip to content

Commit

Permalink
Render form correctly when editing
Browse files Browse the repository at this point in the history
Render form correctly when editing

Display edited fields

Populate form fields

Render form correctly when editing
  • Loading branch information
saulipurhonen committed Jun 4, 2021
1 parent 246da81 commit bf28ce3
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -87,21 +87,18 @@ const useStyles = makeStyles(theme => ({
width: "95%",
},
},
"& h2, h3, h4": {
"& h2, h3, h4, h5, h6": {
margin: theme.spacing(1, 0),
},
<<<<<<< HEAD
=======
"& .MuiPaper-elevation2": {
paddingRight: theme.spacing(1),
"& .array": { margin: 0 },
"& h2, h3, h4": { margin: theme.spacing(1), width: "95%" },
"& h3, h4": { margin: theme.spacing(1) },
"& button": { margin: theme.spacing(0, 1) },
},
"& .MuiSelect-outlined": {
marginRight: 0,
},
>>>>>>> 4fe3185 (Form edit E2E tests)
},
},
}))
Expand Down
83 changes: 73 additions & 10 deletions src/components/NewDraftWizard/WizardForms/WizardJSONSchemaParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import AddIcon from "@material-ui/icons/Add"
import RemoveIcon from "@material-ui/icons/Remove"
import * as _ from "lodash"
import { useFieldArray, useFormContext } from "react-hook-form"
import { useSelector } from "react-redux"

/*
* Highlight style for required fields
Expand Down Expand Up @@ -99,7 +100,7 @@ const traverseValues = (object: any) => {
default: {
console.error(`
No initial value parsing support for type ${object["type"]} yet.
Pretty printed version of object with unsupported type:
${JSON.stringify(object, null, 2)}
`)
Expand Down Expand Up @@ -230,7 +231,7 @@ const traverseFields = (
default: {
console.error(`
No field parsing support for type ${object.type} yet.
Pretty printed version of object with unsupported type:
${JSON.stringify(object, null, 2)}
`)
Expand All @@ -251,6 +252,7 @@ type FormSectionProps = {
*/
const FormSection = (props: FormSectionProps) => {
const { name, label, level } = props

return (
<ConnectForm>
{({ errors }) => {
Expand Down Expand Up @@ -312,14 +314,66 @@ const FormOneOfField = ({
required?: any,
}) => {
const options = object.oneOf

// Get the fieldValue when rendering a saved/submitted form
// For e.g. obj.required is ["label", "url"] and nestedField is {id: "sth1", label: "sth2", url: "sth3"}
// Get object from state and set default values if child of oneOf field has values
// Fetching current object values from state rather than via getValues() method gets values on first call. The getValues method results in empty object on first call
const currentObject = useSelector(state => state.currentObject) || {}

const values = currentObject[path]
? currentObject
: currentObject[Object.keys(currentObject).filter(item => path.includes(item))] || {}

let fieldValue = ""

const flattenObject = (obj, prefix = "") =>
Object.keys(obj).reduce((acc, k) => {
const pre = prefix.length ? prefix + "." : ""
if (typeof obj[k] === "object") Object.assign(acc, flattenObject(obj[k], pre + k))
else acc[pre + k] = obj[k]
return acc
}, {})

if (Object.keys(values).length > 0) {
for (const item of path) {
if (values[item]) {
const itemValues = values[item]
const parentPath = Object.keys(itemValues) ? Object.keys(itemValues) : ""

// Match key from currentObject to option property.
// Field key can be deeply nested and therefore we need to have multiple cases for finding correct value.
if (isNaN(parentPath[0])) {
fieldValue = (options.find(option => option.properties[parentPath])
? // Eg. Sample > Sample Names > Sample Data Type
options.find(option => option.properties[parentPath])
: // Eg. Run > Run Type > Reference Alignment
options.find(
option => option.properties[Object.keys(flattenObject(itemValues))[0].split(".").slice(-1)[0]]
)
)?.title
} else {
// Eg. Experiment > Expected Base Call Table > Processing > Single Processing
if (typeof itemValues === "string") {
fieldValue = options.find(option => option.type === "string").title
}
// Eg. Experiment > Expected Base Call Table > Processing > Complex Processing
else {
const fieldKey = Object.keys(values[item][0])[0]
fieldValue = options.find(option => option.items?.properties[fieldKey]).title
}
}
}
}
}

// Eg. Study > Study Links
if (nestedField) {
for (let obj of options) {
obj.required.every(val => Object.keys(nestedField).includes(val)) ? (fieldValue = obj.title) : ""
for (let option of options) {
option.required.every(val => (Object.keys(nestedField).includes(val) ? (fieldValue = option.title) : ""))
}
}

const [field, setField] = useState(fieldValue)

const handleChange = event => setField(event.target.value)
Expand Down Expand Up @@ -528,7 +582,9 @@ const FormCheckBoxArray = ({ name, label, required, options }: FormSelectFieldPr
<strong>{label}</strong> - check from following options
</p>
<ConnectForm>
{({ register, errors }) => {
{({ register, errors, getValues }) => {
const values = getValues()[name]

const error = _.get(errors, name)
const { ref, ...rest } = register(name)

Expand All @@ -539,7 +595,15 @@ const FormCheckBoxArray = ({ name, label, required, options }: FormSelectFieldPr
<FormControlLabel
key={option}
control={
<Checkbox name={name} {...rest} inputRef={ref} value={option} color="primary" defaultValue="" />
<Checkbox
name={name}
{...rest}
inputRef={ref}
value={option}
checked={values && values?.includes(option) ? true : false}
color="primary"
defaultValue=""
/>
}
label={option}
/>
Expand Down Expand Up @@ -571,8 +635,6 @@ const FormArray = ({ object, path, required }: FormArrayProps) => {

const { fields, append, remove } = useFieldArray({ name })

const currentObject = useSelector(state => state.currentObject) || {}

return (
<div className="array" key={`${name}-array`}>
<Typography key={`${name}-header`} variant={`h${level}`}>
Expand All @@ -582,6 +644,7 @@ const FormArray = ({ object, path, required }: FormArrayProps) => {
const [lastPathItem] = path.slice(-1)
const pathWithoutLastItem = path.slice(0, -1)
const lastPathItemWithIndex = `${lastPathItem}[${index}]`

if (items.oneOf) {
const pathForThisIndex = [...pathWithoutLastItem, lastPathItemWithIndex]

Expand All @@ -599,7 +662,7 @@ const FormArray = ({ object, path, required }: FormArrayProps) => {
const properties = object.items.properties

return (
<div className="arrayRow" key={`${name}[${index}]`}>
<Box px={1} className="arrayRow" key={`${name}[${index}]`}>
<Paper elevation={2}>
{Object.keys(items).map(item => {
const pathForThisIndex = [...pathWithoutLastItem, lastPathItemWithIndex, item]
Expand All @@ -609,7 +672,7 @@ const FormArray = ({ object, path, required }: FormArrayProps) => {
<IconButton onClick={() => remove(index)}>
<RemoveIcon />
</IconButton>
</div>
</Box>
)
})}

Expand Down

0 comments on commit bf28ce3

Please sign in to comment.