gcanti / tcomb-form

Forms library for react
https://gcanti.github.io/tcomb-form
MIT License
1.16k stars 136 forks source link

maybe(Bool) support #93

Closed berndca closed 9 years ago

berndca commented 9 years ago

Thanks for the great library! I'm working on an editor to author documents compliant with IEEE 1685-2014 (IPXACT). This means I have to work with an existing schema. This schema contains conditional Boolean elements, e.g. an element named "volatile". The value of this element is either undefined, true or false. The undefined value can be interpreted as false only if the volatile elements in all child elements are undefined as well. Long story short. There is an actual use case for conditional Boolean fields.

Are you planning to support this in the future? What would be a good workaround right now?

I tried using an Enum, rendered it as radio (so far so good) and tried to use a Transformer to convert betweeen Str and Bool. However I could not get the Transformer to work - I suspect it might only work with 'Textbox'?

Please advise. Thanks, Bernd

gcanti commented 9 years ago

I just made a commit on master branch adding transformers to all components.

In your case something like this should work:

var MyModel = t.struct({
  mybool: t.maybe(t.Bool)
});

var options = {
  fields: {
    mybool: {
      factory: t.form.Select, // render as a select since null is a valid value
      options: [
        {value: '0', text: 'No'},
        {value: '1', text: 'Yes'}
      ],
      transformer: {
        format: function (value) {
          return value === false ? '0' : value === true ? '1' : value;
        },
        parse: function (value) {
          return value === '0' ? false : value === '1' ? true : null;
        }
      }
    }
  }
};

var App = React.createClass({

  save: function () {
    var value = this.refs.form.getValue();
    if (value) {
      console.log(value);
    }
  },

  render: function() {
    return (
      <div>
        <Form ref="form"
          type={MyModel}
          options={options}
        />
        <button className="btn btn-primary" onClick={this.save}>Save</button>
      </div>
    );
  }

});
gcanti commented 9 years ago

Let me know if it's ok

berndca commented 9 years ago

Thanks for the quick response. I switched to version 0.4.8 and tried it out. Works well!

Thanks, Bernd

gcanti commented 9 years ago

Great, thanks for the feedback

Giulio