Skip to content

Instantly share code, notes, and snippets.

@SilencerWeb
Last active August 7, 2019 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SilencerWeb/d9b25e3e8d268632e4f7a9e63e3c121c to your computer and use it in GitHub Desktop.
Save SilencerWeb/d9b25e3e8d268632e4f7a9e63e3c121c to your computer and use it in GitHub Desktop.
import * as React from 'react';
import { Formik } from 'formik';
import * as Yup from 'yup';
import CryptoJS from 'crypto-js';
import { FormGeneratorContainer } from './contact-form-form-generator.container';
export const FormGenerator = (props) => {
const { data: { formId, apiURL, formFields } } = props;
const initialValues = {};
const schemaObject = {};
formFields.forEach(({ id, type, defaultValue, choices, isRequired }) => {
const fieldID = `input_${id}`;
// Initial values generation
if (type === 'name') {
initialValues[`${fieldID}_3`] = defaultValue;
initialValues[`${fieldID}_6`] = defaultValue;
} else if (type === 'radio' || type === 'select' || type === 'multiselect') {
const parsedChoices = JSON.parse(choices);
let selectedChoice = parsedChoices.find(({ isSelected }) => isSelected === true);
if (!selectedChoice) [selectedChoice] = parsedChoices;
initialValues[fieldID] = selectedChoice.value;
} else {
initialValues[fieldID] = defaultValue;
}
// Validation schema object generation
if (type === 'email') {
schemaObject[fieldID] = Yup.string().email('Please, enter valid email');
} else if (type === 'captcha') {
schemaObject[fieldID] = Yup.string().required('This field is required');
}
if (isRequired === true) {
if (type === 'name') {
schemaObject[`${fieldID}_3`] = Yup.string().required('This field is required');
schemaObject[`${fieldID}_6`] = Yup.string().required('This field is required');
} else if (type === 'email') {
schemaObject[fieldID] = schemaObject[fieldID].required('This field is required');
} else {
schemaObject[fieldID] = Yup.string().required('This field is required');
}
}
});
const handleSubmit = () => {
};
return (
<Formik
initialValues={initialValues}
validationSchema={Yup.object().shape(schemaObject)}
render={(formikBag) => <FormGeneratorContainer {...props} {...formikBag}/>}
enableReinitialize
onSubmit={handleSubmit}
/>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment