January 30, 2020

SharePoint: Setting list view specific persisted spcolumnsize programmatically

Problem

I needed to set default list view column widths programmatically on SharePoint Online modern list. I was using PnPjs to create and configure the list.

Thoughts

In modern SPO list view you can change column width, it is then temporarily stored in browser Local Storage as spcolumnsize-unsaved-VIEWGUID. However, you also have the option of saving it into View somehow, as asterisk (*) appears next to view name on SharePoint and you can "Save View As" to persist the column width somewhere. After saving the view even if you remove the spcolumnsize-unsaved-VIEWGUID Local Storage key, and refresh the page, it comes back as spcolumnsize-VIEWGUID, so clearly it is stored somewhere in SharePoint.

Solution

Column widths are persisted in ListViewXml view property inside ColumnWidth element as FieldRef elements. Do note that the FieldRef Names must be column display names, NOT internal field names. I didn’t implement fancy XML parsing, just injected the ColumnWidth element at the end just before ending View tag.

// set field widths
let lv: any = await list.defaultView.select('ListViewXml').get();

let lvXml: string = lv.ListViewXml.replace(
'</View>', '<ColumnWidth><FieldRef Name="Column title 1" width="370" /><FieldRef Name="Some other column" width="90" /></ColumnWidth></View>');

await list.defaultView.setViewXml(lvXml);

No comments:

Post a Comment