adding and removing inputs properly

This commit is contained in:
Alex Corey 2021-04-13 16:50:31 -04:00
parent 372c80ee44
commit e088c7385a
3 changed files with 93 additions and 2 deletions

View File

@ -0,0 +1,85 @@
import React, { useState } from 'react';
import { useField } from 'formik';
import { Checkbox, FormGroup, TextInput } from '@patternfly/react-core';
import styled from 'styled-components';
import Popover from '../Popover';
const InputWrapper = styled.span`
&& {
display: flex;
}
`;
function TextAndCheckboxField({
id,
label,
helperText,
isRequired,
isValid,
tooltip,
name,
type,
rows,
...rest
}) {
const [field, meta] = useField({ name });
const [fields, setFields] = useState(field.value.split('\n'));
let array = field.value.split('\n');
return (
<FormGroup
fieldId={id}
helperText={helperText}
helperTextInvalid={meta.error}
isRequired={isRequired}
validated={isValid ? 'default' : 'error'}
label={label}
labelIcon={<Popover content={tooltip} />}
>
{fields
.map((v, i) => (
<InputWrapper>
<Checkbox />
<TextInput
id={id}
isRequired={isRequired}
validated={isValid ? 'default' : 'error'}
value={v}
type={type}
onChange={value => {
if (value === '') {
setFields(fields.filter((f, index) => i !== index));
} else {
setFields(
fields.map((f, index) => {
if (i === index) {
return value;
}
return f;
})
);
}
}}
/>
</InputWrapper>
))
.concat(
<InputWrapper>
<Checkbox />
<TextInput
id={id}
isRequired={isRequired}
validated={isValid ? 'default' : 'error'}
value=""
type={type}
onChange={(value, event) => {
setFields([...fields, value]);
}}
/>
</InputWrapper>
)}
</FormGroup>
);
}
export default TextAndCheckboxField;

View File

@ -4,3 +4,4 @@ export { default as PasswordField } from './PasswordField';
export { default as PasswordInput } from './PasswordInput';
export { default as FormSubmitError } from './FormSubmitError';
export { default as ArrayTextField } from './ArrayTextField';
export { default as TextAndCheckboxField } from './TextAndCheckboxField';

View File

@ -10,7 +10,9 @@ import FormField, {
CheckboxField,
PasswordField,
FormSubmitError,
TextAndCheckboxField,
} from '../../../components/FormField';
import AnsibleSelect from '../../../components/AnsibleSelect';
import Popover from '../../../components/Popover';
import {
@ -75,7 +77,10 @@ function SurveyQuestionForm({
const defaultIsNotAvailable = choices => {
return defaultValue => {
let errorMessage;
const found = [...defaultValue].every(dA => choices.indexOf(dA) > -1);
const found = [...defaultValue].every(dA => {
console.log(dA, '\n', choices);
return choices.indexOf(dA) > -1;
});
if (!found) {
errorMessage = t`Default choice must be answered from the choices listed.`;
@ -203,7 +208,7 @@ function SurveyQuestionForm({
)}
{['multiplechoice', 'multiselect'].includes(formik.values.type) && (
<>
<FormField
<TextAndCheckboxField
id="question-options"
name="choices"
type="textarea"