Coder Social home page Coder Social logo

aor-dependent-input's Introduction

archived Archived Repository
This code is no longer maintained. Feel free to fork it, but use it at your own risks.

aor-dependent-input

Build Status

A component for displaying inputs and fields depending on other inputs or fields values in Admin-on-rest.

Installation

Install with:

npm install --save aor-dependent-input

or

yarn add aor-dependent-input

Usage

Check that the field specified by dependsOn has a value (a truthy value):

import { DependentInput } from 'aor-dependent-input';

export const UserCreate = (props) => (
    <Create {...props}>
        <SimpleForm>
            <TextInput source="firstName" />
            <TextInput source="lastName" />
            <BooleanInput source="hasEmail" label="Has email ?" />
            <DependentInput dependsOn="hasEmail">
                <TextInput source="email" />
            </DependentInput>
        </SimpleForm>
    </Create>
);

Check that the field specified by dependsOn has a specific value:

import { DependentInput } from 'aor-dependent-input';

export const PostCreate = (props) => (
    <Create {...props}>
        <SimpleForm>
            <TextInput source="title" />

            <SelectInput source="category" choices={[
                { id: 'programming', name: 'Programming' },
                { id: 'lifestyle', name: 'Lifestyle' },
                { id: 'photography', name: 'Photography' },
            ]} />

            <DependentInput dependsOn="category" value="programming">
                <SelectInput source="subcategory" choices={[
                    { id: 'js', name: 'JavaScript' },
                    { id: 'net', name: '.NET' },
                    { id: 'java', name: 'Java' },
                ]} />
            </DependentInput>

            <DependentInput dependsOn="category" value="lifestyle">
                <SelectInput source="subcategory" choices={[
                    ...
                ]} />
            </DependentInput>

            <DependentInput dependsOn="category" value="photography">
                <SelectInput source="subcategory" choices={[
                    ...
                ]} />
            </DependentInput>
        </SimpleForm>
    </Create>
);

Check that the field specified by dependsOn matches a custom constraint:

import { DependentInput } from 'aor-dependent-input';

const checkCustomConstraint = (value) => value.startsWith('programming'));

export const PostCreate = (props) => (
    <Create {...props}>
        <SimpleForm>
            <TextInput source="title" />
            <SelectInput source="category" choices={[
                    { id: 'programming_js', name: 'JavaScript' },
                    { id: 'programming_net', name: '.NET' },
                    { id: 'programming_java', name: 'Java' },
                    { id: 'lifestyle', name: 'Lifestyle' },
                    { id: 'photography', name: 'Photography' },
            ]} />

            <DependentInput dependsOn="category" resolve={checkCustomConstraint}>
                <SelectInput source="subcategory" choices={[
                    { id: 'js', name: 'JavaScript' },
                    { id: 'net', name: '.NET' },
                    { id: 'java', name: 'Java' },
                ]} />
            </DependentInput>
        </SimpleForm>
    </Create>
);

All powers! Check whether the current full record matches your constraints:

import { DependentInput } from 'aor-dependent-input';

const checkRecord = (record) => record.firstName && record.lastName);

export const UserCreate = (props) => (
    <Create {...props}>
        <SimpleForm>
            <TextInput source="firstName" />
            <TextInput source="lastName" />

            <DependentInput resolve={checkRecord}>
                <EmailInput source="email" />
            </DependentInput>
        </SimpleForm>
    </Create>
);

API

The DependentInput and DependentField components accepts the following props:

dependsOn

Either a string indicating the name of the field to check (eg: hasEmail) or an array of fields to check (eg: ['firstName', 'lastName']).

You can specify deep paths such as author.firstName.

value

If not specified, only check that the field(s) specified by dependsOn have a truthy value.

You may specify a single value or an array of values. Deep paths will be correctly retrieved and compared to the specified values.

If both value and resolve are specified, value will be ignored.

resolve

The resolve prop accepts a function which must return either true to display the child input or false to hide it.

If the dependsOn prop is specified, resolve will be called with either the value of the field specified by dependsOn (when a single field name was specified as dependsOn) or with an object matching the specified paths.

Note: When specifying deep paths (eg: author.firstName), resolve will be called with an object matching the specified structure. For example, when passing ['author.firstName', 'author.lastName'] as dependsOn, the resolve function will be passed the following object:

{ author: { firstName: 'bValue', lastName: 'cValue' } }

If dependsOn is not specified, resolve will be called with the current form values (DependentInput) or the full record (DependentField).

If both value and resolve are specified, value will be ignored.

Re-rendering the DependentInput children when the values of the dependencies change

This could be necessary to implement cascaded select. For example, a song may have a genre and a sub genre, which are retrieved with calls to an external service not hosted in our API. This is how we could display only the sub genres for the selected genre:

// in SubGenreInput.js
import React, { Component } from 'react';
import { translate, SelectInput } from 'admin-on-rest';
import fetchSubGenres from './fetchSubGenres';

class SubGenreInput extends Component {
    state = {
        subgenres: [],
    }

    // This is necessary so that the SelectInput receive all its required props
    // from redux-form
    static defaultProps = { addField: true };

    componentDidMount() {
        this.fetchData(this.props);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.dependsOnValue !== this.props.dependsOnValue) {
            this.fetchData(nextProps);
        }
    }

    fetchData(props) {
        fetchSubGenres(props.dependsOnValue).then(subgenres => {
            this.setState({ subgenres });
        })
    }

    render() {
        return <SelectInput {...this.props} choices={this.state.subgenres} />
    }
}

SubGenreInput.propTypes = SelectInput.propTypes;
SubGenreInput.defaultProps = SelectInput.defaultProps;

export default SubGenreInput;

Contributing

Run the tests with this command:

make test

Coverage data is available in ./coverage after executing make test.

An HTML report is generated in ./coverage/lcov-report/index.html.

aor-dependent-input's People

Contributors

alexisjanvier avatar djhi avatar fzaninotto avatar jdemangeon avatar jpetitcolas avatar sedy-bot avatar webda2l 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

Watchers

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

aor-dependent-input's Issues

Change boolean's value according to another boolean

Hello,

I have two boolean inputs and I want to make true the second boolean when the first is toggled.
It is necessary that fields are both rendered at first time and none of them is hidden.
Does aor-dependent-input covers that functionality?

React does not recognize the dependsOnValue

Hi,
I think it is an issue with React 16 but I'm not sure.
I have this code:

React does not recognize the dependsOnValue prop on a DOM element

 <DependentInput dependsOn="country_id">
              <StatesSelectInput source="state_id"/>
            </DependentInput>

In my console I have this error:

Warning: React does not recognize the `dependsOnValue` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `dependsonvalue` instead. If you accidentally passed it from a parent component, remove it from the DOM element.

The error is clear, it is not urgent but just annoying.
Thanks.

DependentInput does not work

Hi.

  • I am using DependentInput for hide some fields on the scren depending of type of users.
  • I have checked differentes configurations but I get unexpected results. No fields are shown

Option 1:

import {DependentInput} from 'aor-dependent-input';
<TextField source="type" />
<DependentInput dependsOn="type" value="NATURAL" >
    <TextField source="firstName" />
    <TextField source="lastName" />
</DependentInput>            
<DependentInput dependsOn="type" value="JURIDICAL" >
    <TextField source="companyName" label="Company name"/>
</DependentInput>

Option 2:

import {DependentInput} from 'aor-dependent-input';
const isNatural = (record) => record.isNatural;
<TextField source="type" />
<DependentInput resolve={isNatural} >
    <TextField source="firstName" />
    <TextField source="lastName" />
</DependentInput>
  • It show type set to NATURAL
  • I got a undefined error

Option 3:

const isNaturalUser = (value) => {value.startsWith('NATURAL');}
<TextField source="type" />
<DependentInput dependsOn="type" resolve={isNaturalUser} >
    <TextField source="firstName" />
    <TextField source="lastName" />
</DependentInput>
  • It show type set to NATURAL
  • I got a undefined error

image

Used Versions:
"admin-on-rest": "^1.4.1",
"aor-dependent-input": "^1.2.0",

Could anyone help me?

Thanks you very much.

Cannot detect field values when used within EmbeddedArrayInput

When paired with https://github.com/MhdSyrwan/aor-embedded-array, the field values are always undefined:

Data:

{
    some_array: [
        {
            type: 'other',
            name: 'Some Name'
        }
    ]
}

Component:

const doResolve = (value) => {
    console.log(value);
    return true;
}

...

<EmbeddedArrayInput label="" source="some_array">
    <TextInput label="Type" source="type"/>
    <DependentInput dependsOn="type" resolve={doResolve}>
        <TextInput label="Name" source="name"/>
    </DependentInput>
</EmbeddedArrayInput>

Even if I use value or resolve, the value cannot be detected.

To be honest I'm unsure whether the problem is with the DependentInput or EmbeddedArrayInput

Dependent input when both resources are based on the REST client and have a 'belongsTo' relationship?

Hi,

I checked your example with your outer fetch, but I do not understand how to achieve a dependent input for a sub-resource, through AOR stateless functions (or not). The use case is that we want the "subCategories" field to be populated based on the "categories" field, to which there is a 'belongsTo' relationship.

    <Create title={<TitleCreate />}{...props}>
        <SimpleForm validate={validateCreateEdit}>

            <ReferenceInput label="CATEGORY" source="cat_id" reference="categories" allowEmpty
                            perPage={100}
                            sort={{field: 'name', order: 'ASC'}}
            >
                <SelectInput optionText="name" />
            </ReferenceInput>

            <ReferenceInput label="SUBCATEGORY" source="subCat_id" reference="subCategories" allowEmpty
                            perPage={100}
                            sort={{field: 'name', order: 'ASC'}}
            >
                <SelectInput optionText="name" />
            </ReferenceInput>

        </SimpleForm>
    </Create>

This is the relationship:

  "relations": {
    "category": {
      "type": "belongsTo",
      "model": "category",
      "foreignKey": "cat_id"
    }
  }
````

I do not understand how this can be done based on the above generic AOR code.

Thanks for any hints or added documentation!

Delayed updates on multiple DependentInput depending on SelectInput

The DependentInput has weird behaviour with defaultValue and SelectInput
example below

when you click on the select it does not change value until you click on the same item again
if you remove defaultValue's or if you have only one DependentInput it works ok

<SimpleForm>
  <SelectInput source="type" choices={[
    {
      id: 'pc',
      name: 'pc',
    },
    {
      id: 'server',
      name: 'server',
    },
    {
      id: 'gateway',
      name: 'gateway',
    },
    {
      id: 'acnetel',
      name: 'acnetel',
    },
  ]} defaultValue="gateway" />

        <DependentInput resolve={switchType('gateway')}>
          <TextInput source="nat" defaultValue="gateway"  />
        </DependentInput>

        <DependentInput resolve={switchType('pc')}>
          <TextInput source="not" defaultValue="pc" />
        </DependentInput>

        <DependentInput resolve={switchType('server')}>
          <TextInput source="nit" defaultValue="server" />
        </DependentInput>

        <DependentInput resolve={switchType('acnetel')}>
          <TextInput source="net" defaultValue="acntel" />
        </DependentInput>
</SimpleForm>
const switchType = (value) => (values) => {
  return values['type'] === value;
};

ReferenceInput

I have 2 ReferenceInput. The thing I want is to pick a company and show only branches of that company. I try this but it does not work.
The branches have a field called motherID that connects them with the companies.

    <ReferenceInput  source="CompanyID" reference="companies" allowEmpty alwaysOn>
    <SelectInput optionText={choice => `${choice.name}`} />
    </ReferenceInput>

    <DependentInput dependsOn="CompanyID" >
    <ReferenceInput  source="BranchID" reference="branches" allowEmpty alwaysOn>
    <SelectInput optionText={choice => `${choice.tmima  +" "+ choice.address}`} />
    </ReferenceInput>
    </DependentInput>

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.