Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can i print only selected rows in my MUI DataGrid pro? #9824

Closed
2 tasks done
bogdancbs opened this issue Jul 28, 2023 · 21 comments · Fixed by #10084
Closed
2 tasks done

How can i print only selected rows in my MUI DataGrid pro? #9824

bogdancbs opened this issue Jul 28, 2023 · 21 comments · Fixed by #10084
Labels
component: data grid This is the name of the generic UI component, not the React module! customization: logic Logic customizability enhancement This is not a bug, nor a new feature feature: Export plan: Pro Impact at least one Pro user support: commercial Support request from paid users

Comments

@bogdancbs
Copy link

Order ID or Support key 💳 (optional)

68255

Duplicates

  • I have searched the existing issues

Latest version

  • I have tested the latest version

The problem in depth 🔍

I have a mui datagrid pro table and now when i export to print it prints all rows. How can i print only selected rows (checkbox).
If table is filtered it prints filtered ones, it's ok, but if i select it prints all.

` <DataGridPro
rows={dosare}
onRowHover={handleRowHover}
checkboxSelection
checkboxSelectionVisibleOnly={true}
disableSelectionOnClick={true}
onSelectionModelChange={(ids) => {
const selectedIDs = new Set(ids);
const selectedRows = dosare.rows.filter((row) =>
selectedIDs.has(row.id),
);
setSelectedRows(selectedRows);
}}
onRowSelectionModelChange ={handleSelectionModelChange}
onFilterModelChange={handleFilterChange}
columns={columns}
pageSize={20}
rowsPerPageOptions={[10, 20, 50, 100]}
pagination
paginationMode="client"
loading={loadingIndicator}
components={{

        headerFilterMenu: null, 
        Toolbar: () => (
          <>
            {isLoading ? (
              <div style={{ width: '100%', marginBottom: 8 }}>
                
                <CustomGridToolbarContainer
                accesoriiFiltru={accesoriiFiltru}
                setAccesoriiFiltru={setAccesoriiFiltru}
                monitorizatFiltru={monitorizatFiltru}
                setMonitorizatFiltru={setMonitorizatFiltru}
              />
              <LinearProgress /> 
              </div>
              
            ) : (
              <div>
              <CustomGridToolbarContainer
                accesoriiFiltru={accesoriiFiltru}
                setAccesoriiFiltru={setAccesoriiFiltru}
                monitorizatFiltru={monitorizatFiltru}
                setMonitorizatFiltru={setMonitorizatFiltru}
              /> 

              </div>
              
            )}
          </>
        ),
      }}
      componentsProps={{
        toolbar: {
          csvOptions: {
            fileName: 'nume-fisier',
            delimiter: ',',
            utf8WithBom: true,
          },
        },
      }}
      localeText={{ 
        ...roRO.components.MuiDataGrid.defaultProps.localeText, 
        headerFilterOperatorContains: 'Filtrare rapidă',
        filterPanelRemoveAll: 'Resetare filtre',
        toolbarExport: 'Exportare',
        toolbarExportLabel: 'Exportare',
        toolbarExportCSV: 'În format CSV',
        toolbarExportPrint: 'Imprimare',
        toolbarExportExcel: 'În format Excel',
      }}
    
      density="compact"

      initialState={{
        pagination: { paginationModel: { pageSize: 15 } },
        columns: {
          columnVisibilityModel: {
            dataactualizare: false,
            titlefinalizat: false,
            datacreare: false,
            parteadversa: false,
            adresaclientdosar: false,
            adresaparteadversa: false,
            calitateclientdosar: false,
            calitateparteadversa: false,
            CUIclientdosar: false,
            CUIparteadversa: false,
            RECOMclientdosar: false,
            RECOMparteadversa: false,
            sentintaprimita: false,
            nrstadii: false,
            materiedosar: false,
            txtum: false,
            solutie: false,
            dosarinstanta: false,
            descsolutie: false,
            comentarii: false,
            legislatie: false,
            staredosar: false,
            emailuser: false,
            denumireuser: false,
            detaliiuser: false,
            telefonuser: false,
            accesorii: false,
            monitorizat: false,
          },
        },
      }}
      onRowClick={handleRowClick}
      onCellClick={handleRowClick}
      getRowClassName={(params) =>
        params.indexRelativeToCurrentPage % 2 === 0 ? 'Mui-even' : 'Mui-odd'
      }
      unstable_headerFilters 
   
    /> `

Your environment 🌎

`npx @mui/envinfo` System: OS: Windows 10 10.0.22621 Binaries: Node: 14.21.3 - C:\Program Files\nodejs\node.EXE Yarn: Not Found npm: 6.14.18 - C:\Program Files\nodejs\npm.CMD Browsers: Chrome: 114.0.5735.248 Edge: Spartan (44.22621.2070.0), Chromium (115.0.1901.183) npmPackages: @emotion/react: ^11.10.6 => 11.11.1 @emotion/styled: ^11.10.6 => 11.11.0 @mui/base: 5.0.0-beta.4 @mui/core-downloads-tracker: 5.14.0 @mui/icons-material: ^5.11.11 => 5.13.7 @mui/lab: ^5.0.0-alpha.133 => 5.0.0-alpha.134 @mui/material: ^5.14.0 => 5.14.0 @mui/private-theming: 5.13.7 @mui/styled-engine: 5.13.2 @mui/styled-engine-sc: ^5.11.11 => 5.12.0 @mui/styles: ^5.14.1 => 5.14.1 @mui/system: 5.13.5 @mui/types: 7.2.4 @mui/utils: 5.13.1 @mui/x-data-grid: ^6.0.1 => 6.9.2 @mui/x-data-grid-pro: ^6.6.0 => 6.8.0 @mui/x-license-pro: 6.6.0 @types/react: 18.2.14 react: ^18.2.0 => 18.2.0 react-dom: ^18.2.0 => 18.2.0 styled-components: ^5.3.9 => 5.3.11
@bogdancbs bogdancbs added status: waiting for maintainer These issues haven't been looked at yet by a maintainer support: commercial Support request from paid users labels Jul 28, 2023
@zannager zannager added component: data grid This is the name of the generic UI component, not the React module! plan: Pro Impact at least one Pro user labels Jul 28, 2023
@cherniavskii
Copy link
Member

Hi @bogdancbs
Currently, changing the exported rows in Print export is not supported.
I'm marking this issue as an enhancement request 👍

Could you clarify, what your expectations are for Print export in the following scenarios:

  1. No rows selected
  2. Some selected rows are filtered out by the applied filters

Thanks!

@cherniavskii cherniavskii added feature: Export customization: logic Logic customizability enhancement This is not a bug, nor a new feature and removed status: waiting for maintainer These issues haven't been looked at yet by a maintainer labels Jul 31, 2023
@bogdancbs
Copy link
Author

Hello, @cherniavskii
ok, is there an estimation in time when this enhancements will be added? :)

  1. when no rows selected, print all rows from all pages.
  2. when filters applied and no rows selected print all results filtered
  3. when some rows selected from a page - print only that rows.

thanks.

@MBilalShafi
Copy link
Member

MBilalShafi commented Aug 29, 2023

@bogdancbs It seems there another issue talking about the same thing: #9993
There has been a PR open already, if you can please test it out here and provide your feedback if you want. It seems to honor both the selected and filtered rows with the print export.

Thanks

@zreecespieces
Copy link
Contributor

I have just updated my PR that @MBilalShafi mentioned and that will fix this issue. Hopefully that will be reviewed and merged in shortly.

@bogdancbs
Copy link
Author

works great! thnx

@bogdancbs
Copy link
Author

Hello @MBilalShafi, any new updates when it will be merged?

@zreecespieces
Copy link
Contributor

@bogdancbs there's still discussion on the PR, feel free to go over to it and leave your input about why this feature should be included and whether or not the current behavior is expected. I personally found it confusing that the print export does not export only selection as that's the behavior of all other export options.

@zreecespieces
Copy link
Contributor

zreecespieces commented Sep 21, 2023

@bogdancbs the PR has been merged and will be included in the next release (6.15.0) which should be sometime in this upcoming week. Stay tuned!

Also note that to prevent breaking changes it will still export all rows by default, but now there is a solution/workaround to export only selected rows via print. An example of how to do this has been added to the documentation which you'll be able to find under this section once it goes live.

@bogdancbs
Copy link
Author

Thank you! Looking forward to test.

@MBilalShafi
Copy link
Member

Yes, it should be available in the next release. Until then, if you want, you can experiment with the API. Here's the API documentation link for the PR: https://deploy-preview-10084--material-ui-x.netlify.app/x/react-data-grid/export/#customizing-the-rows-to-export

Feel free to check it out and possibly share some feedback!

@zreecespieces
Copy link
Contributor

@bogdancbs it's been released! The latest version 6.15.0 has this new feature. Here's a link to the documentation showing how to export only selected rows via print.

@bogdancbs
Copy link
Author

@zreecespieces thank you, i will look in to it to see how i can use

@bogdancbs
Copy link
Author

i don't understand what i'm doing wrong.
here is my datagrid:
` <DataGridPro
rows={dosare}
onRowHover={handleRowHover}
checkboxSelection
checkboxSelectionVisibleOnly={false}
disableSelectionOnClick={true}
onSelectionModelChange={(ids) => {
const selectedIDs = new Set(ids);
const selectedRows = dosare.rows.filter((row) =>
selectedIDs.has(row.id),
);
setSelectedRows(selectedRows);
}}
onRowSelectionModelChange ={handleSelectionModelChange}
onFilterModelChange={handleFilterChange}
columns={columns}
pageSize={20}
rowsPerPageOptions={[10, 20, 50, 100]}
pagination
paginationMode="client"
loading={loadingIndicator}
components={{

        headerFilterMenu: null, 
        Toolbar: () => (
          <>
            {isLoading ? (
              <div style={{ width: '100%', marginBottom: 8 }}>
                
                <CustomGridToolbarContainer
                accesoriiFiltru={accesoriiFiltru}
                setAccesoriiFiltru={setAccesoriiFiltru}
                monitorizatFiltru={monitorizatFiltru}
                setMonitorizatFiltru={setMonitorizatFiltru}
              />
              <LinearProgress /> 
              </div>
              
            ) : (
              <div>
              <CustomGridToolbarContainer
                accesoriiFiltru={accesoriiFiltru}
                setAccesoriiFiltru={setAccesoriiFiltru}
                monitorizatFiltru={monitorizatFiltru}
                setMonitorizatFiltru={setMonitorizatFiltru}
              /> 

              </div>
              
            )}
          </>
        ),
      }}
      componentsProps={{
        row: {
          onContextMenu: handleContextMenu,
          style: { cursor: "context-menu" }
        }, 
        toolbar: {
          csvOptions: {
            fileName: 'nume-fisier',
            delimiter: ',',
            utf8WithBom: true,
          },
        },
      }}
      slots={{ toolbar: CustomGridToolbarContainer }}
      slotProps={{
        toolbar: { printOptions: { getRowsToExport: getSelectedRowsToExport } },
      }}
      localeText={{ 
        ...roRO.components.MuiDataGrid.defaultProps.localeText, 
        headerFilterOperatorContains: 'Filtrare rapidă',
        filterPanelRemoveAll: 'Resetare filtre',
        toolbarExport: 'Exportare',
        toolbarExportLabel: 'Exportare',
        toolbarExportCSV: 'În format CSV',
        toolbarExportPrint: 'Imprimare',
        toolbarExportExcel: 'În format Excel',
      }}
    
      density="compact"

      initialState={{
        pagination: { paginationModel: { pageSize: 15 } },
        columns: {
          columnVisibilityModel: {
            numarintern: false,
            dataactualizare: false,
            titlefinalizat: false,
            datacreare: false,
            parteadversa: false,
            adresaclientdosar: false,
            adresaparteadversa: false,
            calitateclientdosar: false,
            calitateparteadversa: false,
            CUIclientdosar: false,
            CUIparteadversa: false,
            RECOMclientdosar: false,
            RECOMparteadversa: false,
            sentintaprimita: false,
            nrstadii: false,
            materiedosar: false,
            txtum: false,
            solutie: false,
            dosarinstanta: false,
            descsolutie: false,
            comentarii: false,
            legislatie: false,
            staredosar: false,
            emailuser: false,
            denumireuser: false,
            detaliiuser: false,
            telefonuser: false,
            accesorii: false,
            monitorizat: false,
          },
        },
      }}
      onRowClick={handleRowClick}
      onCellClick={handleRowClick}
      getRowClassName={(params) =>
        params.indexRelativeToCurrentPage % 2 === 0 ? 'Mui-even' : 'Mui-odd'
      }
      unstable_headerFilters 
   
    /> `

here is the custom component CustomGridToolbarContainer:
`const CustomGridToolbarContainer = ({
accesoriiFiltru,
setAccesoriiFiltru,
monitorizatFiltru,
setMonitorizatFiltru,
printOptions,
}) => {
return (


<Box sx={{ display: 'flex', alignItems: 'left', mr: 1 }}>



<GridToolbarExport
csvOptions={{
fileName: 'JuristPro - CSV Export lista dosare',
delimiter: ',',
utf8WithBom: true,
}}
/>

<Box sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
<Box sx={{ display: 'flex', alignItems: 'center', mr: 2 }}>
<Typography variant="subtitle2" sx={{ mr: 1 }}>
Accesorii dosare

<FormControl variant="outlined" size="small" sx={{ mr: 2 }}>
Toate dosarele
<Select
fullWidth
style={{ minWidth: '150px' }}
labelId="accesorii-select-label"
id="accesorii-select"
value={accesoriiFiltru}
onChange={handleAccesoriiChange}
label="Toate dosarele"
>
Toate dosarele
Cu accesorii
Fără accesorii



<Box sx={{ display: 'flex', alignItems: 'center' }}>
<Typography variant="subtitle2" sx={{ mr: 1 }}>
Dosare monitorizate


Toate dosarele
<Select
fullWidth
size='small'
style={{ minWidth: '150px' }}
labelId="monitorizat-select-label"
id="monitorizat-select"
value={monitorizatFiltru}
onChange={handleMonitorizatChange}
label="Toate dosarele"
>
Toate dosarele
Doar cele monitorizate
Nemonitorizate


      <Box sx={{ display: 'flex', alignItems: 'center' }}>

      </Box>

    </Box>
  </FlexContainer>
</GridToolbarContainer>

);
};`

and const getSelectedRowsToExport
`const getSelectedRowsToExport = ({
apiRef,
}: GridPrintGetRowsToExportParams): GridRowId[] => {
const selectedRowIds = selectedGridRowsSelector(apiRef);
if (selectedRowIds.size > 0) {
return Array.from(selectedRowIds.keys());
}

return gridFilteredSortedRowIdsSelector(apiRef);
};
`

and import { DataGridPro, GridToolbar, GridToolbarContainer, GridToolbarExport, GridToolbarColumnsButton, GridToolbarDensitySelector, GridToolbarFilterButton, useGridSlotComponentProps, roRO, getGridStringOperators, GridColDef, GridFilterOperator, GridPrintGetRowsToExportParams, gridFilteredSortedRowIdsSelector, selectedGridRowsSelector, GridRowId, } from '@mui/x-data-grid-pro'; i don't understand what i'm doing wrong

@zreecespieces
Copy link
Contributor

@bogdancbs It doesn't look like you're passing the printOptions through the CustomGridToolbarContainer down to the GridToolbarExport Make sure you are like:

<GridToolbarExport csvOptions={{ fileName: 'JuristPro - CSV Export lista dosare', delimiter: ',', utf8WithBom: true, }} printOptions={printOptions} />

If you're still having trouble please create a codesandbox with a basic recreation of this for me to help you troubleshoot.

@bogdancbs
Copy link
Author

@zreecespieces Thank you!! it worked!

@zreecespieces
Copy link
Contributor

@bogdancbs Awesome! I'm glad to be able to help you get this feature working in your application!

@bogdancbs
Copy link
Author

@zreecespieces i just realized that my context menu after adding slots and slots props dose not work anymore. Is there another way?
`components={{

        headerFilterMenu: null, 
        Toolbar: () => (
          <>
            {isLoading ? (
              <div style={{ width: '100%', marginBottom: 8 }}>
                
                <CustomGridToolbarContainer
                accesoriiFiltru={accesoriiFiltru}
                setAccesoriiFiltru={setAccesoriiFiltru}
                monitorizatFiltru={monitorizatFiltru}
                setMonitorizatFiltru={setMonitorizatFiltru}
              />
              <LinearProgress /> 
              </div>
              
            ) : (
              <div>
              <CustomGridToolbarContainer
                accesoriiFiltru={accesoriiFiltru}
                setAccesoriiFiltru={setAccesoriiFiltru}
                monitorizatFiltru={monitorizatFiltru}
                setMonitorizatFiltru={setMonitorizatFiltru}
              /> 

              </div>
              
            )}
          </>
        ),
      }}
      
      slots={{ toolbar: CustomGridToolbarContainer }}
      slotProps={{
        toolbar: { printOptions: { getRowsToExport: getSelectedRowsToExport } },
      }}
      componentsProps={{
        row: {
          onContextMenu: handleContextMenu,
          style: { cursor: "context-menu" }
        }, 
        toolbar: {
          csvOptions: {
            fileName: 'nume-fisier',
            delimiter: ',',
            utf8WithBom: true,
          },
        },
      }}`

@bogdancbs
Copy link
Author

@cherniavskii hello, can you help me?

@cherniavskii
Copy link
Member

@bogdancbs You should pass a React component with a stable reference to the Toolbar slot.
From what I can tell, you're passing an inline function, so from React's perspective, you're passing a different component each time, which unmounts the component and mounts it again instead of the normal React lifecycle.

@bogdancbs
Copy link
Author

@cherniavskii thanks, i used solts only instead of components and now it works. Thanks

@cherniavskii
Copy link
Member

@cherniavskii thanks, i used solts only instead of components and now it works. Thanks

This is odd, just changing components to slots shouldn't make a difference. But it's good to hear that the issue is resolved 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
component: data grid This is the name of the generic UI component, not the React module! customization: logic Logic customizability enhancement This is not a bug, nor a new feature feature: Export plan: Pro Impact at least one Pro user support: commercial Support request from paid users
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants