gcanti / tcomb-form

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

Custom template for "sub form" (struct) #277

Closed vdupre closed 8 years ago

vdupre commented 8 years ago

Hello,

I need to create an simple form for a model (Person) which has a "sub model" (Stat). So I write this :

var formType = tcombForm.struct({
    name: tcombForm.String,
    stat: tcombForm.struct({
        defaultValue: tcombForm.Number,
        bonus: tcombForm.Number
    })
});

and I create a custom template as describe in your doc. It's working for the Person model, but I can't find how to custom the Stat model. If I just type

{ form.inputs.stat }

it displays my stat model fields with the default template,

but I would like to access the sub fields, to do something like :

formTemplate: function(form)
{
    return (
        <div>
            <fieldset>
                <div>{ form.inputs.name }</div>
            </fieldset>
            <fieldset>
                <div className="row">
                    <div className="col-xs-6" >{ form.inputs.stat.defaultValue }</div>
                    <div className="col-xs-6" >{ form.inputs.stat.bonus }</div>
                </div>
            </fieldset>
        </div>
    );
},

Any idea ? thanks by advance !!!

gcanti commented 8 years ago

Hi, the template option can be used at arbitrary level of nesting

function personTemplate(locals) {
  return (
    <div>
      <fieldset>
        { locals.inputs.name }
      </fieldset>
      <fieldset>
        { locals.inputs.stat }
      </fieldset>
    </div>
  )
}

function statTemplate(locals) {
  return (
    <div className="row">
      <div className="col-xs-6" >{ locals.inputs.defaultValue }</div>
      <div className="col-xs-6" >{ locals.inputs.bonus }</div>
    </div>
  )
}

const options = {
  template: personTemplate, // customise form Person
  fields: {
    stat: {
      template: statTemplate // customise subform Stat
    }
  }
}
vdupre commented 8 years ago

Ok, the solution was.. obvious.. sorry for this stupid question and thanks for the quick answer :)

gcanti commented 8 years ago

No problem ;)