foxhound87 / mobx-react-form

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

Adding custom field props in extended Class #512

Closed Desteel closed 5 years ago

Desteel commented 5 years ago

Hi! I need to display error messages after press submit button with option showErrorsOnInit: true.

I did not find a way to change the properties of the fields in Form Hooks and added custom property via extended Field Class. I see my custom props it in the console.log(field) output, but I cannot change my custom props and set through form methods. I get this errors Possible Unhandled Promise Rejection (id: 0): Error: The selected property is not allowed (["submitError"])

Can you tell me please, how can I do it?

I try this

class ExtendedField extends Field {
  submitError = false;
  constructor(props: any) {
    super(props);
  }
}

and this

class ExtendedField extends Field {
  submitError; //or $submitError;
  constructor(props: any) {
    super(props);
    this.submitError = false  //or this.$submitError = false 
  }
}

or

class ExtendedField extends Field {
  @observable submitError; //or $submitError;
  constructor(props: any) {
    super(props);
    this.submitError = false  //or this.$submitError = false 
  }
}

And in extended Form Class

export class ExtendedForm extends Form {
  makeField(field: any) {
    return new ExtendedField(field);
  }

public hooks() {
    return {
      onError: (form: Form) => {
        form.each((field: Field) => {
           field.get("submitError")
           field.set("submitError", true)
        });
      }
    };
  }
}
foxhound87 commented 5 years ago

The set and get methods are intended to be used the with the original filed properties. (I don't know if I will change this behavior in the future).

I think you can create new methods to set and get the new property.

Desteel commented 5 years ago

Thank you. Will such an implementation be valid?

export class ExtendedForm extends Form {
  @observable public submitError: boolean = false;

  public options() {
    return { //... };
  }
  public hooks() {
    return {
      onSuccess: (form: Form) => {
        this.submitError = false;
      },
      onError: (form: Form) => {
        this.submitError = true;
      }
    };
  }
}
foxhound87 commented 5 years ago

you can do that but you have isValid/hasError properties already defined in the form object.