Giter Site home page Giter Site logo

nicolaslopezj / simple-react-form Goto Github PK

View Code? Open in Web Editor NEW
228.0 17.0 38.0 12.62 MB

The simplest way to handle forms in React

Home Page: https://www.npmjs.com/package/simple-react-form

License: MIT License

JavaScript 4.86% TypeScript 95.14%
react meteor form react-native schemas

simple-react-form's Introduction

Simple React Form

travis-ci npm version

Simple React Form is the simplest way to handle forms in React. It helps you make reusable form components in React and React Native.

This is just a framework, you must create the form components or install a package with fields that you will use.

To use with react native check here

Installation

Install the base package

npm install --save simple-react-form

Example

import React from 'react'
import {Form, Field} from 'simple-react-form'
import DatePicker from './myFields/DatePicker'
import Text from './myFields/Text'

class PostsCreate extends React.Component {
  state = {}

  render() {
    return (
      <div>
        <Form state={this.state} onChange={state => this.setState(state)}>
          <Field fieldName="name" label="Name" type={Text} />
          <Field fieldName="date" label="A Date" type={DatePicker} />
        </Form>
        <p>My name is {this.state.name}</p>
      </div>
    )
  }
}

Contributions

Docs

Using with state

In this example, the current value of the form will be stored in this.state

import React from 'react'
import {Form, Field} from 'simple-react-form'
import DatePicker from './myFields/DatePicker'
import Text from './myFields/Text'

class PostsCreate extends React.Component {
  state = {}

  render() {
    return (
      <div>
        <Form state={this.state} onChange={state => this.setState(state)}>
          <Field fieldName="name" label="Name" type={Text} />
          <Field fieldName="date" label="A Date" type={DatePicker} />
        </Form>
        <p>My name is {this.state.name}</p>
      </div>
    )
  }
}

Using without state

In this example, the current value of the form will be stored inside the Form component and passed in the onSubmit function. The difference on this is that the state prop does not change over time.

import React from 'react'
import {Form, Field} from 'simple-react-form'
import DatePicker from './myFields/DatePicker'
import Text from './myFields/Text'

class PostsCreate extends React.Component {
  state = {}

  onSubmit({name, date}) {}

  render() {
    return (
      <div>
        <Form ref="form" state={this.props.initialDoc} onSubmit={this.onSubmit}>
          <Field fieldName="name" label="Name" type={Text} />
          <Field fieldName="date" label="A Date" type={DatePicker} />
        </Form>
        <button onClick={() => this.refs.form.submit()}>Submit</button>
      </div>
    )
  }
}

Field Types

React Simple Form is built from the idea that you can create custom components easily.

Basically this consist in a component that have the prop value and the prop onChange. You must render the value and call onChange passing the new value when the value has changed.

import UploadImage from '../components/my-fields/upload'

<Field fieldName='picture' type={UploadImage} squareOnly={true}/>

Creating the field type

You must create a React component.

import React from 'react'

export default class UploadImage extends React.Component {
  render() {
    return (
      <div>
        <p>{this.props.label}</p>
        <div>
          <img src={this.props.value} />
        </div>
        <TextField
          value={this.props.value}
          hintText="Image Url"
          onChange={event => this.props.onChange(event.target.value)}
        />
        <p>{this.props.errorMessage}</p>
      </div>
    )
  }
}

You can view the full list of props here.

React Native

With React Native the api is the same, but you must enclose the inner content of the form with a View component.

Example:

import React from 'react'
import {View, TextInput} from 'react-native'

export default class TextFieldComponent extends React.Component {
  render() {
    return (
      <View>
        <TextInput
          style={{height: 40, borderColor: 'gray', borderWidth: 1}}
          onChangeText={this.props.onChange}
          value={this.props.value}
        />
      </View>
    )
  }
}

Render the form in the component you want

import Text from '../components/my-fields/text'

<Form state={this.state} onChange={changes => this.setState(changes)}>
  <View>
    <Field fieldName='email' type={Text}/>
    <Field fieldName='password' type={Text}/>
  </View>
</Form>

You should always render your fields inside a View when using react native.

WithValue High order component

If you need to get the current value of the form in the children you can use the WithValue component

import React from 'react'
import {Form, Field, WithValue} from 'simple-react-form'

export default class Example extends React.Component {
  render() {
    return (
      <div>
        <Form>
          <WithValue>
            {value => (
              <div>
                <p>The name is {value.name}</p>
                <Field fieldName="name" label="Name" type={Text} />
              </div>
            )}
          </WithValue>
        </Form>
      </div>
    )
  }
}

Contributors

simple-react-form's People

Contributors

fermuch avatar hmontes avatar jaletelier avatar jjgumucio avatar joadr avatar leolebras avatar nicolaslopezj avatar noksenberg avatar prinzdezibel avatar sachag avatar smalin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

simple-react-form's Issues

Wrong Mongo modifier format for update form with commitOnlyChanges={true}

<Form
	schema={Schemas.UserUpdateSchema}
	type='function'
	ref={form => formRef = form}
	doc={userDoc}
	onSubmit={onSubmitAction}
	commitOnlyChanges={true}
>
	<Field fieldName='profile.firstName' type={Text}/>
</Form>

function onSubmitAction(changed) {...}

changed is expected to be: {'profile.firstName': someNewValue}
but the format is: {profile: {firstName: someNewValue}}
Such format does not allow to perform partial Mongo update because the whole profile is replaced instead of just 'firstName'.

Suppose the first variant should be the default behavier when SimpleSchema is not involved, but when it is, Meteor/Mongo is expected.

howto implement bootstrap?

Hi i know this is made for material-ui.
I wanna use it with bootstrap, but can't figure out so fast how I must implement it.
Could you point me in a direction?

Cannot read property propTypes of null

I'm having this error, and a difficult time tracing it. I made sure all my input fields have propTypes, so I don't think that's the issue. Any idea what might be going on? I'm using react native.
screen shot 2017-02-26 at 10 32 28 am

For the form, I'm using simple-schema (or trying to :) ). I use this error whether I use the `collection prop in the form, or declare the type directly (using the component itself).

// attempting to use schema
<Form useFormTag={false} collection={Incidents} state={this.state} onChange={(changes) => this.setState(changes)}>
  <Field  
    fieldName={field.name}
    key={index}
    label={field.label}
    placeHolder={field.label}
    arrayText={arrayText}
    showModal={this.props.showModal}
    submitForm={this.submitForm} />
</Form>

// declaring directly
<Form useFormTag={false} state={this.state} onChange={(changes) => this.setState(changes)}>
  <Field  
    type={TextInput}
    fieldName={field.name}
    key={index}
    label={field.label}
    placeHolder={field.label}
    arrayText={arrayText}
    showModal={this.props.showModal}
    submitForm={this.submitForm} />
</Form>

Compatibility with node-simple-schema

While I can see the examples use the Meteor package aldeed:simple-schema, this is being replaced with the NPM package node-simple-schema.

There are some changes which appear to be breaking this package:
https://github.com/aldeed/meteor-simple-schema/blob/v2/CHANGELOG.md#200

Form validation is failing with:
Uncaught TypeError: context.invalidKeys is not a function

Are there plans to support this new version of simple-schema or shall I fork and attempt to make the required changes? It may be as simple as checking for the renamed functions.

Thanks for the great package!

Create tests

Help is needed to create the tests

Test that are needed:

  • Clean fields helper
  • Clean nulls helper
  • Doc to modifier helper
  • Replace index keys helper
  • Report nulls helper
  • onValueChange function on form
  • Automatic input generation
  • Form is rendered correctly
  • Object field is working correctly
  • Array field is working correctly (this has a history of troubles, test would be great here)

Add support to latest Simple Schema

https://github.com/nicolaslopezj/simple-react-form/blob/master/src/utility/doc-to-modifier.js
https://github.com/nicolaslopezj/simple-react-form/blob/master/src/utility/doc-to-modifier.test.js

// FIXME
// This test throws an error since it depends on MongoObject, and
// MongoObject is a global that comes from aldeed:simple-schema.
// Since it's a meteor package, it can't be tested without
// meteor, so for now we have to skip this test.

Banging my head against this until I spotted the test file explaining things... I've been trying to use NPM packages over meteor packages... it seems however aldeed:simple-schema is an absolute dependency here (specifically, the MongoObject global it provides)

@nicolaslopezj Can you see about upgrading simple-react-form to support the new collection2 meteor package:
https://github.com/aldeed/meteor-collection2
and it's dependency (npm package) "simpl-schema":
https://github.com/aldeed/node-simple-schema

Verify that aldeed:simple-schema is not listed in your .meteor/.versions file. If it is, you likely depend on some other package that has an explicit dependency on the Meteor aldeed:simple-schema package. This could cause problems or unexpected behavior. Work with that package author to get an updated version that does not explicitly depend on the aldeed:simple-schema package.

Don't mean to sound needy just trying to use the latest stuffs :D

dropdown supports collection?

Does this package support this too?

categoryId : {
        type : String,
        optional : true,
        label : "Category",
        autoform : {
            options : function() {
                var docs = Categories.find().fetch()

                return _.map(docs, function(value) {
                    return {
                        label: value.name,
                        value: value.name
                    }
                })
            }
        }
    },

[IDEA] add prop to clear form after submit

Right now if I need to do a form clean, I have to manage the state locally, but since it's a common pattern to clean the form after success, I propose to add the prop clearOnSuccess.

I can do a PR, but I'd like to know if this is wanted by someone else before, and discuss if we should do it in a different way.

props.collection.simpleSchema is not a function(…)

Hi,

Sorry a newbie here and I'm getting the error above with just a basic form.

import React, {Component} from 'react';
import {Form} from 'simple-react-form';

import Scenes from '../../imports/collections/scene.js';

export default class SceneCreate extends Component {
  render() {
    return(
      <div>
        <h1>Create a scene</h1>
        <Form
          collection={Scenes}
          type='insert'
          ref='form'
          />
      </div>
    );
  }
};

Any thoughts as to what I am doing wrong?

Doubts about registerType

Hello! I love your work!

I'm making some fields for bootstrap, and looking at the source code I found some things I don't quite understand about registerType.

On the file types.jsx you create the function registerType, with several arguments, but I can't see where most of them are being used.

For example:

  • what is description for?
  • how should I use optionsDefinition and optionsDescription?
  • is defaultOptions auto-populated from simpleschema's defaultValue?
  • if my field can only accept an object with lat and lng, like {lat: 3, lng: -5}, how should I defined that with allowedTypes?

And another thing, I am trying to build everything without using simpleschemas, to be sure everything is compatible in a not-meteor environment, but I couldn't find how to display errors in the form.

Enhancement: Field should have an omit prop

Use case: Field(Select) is wrapped or passed to ListContainer which renders it passing in needed props(options). However, ListContainer also passed in other props that are not needed. ListContainer is a library component thus without creating a intermediary wrapper component or a custom field React will throw the Unknown Props error.

Validation in onSubmit event

Accounts.LogInSchema.messages({
    email: "Email is not exists"
});
AutoForm.hooks({
  myForm: {
    onSubmit: function (insertDoc, updateDoc, currentDoc) {
      this.event.preventDefault();
      this.validationContext.addInvalidKeys([{ name: "email", type: "email" }]);
      this.done('error');
      return false;
    }
  }
});

Or how else to add custom check with onSubmit={} event?

Normal Validation

Awesome package!
Just implemented it and worked great.

I'm not using autoform, just the plain implementation.

            <Form state={this.state}>
              <Field fieldName='name' label='Stack Name' type={Text}/>
              <Field fieldName='myArray' type={ArrayComponent}>
              First Field
              <Field fieldName='myField' type={Text}/>
              Second Field
              <Field fieldName='myField2' type={Text}/>
              </Field>
            </Form>

Is it possible to add validation from my SimpleSchema for when the form is submitted?
Is it also possible to add instant validation (onBlur) as well?

Thanks nicolasopezj!

Performance with lots of inputs

Hello,

Made a form with 50 inputs some as complex array and such and I can see latency when I write inside the inputs/ On the computer it becomes slow and on mobile really slow, any ideas on how to speed things up?

Cheers for a great component

Thanks

Passing value from parent doesn't set value in child

Sorry I keep changing this I'm trying to sort this out.
When I use the select field this way, it loses the value of the first field on Submit. I've checked in React dev tools and the value exists in the component but, validation complains about it.
?


  cityOptions() {
    return this.props.cities.map((city) => {
      return {'label':city.displayName, 'value':city._id};
    });
  }

  locationOptions() {
    const cityId = this.state.cityValue || '';
    const locationsFiltered = cityId ? _.where(this.props.locations, {cityId:cityId}) : this.props.locations;
    return locationsFiltered.map((location)=> {
      return {'label':location.name,'value':location._id};
    });
  }

  onChange(value) {
    this.setState({cityValue: value});
  }

render() {
    ...
     <Field id='citySelectID' value={this.state.cityValue} onChange={this.onChange} fieldName='cityId' options={this.cityOptions()}/>
     <Field id='optionSelectID' fieldName='locationIds' options={this.locationOptions()}/>
    ...
}

Client-side code shouldn't be embedded in server-side schema?

I'm using SRF with OnsenUI, and I'm having this issue: in the schema (Simple Schema) I use client-side components as "type" for the srf field (e.g. name: {type: String, srf: {type: TextInput}}). This in turn causes problems as some of the client-side code in OnsenUI can't be executed on the server, which SRF tries to do, since SimpleSchema is isomorphic.

My TextInput field, for example, depends on a script that starts with the following if statement:
if (!window.CustomEvent) {
But unfortunately window doesn't exist on the server.

What's the best approach to handle this?

Sharing Custom Field Componets

I've build a couple now that I would not mind sharing. One to is a Google Recaptcha that prevents the form from being submitted until the recaptcha has been passed and returns the recaptcha string for server side validation. The other is a drop zone that will upload a file using a callback, preview images, has a progress bar, and returns the url passed back to it from the uploader. Neither of these are specific to bootstrap or material, although I have only tested them with material.

Select Field Type

Hi, im getting the following error when trying to use a field with a dropdown. Is this the correct way of defining the srf field?

gender: {
        type: String,
        allowedValues: ['Male', 'Female'],
        optional: true,
        srf: {
        type: 'select'
    }
    },

Here is the error:

modules.js?hash=2453b8c…:22991 Warning: Failed propType: Required prop `options` was not specified in `SelectComponent`. Check the render method of `Field`.warning @ modules.js?hash=2453b8c…:22991checkPropTypes @ modules.js?hash=2453b8c…:21566validatePropTypes @ modules.js?hash=2453b8c…:21585ReactElementValidator.createElement @ modules.js?hash=2453b8c…:21619getComponent @ modules.js?hash=2453b8c…:41029render @ modules.js?hash=2453b8c…:41074ReactCompositeComponentMixin._renderValidatedComponentWithoutOwnerOrContext @ modules.js?hash=2453b8c…:10014ReactCompositeComponentMixin._renderValidatedComponent @ modules.js?hash=2453b8c…:10034ReactCompositeComponent__renderValidatedComponent @ modules.js?hash=2453b8c…:3792ReactCompositeComponentMixin.mountComponent @ modules.js?hash=2453b8c…:9647ReactCompositeComponent_mountComponent @ modules.js?hash=2453b8c…:3792ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactMultiChild.Mixin.mountChildren @ modules.js?hash=2453b8c…:16458ReactDOMComponent.Mixin._createContentMarkup @ modules.js?hash=2453b8c…:13797ReactDOMComponent.Mixin.mountComponent @ modules.js?hash=2453b8c…:13685ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactCompositeComponentMixin.mountComponent @ modules.js?hash=2453b8c…:9652ReactCompositeComponent_mountComponent @ modules.js?hash=2453b8c…:3792ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactMultiChild.Mixin.mountChildren @ modules.js?hash=2453b8c…:16458ReactDOMComponent.Mixin._createContentMarkup @ modules.js?hash=2453b8c…:13797ReactDOMComponent.Mixin.mountComponent @ modules.js?hash=2453b8c…:13685ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactMultiChild.Mixin.mountChildren @ modules.js?hash=2453b8c…:16458ReactDOMComponent.Mixin._createContentMarkup @ modules.js?hash=2453b8c…:13797ReactDOMComponent.Mixin.mountComponent @ modules.js?hash=2453b8c…:13685ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactCompositeComponentMixin.mountComponent @ modules.js?hash=2453b8c…:9652ReactCompositeComponent_mountComponent @ modules.js?hash=2453b8c…:3792ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactCompositeComponentMixin.mountComponent @ modules.js?hash=2453b8c…:9652ReactCompositeComponent_mountComponent @ modules.js?hash=2453b8c…:3792ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactCompositeComponentMixin.mountComponent @ modules.js?hash=2453b8c…:9652ReactCompositeComponent_mountComponent @ modules.js?hash=2453b8c…:3792ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactMultiChild.Mixin.mountChildren @ modules.js?hash=2453b8c…:16458ReactDOMComponent.Mixin._createContentMarkup @ modules.js?hash=2453b8c…:13797ReactDOMComponent.Mixin.mountComponent @ modules.js?hash=2453b8c…:13685ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactMultiChild.Mixin.mountChildren @ modules.js?hash=2453b8c…:16458ReactDOMComponent.Mixin._createContentMarkup @ modules.js?hash=2453b8c…:13797ReactDOMComponent.Mixin.mountComponent @ modules.js?hash=2453b8c…:13685ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactCompositeComponentMixin.mountComponent @ modules.js?hash=2453b8c…:9652ReactCompositeComponent_mountComponent @ modules.js?hash=2453b8c…:3792ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactMultiChild.Mixin.mountChildren @ modules.js?hash=2453b8c…:16458ReactDOMComponent.Mixin._createContentMarkup @ modules.js?hash=2453b8c…:13797ReactDOMComponent.Mixin.mountComponent @ modules.js?hash=2453b8c…:13685ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactMultiChild.Mixin.mountChildren @ modules.js?hash=2453b8c…:16458ReactDOMComponent.Mixin._createContentMarkup @ modules.js?hash=2453b8c…:13797ReactDOMComponent.Mixin.mountComponent @ modules.js?hash=2453b8c…:13685ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactCompositeComponentMixin.mountComponent @ modules.js?hash=2453b8c…:9652ReactCompositeComponent_mountComponent @ modules.js?hash=2453b8c…:3792ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactCompositeComponentMixin.mountComponent @ modules.js?hash=2453b8c…:9652ReactCompositeComponent_mountComponent @ modules.js?hash=2453b8c…:3792ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactCompositeComponentMixin.mountComponent @ modules.js?hash=2453b8c…:9652ReactCompositeComponent_mountComponent @ modules.js?hash=2453b8c…:3792ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactCompositeComponentMixin.mountComponent @ modules.js?hash=2453b8c…:9652ReactCompositeComponent_mountComponent @ modules.js?hash=2453b8c…:3792ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063ReactCompositeComponentMixin.mountComponent @ modules.js?hash=2453b8c…:9652ReactCompositeComponent_mountComponent @ modules.js?hash=2453b8c…:3792ReactReconciler.mountComponent @ modules.js?hash=2453b8c…:8063mountComponentIntoNode @ modules.js?hash=2453b8c…:4966Mixin.perform @ modules.js?hash=2453b8c…:9200batchedMountComponentIntoNode @ modules.js?hash=2453b8c…:4982Mixin.perform @ modules.js?hash=2453b8c…:9200ReactDefaultBatchingStrategy.batchedUpdates @ modules.js?hash=2453b8c…:13191batchedUpdates @ modules.js?hash=2453b8c…:8693ReactMount._renderNewRootComponent @ modules.js?hash=2453b8c…:5176ReactMount__renderNewRootComponent @ modules.js?hash=2453b8c…:3792ReactMount._renderSubtreeIntoContainer @ modules.js?hash=2453b8c…:5250ReactMount.render @ modules.js?hash=2453b8c…:5270React_render @ modules.js?hash=2453b8c…:3792(anonymous function) @ modules.js?hash=2453b8c…:64435
modules.js?hash=2453b8c…:65780 Uncaught TypeError: Cannot read property 'map' of undefined

Pre-submit hook

Hello, thank you for your package.
As I see it's API doesn't have any hooks (I use it with meteor Simple Schema package).
Do you have any plans for it? Or maybe you can advice how to preprocess form data, before sending it do DB.

Field Type hidden

const TestSchema = new SimpleSchema({
  plan: {
    type: String
  }
})

class Test extends React.Component {
  constructor(props) {
    super(props)
    this.onSubmit = this.onSubmit.bind(this)
    this.state = {
    }
  }
  onSubmit(doc) {
    console.log(doc) // {} no plan property here
  }
  render() {
   const plan = "pro"
    return (
      <Form schema={TestSchema} type="function" onSubmit={this.onSubmit} >
         <Field fieldName="plan" fieldType="hidden" showLabel={false} value={plan} />
      </Form>
    )
  }
}

React native with Array field: 'There is no field "parentField.0.0.childField" in the schema'

I'm trying to set up the Array field with react native. If all goes well, I'll make a pull request. For right now, I'm stumped by this issue, somehow the getFieldName in Field.js is getting parentField.0 as the context.parentFieldName (that seems right), and 0.childField for this.props.fieldName (that seems wrong). Any ideas on how to go about fixing this? The only thing I changed for RN compatibility is this (in ArrayContextItem.js):

isRN () {
  return navigator.product === 'ReactNative'
}

render () {
    if (this.isRN()) {
      const {View} = require('react-native');
      return (
        <View>
          {this.props.children}
        </View>
      )
    }
    return (
      <div>
        {this.props.children}
      </div>
    )
  }

Add className

Is there any reason you don't pass className to the Form and Field components? I would be happy to make a PR, I just wanted to check and see if there was a reason for that.

Need Maintenance Help?

@nicolaslopezj if you want you can add me as a maintainer here as well as the srf material ui. We use SRF in our production app where I work and would not mind helping out.

Validation

How you accomplish validation error messaging per field when using simple schema? Is it possible and not documented?

I'd love to do something like this in my schema:
firstname: { type: String, optional: false, srf: { type: TextFieldComponent, errorText: (fieldInvalid) ? "ERROR" : "", }, regEx: /.{1,}/ },
But i'm not sure how to make it reactive (the fieldInvalid variable):

I've also tried handling it on the other end- before the "submit" - I can grab the collection schema and use it to validate each field... trouble is i'm not sure how to update the field "errorText" property using a ref to the form, is that even possible?

Insert not found

I can't figure out why i get this. I'm pretty new with meteor but as far as i now simple schema should handle the insert method and all the other crud stuff.

this is my code:

import Textarea from 'simple-react-form-material-ui/lib/textarea'
import Text from 'simple-react-form-material-ui/lib/text'
const Events = new Mongo.Collection('events');

Events.allow({
  insert: (userId, doc) => {
    return !!userId;
  }
});

Events.attachSchema({
  title: {
    type: String,
    label: "Title",
    max: 200,
    srf: {
      type: Text
    }
  },
  desc: {
    type: String,
    label: "Description",
    srf: {
      type: Textarea
    }
  }
)}

my component:

import React, { Component } from 'react';
import { Form } from 'simple-react-form';
import Events from '../../api/events/events';
import RaisedButton from 'material-ui/RaisedButton';

export default class NewEvent extends Component {
  render () {
    return (
      <div>
        <Form
          collection={Events}
          type='insert'
          ref='form'
          onSuccess={(docId) => { alert("Submitted") }} />
          <RaisedButton label='Create' onTouchTap={() => this.refs.form.submit()}/>
      </div>
    )
  }
}

but on submit i get:

[form-defaultFormId-error] errorClass {error: 404, reason: "Method '/events/insert' not found", details: undefined, message: "Method '/events/insert' not found [404]", errorType: "Meteor.Error"…}

it seems like i've to defined by myself insert, update and delete, do I?

React js warning after save

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Form component.

Warning appears when updating a collection

I get a warning when updating a collection. I'm not using any state change in the update page.

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.

please give it a look

Creating a fieldtype for object doesn't save the new doc

I've been trying to add a fieldtype that will control an object in the schema and when submitting the form, it doesn't get saved and it's not for any validation issues (I've tried to add blackbox: true to the schema and still doesn't work.

Any help on this, is highly apreciated.

Thanks

Documentation improvements

We need help to make the documentation easier to read. Please make suggestions of changes to make it better

simple-react-form problem with textfields?

I am not sure if simple-react-form is causing the problem or what, since I did a lot of changes in my project without testing, but now every time I add a field inside a form associated with state instead of a collection every time I try to write on any field inside the form I get this error message.

Uncaught TypeError: Cannot read property 'type' of null
at TextFieldComponent._isNumberType (modules.js?hash=81afe6d…:40088)
at TextFieldComponent.onChange (modules.js?hash=81afe6d…:40093)
at TextField._this.handleInputChange (modules.js?hash=81afe6d…:21568)
at Object.executeOnChange (modules.js?hash=81afe6d…:49757)
at ReactDOMComponent._handleChange (modules.js?hash=81afe6d…:49573)
at Object.ReactErrorUtils.js.ReactErrorUtils.invokeGuardedCallback (modules.js?hash=81afe6d…:42809)
at executeDispatch (modules.js?hash=81afe6d…:42589)
at Object.executeDispatchesInOrder (modules.js?hash=81afe6d…:42612)
at executeDispatchesAndRelease (modules.js?hash=81afe6d…:41996)
at executeDispatchesAndReleaseTopLevel (modules.js?hash=81afe6d…:42007)

coming from this form

any help? :)

[String] array field

I have a field defined in the schema as [String], and a field definition like so:

"photos": {type: [String], optional: true, srf: {type: PhotoInput}},

But that showed just the PhotoInput, not in array form. So I thought, let's try this:

"photos": {type: Array, optional: true, srf: {type: ArrayField}},
"photos.$": {type: String, srf: {type: PhotoInput}},

But that shows an empty array field, that is an array with no input field.

Does the array field only work for arrays of objects?

Put material ui component into a separate project

Hi,

Can you please separate your material ui components into another project that depends on this one. That way we can create components for bootstrap, semantic ui, etc. without bloating the code.

How get index in Array type Field

<Field fieldName="sections" type={Array}>
   <Field fieldName="type" type={Select} />
   {this.state.sections[<how get index here?>].type === 'value' &&
       <Field fieldName="headline" type={Text}>
   }
</Field>

Have problem with the example.

I make all what the example show. But activate the srf with the code don't work. I got Match undefined etc. Everything else work but I can't change the type of the form.

Can't get custom field to submit updated value

Hi,
I've created a custom field for image upload. Internally it works but it never submits the (new) value. I'm not sure what it needs to send the updated value properly.

import React, { Component, PropTypes } from 'react';
import TextField from 'material-ui/TextField'
import styles from 'simple-react-form-material-ui/lib/styles'
import {FieldType, registerType} from 'simple-react-form'
import cloudinary from 'cloudinary';
import {createMarkup, cloudinaryURL} from '/lib/utils.js';

const CLOUDINARY_UPLOAD_PRESET = Meteor.settings.CLOUDINARY_UPLOAD_PRESET;
const CLOUDINARY_API_KEY = Meteor.settings.public.CLOUDINARY_API_KEY;
const CLOUDINARY_API_SECRET = Meteor.settings.CLOUDINARY_API_SECRET;
const CLOUDINARY_UPLOAD_URL = 'https://api.cloudinary.com/v1_1/' + Meteor.settings.public.CLOUDINARY_CLOUD_NAME +'/image/upload';

const propTypes = {
  ...FieldType.propTypes,
  fieldType: React.PropTypes.string
}

const defaultProps = {

}

export default class ImageUpload extends Component {

  constructor(props) {
    super(props);
    this.state = {
      value: props.value,
    };
    this.type = 'image';
    this.handleChange = this.handleChange.bind(this);
  }

  componentWillReceiveProps (nextProps) {
    this.setState({ value: nextProps.value })
  }

  onChange (event) {
    this.setState({ value: event.target.value })
  }

  handleChange(e) {
    let files = e.currentTarget.files;
    return Cloudinary.upload(files, {}, function(err,res){
      this.setState({
        value: res.public_id
      });
    }.bind(this));
  }

  render() {
    return <div>
      <div className="fileUpload">
        <p>{this.props.label}</p>
        <input name='file' type='file' ref='file' className='cloudinary-fileupload'
          data-cloudinary-field='image-id' onChange={this.handleChange}/>
          <div style={styles.errorMessage}>{this.props.errorMessage}</div>
      </div>
      <div>
        <div>
          <TextField ref='input'
            fullWidth
            floatingLabelText={this.props.useHint ? null : this.props.label}
            hintText={this.props.useHint ? this.props.label : null}
            value={this.state.value || ''}
            onChange={this.onChange.bind(this)}
            {...this.props.passProps}
          />
          <img width='100' src={cloudinaryURL(this.state.value, 100, null, 'fill', 'auto')} />
        </div>
      </div>
    </div>;
  }
}

ImageUpload.propTypes = propTypes
ImageUpload.defaultProps = defaultProps

registerType({
  type: 'image',
  component: ImageUpload
})

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.