Formik: How can I build the initialValues dynamically?

Created on 3 May 2018  路  11Comments  路  Source: formium/formik

Question?

How can I build the initialValues dynamically? I want to make a form constructor that receives n fields by initializing these fields according to the number of keys received in an object that comes by parameter...
I know I have solutions using pure JavaScript to create some util, but does Formik have any features that allow you to do this?
Thanks

stale

Most helpful comment

@hygorzorak @stelioschar @FMGordillo in case you're still interested in this the solution to creating dynamic initialValues might look something like this:

{DATA.map((value, index) => {
    let initialValue = `dynamicValue_${value}`;
   return (
       <Formik
            initialValues={{
               [initialValue]: <VALUE>
            }}
    .....
   )

Hopefully that helps someone

All 11 comments

Hola! So here's the deal, between open source and my day job and life and what not, I have a lot to manage, so I use a GitHub bot to automate a few things here and there. This particular GitHub bot is going to mark this as stale because it has not had recent activity for a while. It will be closed if no further activity occurs in a few days. Do not take this personally--seriously--this is a completely automated action. If this is a mistake, just make a comment, DM me, send a carrier pidgeon, or a smoke signal.

ProBot automatically closed this due to inactivity. Holler if this is a mistake, and we'll re-open it.

@hygorzorak Did you finally managed to make this work. If yes, could you share your thoughts?

+1, i'm interested

@palmerbot

@hygorzorak @stelioschar @FMGordillo in case you're still interested in this the solution to creating dynamic initialValues might look something like this:

{DATA.map((value, index) => {
    let initialValue = `dynamicValue_${value}`;
   return (
       <Formik
            initialValues={{
               [initialValue]: <VALUE>
            }}
    .....
   )

Hopefully that helps someone

this is situation. I have tooo

@truecolintracy Hi Colin, Thank you for your answer. How could I create dynamic field validation with yup. where similarly to above I dont know the initial field names. Thanks very much

@AndrewAi do you have a link to a codepen that I might look at, I'm not positive exactly what you're looking to do.

@truecolintracy thanks for your reply, I actually didnt end up needing to have to dynamic yup validation so I got sorted. Thanks very much

Hi, I am relatively new when it comes to working with React and Formik (working on a personal project) but I believe I have worked on something similar recently. I came across this use case where I wanted initial values and validation to be created dynamically. What I have ended up doing for now is, create an array of json object which will act as a model for my form i.e. each element represent a form field.

formSchema = [
  {name: "Article Name", type: "text", required: true, colWidth: "12"}, 
  {name: "Category", type: "select", selectValues: [1, 2, 3], required: true, colWidth: "3"}
]

Then I added a couple of helper Javascript files one for creating initial state and another for creating validation schema. Each of these files exports a method which I can import in my FormComponent. These methods take input the above json I created and return the initial values and validation schema respectively.

To give an idea, for validation schema, I have a function similar to:

export const getValidationSchema = (formHash) => {
  let schemaObject = {};
    _.forEach(formHash, (fieldObject) => {
      schemaObject[fieldObject.name] = getValidationRule(fieldObject);
    });
  return yup.object().shape(schemaObject);
};

const getValidationRule = (formFeild) => {
  let fieldValidationRule = null;
  fieldValidationRule = dataTypeValidation(formFeild.type, fieldValidationRule);
  fieldValidationRule = requiredValidation(formFeild.required, fieldValidationRule);
  return fieldValidationRule;
};

const dataTypeValidation = (fieldType, validationRule) => {
  let typeValidation = validationRule;
  switch(fieldType){
    case 'float':
      typeValidation = yup.number().positive()
      break;
    case 'date':
      typeValidation = yup.date().min(new Date());
      break;
    default:
      typeValidation = yup.string();
  }
  return typeValidation;
};

const requiredValidation = (fieldRequired, validationRule) => {
  let requireValidation = _.cloneDeep(validationRule);
  if(fieldRequired){
    return requireValidation.required("Cannot be blank");
  }
  else{
    return requireValidation;
  }
};

Similarly, I use the type property inside my json model to determine initial value for the respective field.
I came here looking for a similar issue, I thought the work I have done might help someone and I may get some points to improve what I have learnt so far.

Was this page helpful?
0 / 5 - 0 ratings