SharePoint/PnP-JS-Core

How to add items in batch in sharepoint hosted app cross domain?

Closed this issue ยท 11 comments

I tried but it is not working at all.

var batch = $pnp.sp.web.createBatch();

for (i = 0; i < 2; i++) {
  $pnp.sp.crossDomainWeb(JobList.SPAppWebUrl, JobList.SPHostUrl).lists.getByTitle('VPS_Job')
    .items.inBatch(batch).add({ Title: "Batch" + i }).then(b => {
      console.log(b);
    });
}

batch.execute().then(d => console.log("Done"));

The batch object for SP Hosted Add-In should be created in the context of crossDomainWeb I guess.
As you are mixing ES5 and ES6, I made an assumption that you have a transpilation build step so the further code is in ES next for the simplicity purposes. Also, I highly recommend providing itemEntityTypeFullName as the second parameter for item creation batches in a list, it reduces requests number.

(async () => {
  const web = pnp.sp.crossDomainWeb(JobList.SPAppWebUrl, JobList.SPHostUrl);
  const batch = web.createBatch();
  const list = web.lists.getByTitle('VPS_Job');
  const itemEntityTypeFullName = await list.getListItemEntityTypeFullName();
  for (var i = 0; i < 2; i += 1) {
    list.items.inBatch(batch)
      .add({ Title: `Batch ${i}` }, itemEntityTypeFullName);
  }
  batch.execute().then(() => console.log("Done"));
})();

Thanks for reply, I tried the code, it says 'Done' but there is no item created in list.
I would like to create items inside different folders?

The individual catch for add promises can be used to track what might be wrong.

I would like to create items inside different folders?

Please dont forget using search on the issues and wiki pages. Most of these questions have been asked and answered a number of times. I.e. this one

Regards batch and move to folders: it can't be done in one batch call in REST API. Item can't be created in a folder with REST, an item is created in a list's root folder then moved to a desired folder. Example:

(async () => {

  const web = new pnp.Web(_spPageContextInfo.webAbsoluteUrl);
  const batch1 = web.createBatch();
  const batch2 = web.createBatch();
  let errors: any = [];

  const listUri = `${_spPageContextInfo.webServerRelativeUrl}/Lists/ListA`;
  const list = web.getList(listUri);
  const itemEntityTypeFullName = await list.getListItemEntityTypeFullName();

  const items = [{
    payload: { Title: 'Item 1' },
    folder: '/Folder 1'
  }, {
    payload: { Title: 'Item 2' },
    folder: '/Folder 2'
  }];

  for (const data of items) {
    list.items.inBatch(batch1)
      .add(data.payload, itemEntityTypeFullName)
      .then(item => {
        data['item'] = item;
        web.getFileByServerRelativeUrl(`${listUri}/${item.data.Id}_.000`)
          .inBatch(batch2)
          .moveTo(`${listUri}${data.folder}/${item.data.Id}_.000`)
          .catch(error => {
            errors.push({ action: 'move', item: data, error });
          });
      })
      .catch(error => {
        errors.push({ action: 'add', item: data, error });
      });
  }

  await batch1.execute();
  await batch2.execute();

  return { items, errors };
  
})().then(console.log);

image

list is having unique permission over folders. It can not move item as user only have access to specific folder under list.

Left a comment in the related issue.

I consider the initial question to be answered. The following question with folders is a separate topic, now connected via the link.
Going to close this particular issue. Feel free to reopen if crossDomainWeb/batch questions still remain.

no way to add items in folder, tried but no success. using jsom only

@ahsanranjha,

If you know the REST API way of creating an item in a folder directly skipping moveTo step, I would be glad to hear it, notwithstanding it's highly likely that there is no such feasibility with the exception of SPO and modern AddValidateUpdateItemUsingPath which is not implemented in PnPjs yet. Then also, I'm not sure that you're using SharePoint Online and that your SharePoint installation supports the new method.

So, feel free using JSOM/SOAP/custom web services instead, as far as you can't create in a root folder then move. Also, feel free addressing questions, not related to the PnPjs library, not as issues in this repo, but to the community, i.e. Tech Community.

New Issue is AddValidateUpdateItemUsingPath return itemId 0 for newly created item, i need this id to process add task item.

I have successfully tested AddValidateUpdateItemUsingPath using following line of code.

CreateItemWithPayload: function () {

            retrieveFormDigest();
            var executor = new SP.RequestExecutor(JobList.SPAppWebUrl);
            var operationUri = JobList.SPAppWebUrl + "/_api/SP.AppContextSite(@target)/web/lists/GetByTitle('VPS_Job')/AddValidateUpdateItemUsingPath()?@target='" + JobList.SPHostUrl + "'";
            var bodyContent = JSON.stringify(
                {
                    "listItemCreateInfo": {
                        //'__metadata': { 'type': 'SP.Data.RESTCreatedListListItem' },
                        "__metadata": {
                            "type": "SP.ListItemCreationInformationUsingPath"
                        },
                        "FolderPath": {
                            "__metadata": {
                                "type": "SP.ResourcePath"
                            },
                            "DecodedUrl": "/Plus/Lists/VPS_Job/CR00001"
                        }
                    },
                    "formValues": [{ "FieldName": "Title", "FieldValue": "Test 1", "HasException": false, "ErrorMessage": null }],
                    "bNewDocumentUpdate": false,
                    "checkInComment": null
                }
            );

            executor.executeAsync({
                url: operationUri,
                method: "POST",
                headers: {
                    "Accept": "application/json;odata=verbose",
                    "content-type": "application/json;odata=verbose",
                    "content-length": bodyContent.length,
                    "X-RequestDigest": formDigestValue, 
                },
                body: bodyContent,
                success: function (data) {
                    var jsonObject = JSON.parse(data.body);
                    $("#message").text("Operation completed!");
                },
                error: function (data, errorCode, errorMessage) {
                    var jsonObject = JSON.parse(data.body);
                    var errMsg = "Error: " + jsonObject.error.message.value;
                    $("#error").text(errMsg);
                }
            });

        }

image

Great. Thanks, I got Item Id. it Required Data parsing steps to bind it. life is not easy here.