Search code examples
react-admin

How to use on reference input to related filed in react-admin?


I'm using react-admin.

I have 3 resources: schools, teachers and classes

  • Each school has its teachers and its classes
  • Each class has a teacher from its school

In creations of class one of the inputs is a teacher, it is need to be a reference type but not to all the teachers only for those who belong to the school of this class.

How should I support it?

How to pass the school_id to the reference input?

Thank you!


Solution

  • This is explained in the documentation: https://marmelab.com/react-admin/Inputs.html#referenceinput

    In summary:

    / you can filter the query used to populate the possible values. Use the
    // `filter` prop for that.
    <ReferenceInput
        source="teacher_id"
        reference="teachers"
        filter={{ school_id: values.school_id }}
    >
        <SelectInput optionText="name" />
    </ReferenceInput>
    

    You may wonder how you can get this school_id: https://marmelab.com/react-admin/Inputs.html#linking-two-inputs

    import { useFormState } from 'react-final-form';
    
    const TeacherInput = () => {
        const { values } = useFormState();
    
        return (
            <ReferenceInput
                source="teacher_id"
                reference="teachers"
                filter={{ school_id: school_id: values.school_id }}
            >
                <SelectInput optionText="name" />
            </ReferenceInput>
        );
    }