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

Pass initial data to an extended Form object #390

Closed miguelrs closed 6 years ago

miguelrs commented 6 years ago

I have defined my EditEventForm as a class as explained in the docs - like this:

import {Form} from 'mobx-react-form';
import validatorjs from 'validatorjs';

export default class EditEventForm extends Form {

    plugins() {
        return {dvr: validatorjs};
    }

    setup() {
        let event = // Need to get my Event model somehow to build initial values!

        return {
            fields: [
                {
                    name: 'startDateTime',
                    label: 'Start date and time',
                    placeholder: 'Pick a date and time',
                    rules: 'required',
                    value: event.startedAt.format('DD-MM-YYYY'),
                },
                {
                    name: 'endDateTime',
                    label: 'End date and time',
                    placeholder: 'Pick a date and time',
                    rules: 'required',
                    value: event.endedAt.format('DD-MM-YYYY'),
                },
            ],
        };
    }

    hooks() {
        return {
            onSuccess(form) {
                alert('Form is valid! Send the request here.');
                console.log('Form Values!', form.values());
            },
            onError(form) {
                alert('Form has errors!');
                console.log('All form errors', form.errors());
            },
        };
    }
}

And then inside the render() method of some component, I create my form like:

const editEventForm = new EditEventForm();

I've been reading the docs and I can't find out how I can pass that Event model ☝️ to my Form, so that I can set the initial values of the fields based on that...

I'm sure this is such a dumb question and I'm missing something obvious, but can't figure out 😅

klaussa commented 6 years ago

@miguelrs Check this ticket. #384

miguelrs commented 6 years ago

Ok, thanks for your help @euandrei

I figured out now - that bit about the constructor arguments is a bit confusing in the docs...

Anyway, it'd be nice if you could pass some data to the Form class easily and build the default field values based on the given data inside the class...
I liked the approach of having a Form class containing everything about the form configuration, but I had to define the default values in my Component instead of in the Form class, and had to do the same thing for the onSubmit function (in order to access the Store), so eventually the Form class only defines (some bits of) the fields, which makes the class a bit useless... I think I will remove it and define everything in the Component...