Delete all documents which have no parent when opening new form

Hello,
I hope you can help me with this. I have included a library in my form.
However, if a document is uploaded and the form is not saved, the document is displayed again the next time the form is opened.
Is there a way to delete all existing documents without parent from this user the next time the form is opened?
I currently have a view that only shows all documents of a user.

Best regards
Sternchen

Hello @Sternchen,

You can delete document from the Document Library using PnPjs function:

pnp.sp.web.getFileByServerRelativeUrl("/sites/test/Documents/presentation.pptx").delete();

You can delete all files that are displayed in List or Library control like so:

var docuemnts = fd.control('SPDataTable1').widget.dataSource.data();

docuemnts.forEach(doc => 
    pnp.sp.web.getFileByServerRelativeUrl(doc.FileRef).delete()
                 )

How can I intercept beforehand that it only executes when documents are there?
Currently I get the error message from undefined. For example, with users who open the form for the very first time. No documents can be displayed for them.
Even if there is a document there, this error message comes up.

I have used this code as suggested. However, the message with undefined always comes up.
What is the reason for this and how do I fix it?

Dear @Sternchen,
The control should be ready before it can be used to retrieve values, like this:

fd.spRendered(function(){
    fd.control('SPDataTable1').ready().then(function(dt) {
        var documents = fd.control('SPDataTable1').widget.dataSource.data();
        documents.forEach(doc => 
            pnp.sp.web.getFileByServerRelativeUrl(doc.FileRef).delete()
        );
    });
});

Thanks for the help.
The element is now deleted, but it is still displayed.

I added this after your function.

fd.control('SPDataTable1').refresh();

Seems like it is working. Do you have another idea instead of the refresh?

Dear @Sternchen,
No, it's good, especially if it's working :slight_smile: My code was just to delete documents, but yes, you need to refresh the control to see the results.

Thank you for your help. :slight_smile:

1 Like