Search code examples
react-admin

Manipulate create button path


I want to manipulate the create button shown on a list page based on the filter parameter shown on the same page (and also shown at the address bar). Upon clicking the crete button the user must be redirected to the create page with one of the parameters already filled based on the filter.

I've read the documentation and it shows how to do this within a per-line options (https://marmelab.com/react-admin/doc/2.9/CreateEdit.html#prefilling-a-create-record), but I want to do this globaly, so that the global "create" button, correctly redirects the user to a pre-filled form (like using the adress http://localhost/comments/create?post_id=123 shown on the ducomentation). Is it possible to change the create button behavior based on this?

Can anyone help me?


Solution

  • I've found a workaround based on the docs:

    const CustomActions = ({
        currentSort,
        className,
        resource,
        filters,
        displayedFilters,
        exporter, // you can hide ExportButton if exporter = (null || false)
        filterValues,
        permanentFilter,
        hasCreate, // you can hide CreateButton if hasCreate = false
        basePath,
        selectedIds,
        onUnselectItems,
        showFilter,
        maxResults,
        total,
        ...rest
    }) => {
    
        var currentHref = window.location.href;
        var myRegexp = /filter={%22id%22:%22(\d+)%22}/;
        var regex = currentHref.match(myRegexp); //just got my filtered ID....
        var url = "";
        if (regex) {
            var id = regex[1];
            url = '"id":"' + id + '"';
        }
        return (
            <TopToolbar className={className} {...sanitizeListRestProps(rest)}>
                {filters && cloneElement(filters, {
                    resource,
                    showFilter,
                    displayedFilters,
                    filterValues,
                    context: 'button',
                })}
    
                {/* Add your custom actions */}
                <Button color="primary" size="small" label="" href={`${basePath}/create?source={${url}}`}>
                    <AddIcon /> New
                </Button>
            </TopToolbar>
        )
    
    };
    
    <List {...props} actions={<CustomActions />} >