Search code examples
admin-on-rest

prefill or pass query parameters to child resource


How I can get access to query parameters in child resource create form?

For example if I want to have a button on parent resource edit page which redirects to /childresource/create?parentid=123 and then on child resource create form we have <SelectInput source="parentid" /> and I want this to be preselected?

Is it somehow possible already? Would it be better with custom react routing for example to /parent/123/addchild and have whole custom create component or maybe just customer selectinput component?

I already have functional create page for child but it would be really nice to somehow prefill values.


Solution

  • Answer to your second question:

    ProductSelect.defaultProps = {
      location: PropTypes.object.isRequired,
    };
    
    // This is the component exported and known by admin-on-rest, not ProductSelect
    const EnhancedProductSelect = withRouter(ProductSelect);
    
    // Hence, this is the one which needs a defaultProp for addField
    EnhancedProductSelect.defaultProps = {
      addField: true
    };
    
    export default EnhancedProductSelect;
    

    Does this help for the first question ?

    https://codesandbox.io/s/pp0o4x40p0

    The relevant code parts are:

    • the CreateCommentButton component inside src/posts.js
    • the CommentCreate component inside src/comments.js (note how we set the defaultValue prop on SimpleForm)