4

So the code below works great, but I'm using a ReferenceField just to fetch the record selected in the ReferenceInput. This feels a bit odd.

Any advice on how I SHOULD do this ?

My use case :

// js-ish description of my datamodel

{ id, name, needsMeta } = Role

{ id, name } = RoleMeta

{ id, roleId, userId, metaId } = AssignedRole

I'm building the Create / Edit Form for the AssignedRole model.

I want to show the ReferenceInput for metaId only if the selected Role needs a meta (needsMeta)

<ReferenceInput
    source="roleId"
    reference="role"
    sort={{
        field: 'id',
        order: 'ASC'
    }}
>
    <AutocompleteInput optionText="name" />
</ReferenceInput>
<FormDataConsumer>
    {({ formData, ...rest }) => (
        formData.roleId &&
        <ReferenceField
            source="roleId"
            record={{roleId: formData.roleId}}
            reference="role"
            basePath={rest.basePath}
            resource={rest.resource}
            linkType={false}
        >
            <FunctionField render={roleRecord => {
                if(!roleRecord.needsMeta){
                    formData.metaId = null;
                }
                return roleRecord && roleRecord.needsMeta && (
                    <ReferenceInput
                        source="metaId"
                        reference="rolemeta"
                        sort={{
                            field: 'id',
                            order: 'ASC'
                        }}
                        {...rest}
                    >
                        <AutocompleteInput optionText="name" />
                    </ReferenceInput>
                );
            }} />
        </ReferenceField>
    )}
</FormDataConsumer>
Armel Larcier
  • 15,747
  • 7
  • 68
  • 89

0 Answers0