4

The code is as follows

 <TextField {...form.$("phone.countryCode").bind()} value={222} />

The form setup is as follows

{
        name: "phone",
        fields: [
          {
            name: "countryCode",
            label: "Country Code:",
            bindings: "TextField",
            placeholder: "+",
            rules: "required",
          }
       ]
}

The value displays correctly in the textfield. But when i submit the form, it shows "required" error.

I assume field.input.onChange is not triggered when we set the value like this and hence the mobx field is not updated with the value.

Any idea on how to fix this?

Edit:

The value is a dynamic one based on the country selection. So you cannot set the value during initialise. That is why i had to go for this approach.

prajeesh
  • 2,202
  • 6
  • 34
  • 59
  • 222 is just a sample value. The question is if you are storing a value in a text field(or may be a hidden field) why it doesn't update the form? (Also regarding the upvotes, may be there are people who faced similar issue) – prajeesh Sep 24 '21 at 10:34

1 Answers1

0

Don't need to override value on the TextField, mobx-react-form (I am assuming you are using it) can't possibly know that you are doing it. Just pass default value while initialising the form, like so:

const fields = [
  {
    name: "countryCode",
    label: "Country Code:",
    bindings: "TextField",
    placeholder: "+",
    rules: "required",
    value: 'YOUR_DEFAULT_VALUE_HERE'
  }
]

new MobxReactForm({ fields });

If the value depends on the other value then you can use useEffect, for example:

useEffect(() => {
  // set countryCode value manually with needed value
  FormModel.$("countryCode").set(country.code);
// Add needed deps
}, [country])
Danila
  • 15,606
  • 2
  • 35
  • 67