Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

admin-on-rest: Hide Form Input depends on other Input value

I couldn't find way to hide input depends on some record value. I tried to get import { formValueSelector } from 'redux-form' to get current state but i failed.

export default props => 
    <Edit {...props}>
        <SimpleForm>
            <DisabledInput source="id"/>
            <NumberInput options={opts} source="age" />
            {
            props.record.age > 18 &&
                <TextInput options={opts} source="question"/>
            }
        </SimpleForm>
    </Edit>
like image 723
Ismail Baskin Avatar asked Dec 02 '22 12:12

Ismail Baskin


2 Answers

You can use marmelab/aor-dependent-input, it's a component for displaying input depending on other inputs values.

Example usage:

import React from 'react';
import {
    Create, SimpleForm, TextInput, DisabledInput, NumberInput
} from 'admin-on-rest';
import DependentInput from 'aor-dependent-input';

const checkAge = (age) => {
    return parseInt(age, 10) > 18;
};

const UserCreate = (props) => (
    <Create {...props}>
        <SimpleForm>
            <DisabledInput source="id"/>
            <NumberInput source="age" step="1" />

            <DependentInput dependsOn="age" resolve={checkAge}>
                <TextInput source="question"/>
            </DependentInput>
        </SimpleForm>
    </Create>
);

export default UserCreate;
like image 168
Wédney Yuri Avatar answered Mar 23 '23 07:03

Wédney Yuri


The record doesn't change until you submit, so your solution doesn't work. I believe the solution is to use formValueSelector, as explained in the redux-form documentation, in a custom connected Input components.

Something like:

// in src/ConditionalInput.js
import React from 'react';
import { connect } from 'react-redux';
import { formValueSelector } from 'redux-form'
import { TextInput } from 'admin-on-rest/lib/mui`;

const ConditionalInput = ({ isDisplayed, condition, children, ...rest }) => 
    isDisplayed 
        ? React.cloneElement(children, rest)
        : null;

function mapStateToProps(state, props) {
    return {
        isDisplayed: props.condition(formValueSelector('record-form')),
    }
}

export default connect(mapStateToProps)(ConditionalInput);

// in your EditView
export default props => 
<Edit {...props}>
    <SimpleForm>
        <DisabledInput source="id"/>
        <NumberInput options={opts} source="age" />
        <ConditionalInput condition={selector => selector('age') > 18}>
            <TextInput options={opts} source="question"/>
        </ConditionalInput>
    </SimpleForm>
</Edit>
like image 25
François Zaninotto Avatar answered Mar 23 '23 08:03

François Zaninotto