简体   繁体   中英

Show item data from SelectInput using react-admin

I have a SelectInput with which i select projects. One of the properties of such a project is projectLead . I try to show this property (projectLead) using a TextField . I wrote the following code to achieve this (which doesn't work):

<ReferenceInput label="Project" source="projectId" reference="projects">
    <SelectInput optionText="projectname"/>
</ReferenceInput>
<FormDataConsumer>
    {({formData, ...rest}) => {
        return <ReferenceField label="Projectlead" source="formData.projectId" reference="projects" linkType={false} {...rest}>
            <TextField source="projectLead" />
        </ReferenceField>
    }}
</FormDataConsumer>

In fact, I should have this property already on the client since it was loaded using the ReferenceInput . Is there any way I can access the full selected object of the SelectInput ?

Since I could not find a solution accessing the property directly I used the above code to fetch it from the server. This however only shows a loading bar forever. In the network tab from Chrome, I can see that the call to the backend has successfully completed and returned the expected data.

I found a work around by creating the following component:

import React from 'react';
import {connect} from 'react-redux'
import get from 'lodash.get';
import TextField from '@material-ui/core/TextField';
import { addField, FieldTitle } from 'ra-core';
import PropTypes from 'prop-types';

class FormDataConsumerField extends React.Component {
    render() {
        return (
            <TextField
                disabled
                margin="normal"
                value={get(this.props.selectedProject, this.props.source) ? get(this.props.selectedProject, this.props.source) : ""}
                label={<FieldTitle label={this.props.label} source={this.props.source} resource={this.props.resource} />}
                className={this.props.className}
                classes={this.props.classes}
                {...this.props.options}
            />
        );
    }
}

FormDataConsumerField.propTypes = {
    classes: PropTypes.object,
    className: PropTypes.string,
    label: PropTypes.string,
    options: PropTypes.object,
    record: PropTypes.object,
    resource: PropTypes.string,
    source: PropTypes.string,
};

const mapStateToProps = (state, props) => ({
    selectedProject: state.admin.resources[props.resource] ? state.admin.resources[props.resource].data[props.id] : null
});

export default addField(connect(mapStateToProps)(FormDataConsumerField));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM