mirror of
https://github.com/ansible/awx.git
synced 2026-01-20 14:11:24 -03:30
Merge pull request #7821 from mabashian/7814-form-error
Handle form submission errors that may be deeply nested in the return object Reviewed-by: https://github.com/apps/softwarefactory-project-zuul
This commit is contained in:
commit
16ce7b4647
@ -2,6 +2,26 @@ import React, { useState, useEffect } from 'react';
|
||||
import { useFormikContext } from 'formik';
|
||||
import { Alert } from '@patternfly/react-core';
|
||||
|
||||
const findErrorStrings = (obj, messages = []) => {
|
||||
if (typeof obj === 'string') {
|
||||
messages.push(obj);
|
||||
} else if (typeof obj === 'object') {
|
||||
Object.keys(obj).forEach(key => {
|
||||
const value = obj[key];
|
||||
if (typeof value === 'string') {
|
||||
messages.push(value);
|
||||
} else if (Array.isArray(value)) {
|
||||
value.forEach(arrValue => {
|
||||
messages = findErrorStrings(arrValue, messages);
|
||||
});
|
||||
} else if (typeof value === 'object') {
|
||||
messages = findErrorStrings(value, messages);
|
||||
}
|
||||
});
|
||||
}
|
||||
return messages;
|
||||
};
|
||||
|
||||
function FormSubmitError({ error }) {
|
||||
const [errorMessage, setErrorMessage] = useState(null);
|
||||
const { setErrors } = useFormikContext();
|
||||
@ -18,14 +38,7 @@ function FormSubmitError({ error }) {
|
||||
const errorMessages = error.response.data;
|
||||
setErrors(errorMessages);
|
||||
|
||||
let messages = [];
|
||||
Object.values(error.response.data).forEach(value => {
|
||||
if (Array.isArray(value)) {
|
||||
messages = messages.concat(value);
|
||||
} else {
|
||||
messages.push(value);
|
||||
}
|
||||
});
|
||||
const messages = findErrorStrings(error.response.data);
|
||||
setErrorMessage(messages.length > 0 ? messages : null);
|
||||
} else {
|
||||
/* eslint-disable-next-line no-console */
|
||||
|
||||
@ -52,4 +52,30 @@ describe('<FormSubmitError>', () => {
|
||||
expect(global.console.error).toHaveBeenCalledWith(error);
|
||||
global.console = realConsole;
|
||||
});
|
||||
|
||||
test('should display error message if field error is nested', async () => {
|
||||
const error = {
|
||||
response: {
|
||||
data: {
|
||||
name: 'There was an error with name',
|
||||
inputs: {
|
||||
url: 'Error with url',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
let wrapper;
|
||||
await act(async () => {
|
||||
wrapper = mountWithContexts(
|
||||
<Formik>{() => <FormSubmitError error={error} />}</Formik>
|
||||
);
|
||||
});
|
||||
wrapper.update();
|
||||
expect(
|
||||
wrapper.find('Alert').contains(<div>There was an error with name</div>)
|
||||
).toEqual(true);
|
||||
expect(wrapper.find('Alert').contains(<div>Error with url</div>)).toEqual(
|
||||
true
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user