Giter Club home page Giter Club logo

formsy-material-ui's Introduction

⚠️ Help Wanted ⚠️

This package is currently under active restoration after a long hiatus, and all help is appreciated, especially MUI users.

formsy-material-ui npm version Build Status

This library is a wrapper for Material-UI form components to allow them to be used with formsy-react, a form validation component for React forms.

Installation

To and install formsy-material-ui and add it to your package.json, run:

$ yarn add formsy-material-ui

You will also need to add these peer dependencies if not already installed:

Usage

import {
  FormsyAutoComplete,
  FormsyCheckbox,
  FormsyDate,
  FormsyRadio,
  FormsyRadioGroup,
  FormsySelect,
  FormsyText,
  FormsyTime,
  FormsyToggle,
} from 'formsy-material-ui';

Events

Components allow for onChange event handlers in props. They are fired when the value of the component changes, regardless of the underlying handler (eg, FormsyToggle uses onToggle internally, but we still use onChange in props to hook into the event.)

The call back signatures for all onChange handlers conform to Material-UI's proposed Standardized Callback Signatures.

An example usage of this would be to use an onChange for the FormsySelect and receive notifications when it changes.

Example Form

import React from 'react';
import createClass from 'create-react-class';
import Formsy from 'formsy-react';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Paper from 'material-ui/Paper';
import RaisedButton from 'material-ui/RaisedButton';
import MenuItem from 'material-ui/MenuItem';
import {
  FormsyCheckbox,
  FormsyDate,
  FormsyRadio,
  FormsyRadioGroup,
  FormsySelect,
  FormsyText,
  FormsyTime,
  FormsyToggle,
  FormsyAutoComplete,
} from 'formsy-material-ui/lib';

const Main = createClass<any, any>({
  /**
   * As an alternative to `MuiThemeProvider` you can add a theme directly into context.
   * See the [Material-UI themes](http://www.material-ui.com/#/customization/themes) docs for details.
   *
   * childContextTypes: {
   *   muiTheme: PropTypes.object,
   * },
   * getChildContext(){
   *   return {
   *     muiTheme: getMuiTheme(),
   *   }
   * },
   */

  getInitialState() {
    return {
      canSubmit: false,
    };
  },

  errorMessages: {
    wordsError: 'Please only use letters',
    numericError: 'Please provide a number',
    urlError: 'Please provide a valid URL',
  },

  styles: {
    paperStyle: {
      width: 300,
      margin: 'auto',
      padding: 20,
    },
    switchStyle: {
      marginBottom: 16,
    },
    submitStyle: {
      marginTop: 32,
    },
  },

  enableButton() {
    this.setState({
      canSubmit: true,
    });
  },

  disableButton() {
    this.setState({
      canSubmit: false,
    });
  },

  submitForm(data) {
    alert(JSON.stringify(data, null, 4));
  },

  notifyFormError(data) {
    console.error('Form error:', data);
  },

  render() {
    let { paperStyle, switchStyle, submitStyle } = this.styles;
    let { wordsError, numericError, urlError } = this.errorMessages;

    return (
      <MuiThemeProvider muiTheme={getMuiTheme()}>
        <Paper style={paperStyle}>
          <Formsy.Form
            onValid={this.enableButton}
            onInvalid={this.disableButton}
            onValidSubmit={this.submitForm}
            onInvalidSubmit={this.notifyFormError}
          >
            <FormsyDate name="date" required floatingLabelText="Date" />
            <FormsyTime name="time" required floatingLabelText="Time" />
            <FormsySelect name="frequency" required floatingLabelText="How often do you?">
              <MenuItem value={'never'} primaryText="Never" />
              <MenuItem value={'nightly'} primaryText="Every Night" />
              <MenuItem value={'weeknights'} primaryText="Weeknights" />
            </FormsySelect>
            <FormsyAutoComplete
              name="frequency-auto-complete"
              required
              floatingLabelText="How often do you?"
              dataSource={['Never', 'Every Night', 'Weeknights']}
            />
            <FormsyCheckbox name="agree" label="Do you agree to disagree?" style={switchStyle} />
            <FormsyToggle name="toggle" label="Toggle" style={switchStyle} />
            <FormsyRadioGroup name="shipSpeed" defaultSelected="not_light">
              <FormsyRadio value="light" label="prepare for light speed" style={switchStyle} />
              <FormsyRadio value="not_light" label="light speed too slow" style={switchStyle} />
              <FormsyRadio value="ludicrous" label="go to ludicrous speed" style={switchStyle} disabled={true} />
            </FormsyRadioGroup>
            <FormsyText
              name="name"
              validations="isWords"
              validationError={wordsError}
              required
              hintText="What is your name?"
              floatingLabelText="Name"
            />
            <FormsyText
              name="age"
              validations="isNumeric"
              validationError={numericError}
              hintText="Are you a wrinkly?"
              floatingLabelText="Age (optional)"
            />
            <FormsyText
              name="url"
              validations="isUrl"
              validationError={urlError}
              required
              hintText="http://www.example.com"
              floatingLabelText="URL"
              updateImmediately
            />
            <RaisedButton style={submitStyle} type="submit" label="Submit" disabled={!this.state.canSubmit} />
          </Formsy.Form>
        </Paper>
      </MuiThemeProvider>
    );
  },
});

export default Main;

Known Issues

See issues.

Release History

See CHANGELOG.md

Acknowledgements

Originally started by Matt Brookes, later transfered to Ryan Blakeley before joining the Formsy Organization.

Thanks to our contributors.

Alternatives

Here are some alternative solutions you might also wish to consider:

formsy-material-ui's People

Contributors

amannn avatar astonm avatar bitdivision avatar codeaholicguy avatar crashbell avatar enricofoschi avatar ferencrocks avatar jchouse avatar joelkoz avatar juanecabellob avatar juicelink avatar jurgob avatar kouak avatar magicalcows avatar mattmcdonald-uk avatar mbrookes avatar mokto avatar mvandiest avatar nicgirault avatar py-in-the-sky avatar reebalazs avatar rkuykendall avatar ryanblakeley avatar salockhart avatar simpixelated avatar testtest2227 avatar tintypemolly avatar ulich avatar valoricde avatar vijayrawatsan 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  avatar  avatar  avatar  avatar  avatar

formsy-material-ui's Issues

Possibility to style the error message

can we have the possibility to style the error message?
for instance sending a hintStyle objects styles the hint text, maybe we can have an errorStyle to style the error

[FormsyText] Cannot access focus() method of original TextField

With material-ui I can access its property through ref, but FormsyText can't:

<TextField
        ref="TodoTextField"
        hintText="task name"
        floatingLabelText="I will do"
        errorText={this.state.data.get('textFieldError')}
        value={this.state.data.get('textFieldValue')}
        onChange={this._handleTextFieldChange}
this.refs.TodoTextField.focus(); //work as expected

With FormsyText

<FormsyText
  ref="TodoTextField"
  name="todoText"
  required
  hintText="task name"
  value={this.state.data.get('textFieldValue')}
  floatingLabelText="I will do" />
Uncaught TypeError: this.refs.TodoTextField.focus is not a function

FormsyCheckbox error on form reset

I have a form which contains some FormsyCheck:

<Formsy.Form
          ref='searchForm'
          method="GET"
          className="form"
          onValidSubmit={this.submitForm}
          onInvalidSubmit={this.submitForm}
          onChange={onChange}
 >
        <FormsyCheckbox
            name={name}
            floatingLabelText={name}
            label={name}
            defaultChecked={!!defaultValue}
        />

        <RaisedButton
            label="Reset"
            onTouchTap={onReset}
         />.

when Inside onReset I call

this.refs.searchForm.reset();

I have the following warning:

warning.js:45 Warning: Failed propType: Required propswitchedwas not specified inEnhancedSwitch. Check the render method ofCheckbox.

Date-Picker slow performance

After opening the modal of FormsyDate, there is a ~1s delay until the date-picker becomes responsive.
Also after clicking on a date, there is another ~1s delay until the corresponding date gets shown as text in modal header (example: clicking on 13, wait, "Fri,Nov 13" is shown in the header)
Any ideas what could cause these delays/ performance issues?

MUI 0.14.1 causes error: Warning: React.createElement: type should not be null, undefined, boolean, or number.

App info: Meteor 1.3 beta-latest, formsy-react and formsy-material-ui have been installed via the new Meteor modules syntax. When I am only using formsy-react (<Formsy.Form />) with a custom created input component, everything loads fine and no errors.

However, as soon as I put <FormsyDate /> (or any of the other input types) nested into the Formsy.Form component, I get these errors on the client:

Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of FormsyDate.

and Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of FormsyDate.

I am importing both modules into my current file like so:

const Formsy = require('formsy-react');
const FMUI = require('formsy-material-ui');
const { FormsyCheckbox, FormsyDate, FormsyRadio, FormsyRadioGroup, FormsySelect, FormsyText, FormsyTime, FormsyToggle } = FMUI; 

I have tried everything to make these errors go away, but I've hit a wall for sure. Do you have any idea what could be causing these errors?

[FormsyText] visual feedback for required inputs

Hi,

Apparently, setting the required attribute on a FormsyText reports the form state as invalid (the submit button can be disabled), but no message appears below the field? Is it the expected behavior? Shouldn't we do something with the showRequired function?

[FormsySelect] "menuItems" property of "SelectField" and "DropDownMenu" has been deprecated

I've some problems with the FormsySelect component. When I use the example code from your readme, i get the following deprecated warnings:

Warning: "menuItems" property of "SelectField" has been deprecated.
to promote composability.

Warning: "menuItems" property of "DropDownMenu" has been deprecated.
Instead, use composability.

When I use the example from the Select Field component, it doesn't work. I think the problem is the onChange property (#27).

Example code:

<FormsySelect
    name="salutation"
    floatingLabelText="Salutation"
    onChange={this._changeSalutation}
    required
    style={{ textAlign: 'left' }}
    tabIndex={1}
    value={this.state.salutation}
>
    {salutationList}
</FormsySelect>

Extract from package.json:

"dependencies": {
    "formsy-material-ui": "^0.3.4",
    "formsy-react": "^0.17.0",
    "material-ui": "^0.14.2",
}

Thanks for your help.

dynamically add/remove form field

Hey there, I'm wondering if you know of an easy way to add/remove form fields depending on the state of the form. For example, showing a new section of the form if a user selects a certain checkbox.

Thank you!

[FormsyDate] formatDate prop skips locale

Current implementation of formatDate formatter skips locale settings thus giving incorrect value due time-zone calculations.

Date set for today is 2015-11-30 which gives "2015-11-29T23:00:00.000Z" as ISO representation. My timezone is CET. Substringing it will give the day before which is incorrect.

The simplest fix would be to change FormsyDate.jsx:12 from

formatDate={(date) => date.toISOString().substring(0,10)}

to

formatDate={(date) => date.toLocaleString().substring(0,10)}

Yellow frame made on double clicking FormsyText

I recently started using material-ui and stumbled upon formsy-material-ui just what I needed.
I get this odd issue when selecting an option by double clicking a text field.There is a yellow box made around it.This does not go until I type something.Is this only my issue.How do I prevent it.
This issue is also in the live demo.

odd

Validation breaks when setting initial state.

Maybe there is some other way to do this, but I'm having the following problem...

Using valueLink breaks validation as it does not go through formsy's getValue() behavior. If you attempt to pass a value prop, as you normally would with formsy, then that prop is spread down to the material-ui component and bypasses formsy's getValue() behavior as well.

I'm in a crunch so I don't have time to make a PR, but I've proven, at least for FormsyText that the following example using destructuring works:

let FormsyText = React.createClass({
  mixins: [ Formsy.Mixin, FormComponentMixin ],
  render: function() {
    var { value, ...other } = this.props;
    return (
      <TextField
        value={this.getValue()}
        {...other}
        onChange={this.handleChange}
        errorText={this.getErrorMessage()} />
    );
  }
});

I don't know whether the same destructuring can be used for the other fields. But I thought I'd start a dialog here around this problem.

[FormsyDate] defaultDate is not valid for required

Hi everyone,

Here my component, I try to set defaultDate is minDate but the form is still invalid cause the value of start_date_time still null until I make a change on this. Have you had any idea for this?

<FormsyDate
        required
        fullWidth
        disableYearSelection
        minDate={minDate}
        defaultDate={minDate}
        formatDate={this.handleFormatDate}
        name="start_date_time"
        floatingLabelText="Start date" />```

onEnterKeyDown has been deprecated in material-ui 0.15

material-ui has released an alpha of 0.15 where onEnterKeyDown has been deprecated.
This causes a warning in the console:

Warning: "onEnterKeyDown" property of "TextField" has been deprecated.
Use onKeyDown and check for keycode instead.

Setting defaultValue still shows hint/floatingLabelText

I'm trying to show a defaultValue. However, if hintText or floatingLabelText is set they will overlay over the defaultValue.

Using these versions:

"material-ui": "0.13.1",
"formsy-react": "0.17.0",
"formsy-material-ui": "0.2.4",

Checkboxes don't toggle

It appears the internal switched property (on MUI Checkbox) is no longer being toggled properly when wrapped in a <FormsyCheckbox>.

It appears that:

  • A click calls <EnhancedSwitch>'s _handleChange().
  • This calls this.props.onParentShouldUpdate(), which is implemented by <Checkbox> and calls this.setState({switched: true}).
  • In the same callback, <EnhancedSwitch> also calls this.props.onSwitch(), which is implemented by <Checkbox>.
  • <Checkbox> calls its own onCheck which is set by Formsy-MUI.
  • This calls Formsy-MUI's setValue(), which fires another setState().
  • This causes the <FormsyCheckbox> to rerender, which fires <Checkbox>'s componentWillReceiveProps.
  • <Checkbox>'s componentWillReceiveProps calls its own setState(), which looks at the value of this.state.switched and overwrites it. But it hasn't changed yet, the transition is still pending, so it is always set to false.

Not sure what the fix is here. <EnhancedSwitch> should probably be passing a callback to onParentShouldUpdate() that it can send to setState(), to ensure the state transition flushes before any other handlers fire.

FormsyText is really slow

I find the text inputs and checkboxes to be really slow when you type. Its fine if you type 1 letter but if you try to type a few words it lags like crazy. This occurs in your demo page as well. Any thoughts?

v0.2.3: Cannot edit already visited input fields

I'm having multiple FormsyText components and basically just following the example. Reproduction:

  • Enter input field
  • Type something (or even don't)
  • Click onto something else
  • Re-visit the field
  • Try to edit the field, doesn't change anything

So, as a user, I'm stuck with whatever I've written into the input the first time I visited it.
Any ideas what could cause that issue?
I'm using ES6 class syntax and React v0.14.1, material-ui v0.13.1

[FormsySelect] dropdown doesn't work

Nothing happens when I click on a FormsySelect component. (Neither are there any errors/warnings/messages in the console.)

I created the FormsySelect component as per the README.md

      <FormsySelect
        name='frequency'
        required
        floatingLabelText="How often?">
        <MenuItem value={'never'} primaryText="Never" />
        <MenuItem value={'nightly'} primaryText="Every Night" />
        <MenuItem value={'weeknights'} primaryText="Weeknights" />
      </FormsySelect>

Please note FormsyText works as per the README.

I am using

"formsy-material-ui": "^0.3.8",
"formsy-react": "^0.17.0",
"material-ui": "^0.14.4",

Problem with `v0.3.0` NPM package

I npm installed twice to update to v0.3.0, and the package only contained the following:

  • CHANGELOG.md
  • LICENSE
  • package.json
  • README.md

FormsySelect behavior when selected empty value

see this example

<Formsy.Form>
  <FormsySelect name="hey" hintText="plzzzzzzzzzzzzzz">
    <MenuItem value="" primaryText="please select"/>
    <MenuItem value="foo" primaryText="foo"/>
    <MenuItem value="bar" primaryText="bar"/>
    <MenuItem value="baz" primaryText="baz"/>
  </FormsySelect>
</Formsy.Form>

blah

This seems quite odd.

A naive solution would be modifying https://github.com/mbrookes/formsy-material-ui/blob/master/src/FormsySelect.jsx#L21

this.setState({hasChanged: true});

like this

this.setState({ hasChanged: value !== '' });

hey

Are there any possible side effects caused by this behavior?

Checkbox array use case throws PropTypes warning

With multiple checkboxes as part of an array, Formsy throws an error because formsy-material-ui/checkbox automatically sets checked to be the value of the checkbox.

https://github.com/mbrookes/formsy-material-ui/blob/master/src/FormsyCheckbox.jsx#L30

Unfortunately if you are trying to save actual values in an array, this falls apart. Example:

<FormsyCheckbox name="tags[]" value="test" label="test"/>
<FormsyCheckbox name="tags[]" value="test2" label="test2"/>
<FormsyCheckbox name="tags[]" value="test3" label="test3"/>

Material UI enhanced switch component PropTypes require that checked be a boolean here:
https://github.com/callemall/material-ui/blob/master/src/enhanced-switch.jsx#L77

So in your component you need to allow for value to be a string and separate from the checked prop if both are defined.

[Core] ES2015 exports

Update exports to ES2015 module format, without breaking things for CommonJS imports like Material-UI 0.14.1 did!

Break with material-ui 0.14.1.

Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of `FormsyText`.

In FormsyText.js, I figure out that

var TextField = require('material-ui/lib/text-field');

should be

var TextField = require('material-ui/lib/text-field').default;

Because text-field.js has changed in material-ui:

'use strict';
Object.defineProperty(exports, "__esModule", {
  value: true
});

var _TextField = require('./TextField');

var _TextField2 = _interopRequireDefault(_TextField);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = _TextField2.default;

Text PropType

It would be nice for the value of a FormsyText component to accept numbers as well instead of just strings. The material-ui TextField accepts of Proptype of "any". If you think this is a valid change, I can submit a PR.

[FormsyText] Validating onBlur doesn't enable the submit button if this is the last field before submit.

If a user fills out a textfield as the last required input, with onBlur the submit button isn't enabled unless the user clicks away from the field. With onChange this problem would likely be resolved.

WIth onChange we can also validate urls in real-time without waiting until they click away, forcing them to re-click on the field.

I can see why with URLs you might want to wait until they have finished typing so we don't pre-maturely show an error but having to re-click on the field is even more frustrating (from my point-of view).

How to submit form in MUI modal

Hi,

I have a modal with the form as the content. I pass my submit button in the actions attribute of the modal component but when clicking the button I don't receive my formData values. How can I submit the form and receive the data from the form with putting the submit button outside the form?

Here is the code that I use for the moment :

import React from 'react';
import Dialog from 'material-ui/lib/dialog';
import FlatButton from 'material-ui/lib/flat-button';
import FormsyText from 'formsy-material-ui/lib/FormsyText';
import { Form } from 'formsy-react';

class EventForm extends React.Component {

  constructor(props) {
    super(props);
    this.submit = this.submit.bind(this);
    this.enableButton = this.enableButton.bind(this);
    this.disableButton = this.disableButton.bind(this);
    this.state = {
      canSubmit: false
    };
  }

  enableButton(){
     this.setState({canSubmit: true});
  }

  disableButton(){
     this.setState({canSubmit: false});
  }

  submit(formData) {
    console.log(formData);
  }

  render() {
    const actions = [
      <FlatButton
        label="Close"
        secondary
        onTouchTap={this.props.onHide}
      />,
      <FlatButton
        label="Submit"
        secondary
      />

    ];

    return (
        <div>
          <Dialog
            title="Add Event"
            actions={actions}
            titleClassName={"dialog-title"}
            actionsContainerClassName={"dialog-footer"}
            modal
            autoScrollBodyContent
          >
            <Form onValidSubmit={this.submit} onValid={this.enableButton}>
              <FormsyText
               name="description"
               validations="minLength:3"
               validationError="Description of the event"
               required
               hintText="Description (required)"
               floatingLabelText="Description (required)"
              />
            </Form>
          </Dialog>
        </div>
    );
  }
}

export default EventForm;

[Tests] Automated test suite needed

Supporting all of formsy's options in conjunction with material-ui is becoming increasingly complex for such a small project. An automated test suite would maybe help, although it could itself become more complex than the code it's testing.

Thoughts?

Example of new select "composability"

Hey there, could you update the readme to include an example of how to use the new "composable" select components? I am seeing a lot of the warnings but am not quite sure how to fix them.

Thanks!

FormsyDate causes Uncaught Invariant Violation

Hi I am trying to use FormsyDate DateField type input for form to format date.
But i am getting following error

Uncaught Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's render method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).

Please let me know what mite be wrong

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.