Pnpjs: Adding a custom view to a list doesn't add all columns

Created on 3 Sep 2018  路  2Comments  路  Source: pnp/pnpjs

I'm creating a list with an allready existing content type and then I'm trying to add a custom view with the columns from that content type.

The problem is that the view gets created but it only contains some of the columns and it is random witch columns gets added when i run the function.

Here's the code that creates the list with existing content type and adds the view with the specified columns.

`
private createList(title: string, description: string): void {

let spWeb = new Web(this.context.pageContext.web.absoluteUrl);
let spListTitle = title;
let spListDescription = description;
let spListTemplateId = 100;
spWeb.lists.add(spListTitle, spListDescription, spListTemplateId, true).then(spList => {
  spList.list.contentTypes.addAvailableContentType('0x0100F7F5B4DDB6E94651A406BFDBF935F83C').then((list) => {


    spList.list.views.add("My New View 4", false, {
      RowLimit: 20,
      DefaultView: true,
      ViewQuery: "<OrderBy><FieldRef Name='Modified' Ascending='False' /></OrderBy>",
    }).then((v) => {
      // manipulate the view's fields
      v.view.fields.removeAll().then(_ => {
        v.view.fields.add("AnniversariesTitle"),
        v.view.fields.add("AnniversariesPerson"),
        v.view.fields.add("AnniversariesDate")
      });
  });
  });
});

}`

Thanks in advance.

code question

All 2 comments

Hi @fkgdmk,

This is SharePoint API nuance. Fields can't be added to a view in parallel, only one after another.

(async () => {
  await v.view.fields.removeAll();
  await v.view.fields.add("AnniversariesTitle");
  await v.view.fields.add("AnniversariesPerson");
  await v.view.fields.add("AnniversariesDate");
})();

UPD: This approach can be used to add a number of fields in one call.

Let me even copy some part of the code in here:

const batch = sp.web.createBatch();

const fields = ['ID', 'LinkTitle', 'Author', 'Created', 'Editor', 'Modified'];

view.fields.inBatch(batch).removeAll();
fields.forEach(fieldName => {
    view.fields.inBatch(batch).add(fieldName);
});

batch.execute().then(_ => console.log('Done')).catch(console.log);

Thank you very much.

Was this page helpful?
0 / 5 - 0 ratings