foxhound87 / mobx-react-form

Reactive MobX Form State Management
https://foxhound87.github.io/mobx-react-form
MIT License
1.09k stars 129 forks source link

Mixed Mode values fallback #225

Closed pdfowler closed 7 years ago

pdfowler commented 7 years ago

I'm trying to implement a simple name + address form, following the guidelines in the docs/guide, but after a single successful run, I can't get it to work.

Here's what I'm working with:

Base Object:

const user = {
    name: 'fatty',
    address: {
        street: '123 Fake St.',
        zip: '12345',
    }
}

Field Defs:

export const addrFields = [{
    name: 'street',
    label: 'Street',
    rules: 'required|string',
  }, {
    name: 'zip',
    label: 'ZIP Code',
    rules: 'required|string',
}];

export const fields = [
  {
    name: 'name',
    label: 'Name',
    rules: 'required|string|between:5,50',
  },
  {
    name: 'address',
    label: 'Address',
    fields: addrFields,
}];

myForm.js

import Form from './_.extend';

class BasicNestedForm extends Form { /* etc */ }

export function init(values = {}) {
  return new BasicNestedForm({ fields, values });
}

Repro:

  1. initialize the form with: newForm = myForm.init(user)
  2. the "name" field is correctly populated : newForm.$('name').value === user.name (/)
  3. the "address" nested field is not populated w/ values. It has has newForm.$('address').values() === addrFields, Expected: newForm.$('address').values() === user.address && newForm.$('address.street').value === user.address.street
foxhound87 commented 7 years ago

In the meantime you can use the separated fields mode defining mutliple object like this:

const plugins = {
  dvr: validatorjs,
};

const fields = [
  'name',
  'address',
  'address.street',
  'address.zip',
];

const rules = {
  'name': 'required|string|between:5,50',
  'address.street': 'required|string',
  'address.zip': 'required|string',
};

const values = {
  name: 'fatty',
  address: {
    street: '123 Fake St.',
    zip: '12345',
  },
};

new NewForm({ fields, values, rules }, { plugins });
pdfowler commented 7 years ago

That did the trick! Thanks

An additional note on the repro: When the form rendered, the address (nested) fields would render with "[object]" as the value.

foxhound87 commented 7 years ago

That because the address field contains nested fields (as props), so its value prop is computed with the nested values as object.

foxhound87 commented 7 years ago

This issue occurred because you used some sort of "mixed mode" (using the separated mode in conjunction with the unified mode), and this kind of use is not tested by me, but it is much interesting to be considered as a future feature.

Only for more information: If you are not using separated mode, the unified mode will work defining the values in the fields object or with the update() method.