gcanti / tcomb-form

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

Set template on sub-type instead of fields #184

Closed damienleroux closed 9 years ago

damienleroux commented 9 years ago

Hi,

I want to figure out if it is possible with tComb-form to link a template to a subType. Here is an example:

I have created a sub type of Str with maxlength = 16:

var string16 = t.subtype(tComb.Str, function (s) {
  return s.length <= 16;
});

I want to display this type within a Form. I have created a structure sent to Form:

var myStruct = t.struct({
  myString : string16
});
<Form ref="form" type={myStruct}  />

When displaying this structure I would like have this:

<inputtype="text" maxlength="16">

Using the Options properties from Form is tedious because I have to redifine the property maxlength for each field based on string16:

var options = {
  fields: {
    myString: {
      maxlength:16
    }
  }
};
<Form ref="form" type={myStruct}  options={options}/>

is that possible to bind a template to the subtype string16 in order to not have to redefine how display it each time a structure uses it?

Thank you very much for your help. Damien

gcanti commented 9 years ago

Using the Options properties from Form is tedious

You could automatically generate the options exploiting the runtime type introspection allowed by tcomb:

var string16 = t.subtype(t.Str, function (s) {
  return s.length <= 16;
});

var myStruct = t.struct({
  myString: string16
});

function getOptions(struct) {
  var options = {fields: {}};
  // every type defined by tcomb has a meta object https://github.com/gcanti/tcomb#runtime-type-introspection
  for (var prop in struct.meta.props) {
    if (struct.meta.props[prop] === string16) {
      options.fields[prop] = {
        attrs: {
          maxLength: 16
        }
      };
    }
  }
  return options;
}

var options = getOptions(myStruct);
damienleroux commented 9 years ago

Thank you for the solution: it is working. I have added a code block to handle the maybe combinator:

function getOptions(struct) {
  var options = {fields: {}};
  // every type defined by tcomb has a meta object https://github.com/gcanti/tcomb#runtime-type-introspection
  for (var prop in struct.meta.props) {
    var type = struct.meta.props[prop];

    if (struct.meta.props[prop].meta.kind == 'maybe')
      type = struct.meta.props[prop].meta.type;

    if (type === string16) {
      options.fields[prop] = {
        attrs: {
          maxLength: 16
        }
      };
    }
  }
  return options;
}
gcanti commented 9 years ago

:+1: