Sharepoint - SPFX - Listview command - Get current folder

It is pretty easy. Because you know which item is selected, you know url of the file. event.selectedRows[0] holds a lot of information about the selected item. Or you can use query string.

@override
public onExecute(event: IListViewCommandSetExecuteEventParameters): void {
  switch (event.itemId) {
    case 'COMMAND_1':
      {
        var folderUrl: string;

        // Get file url of first selected item
        if (event.selectedRows.length > 0) {
          const fileUrl: string = event.selectedRows[0].getValueByName("FileRef");

          // Trim the file name and you have server relative folder url
          folderUrl = fileUrl.substring(0, fileUrl.lastIndexOf('/'));
        } else {
          // Get url form query string
          folderUrl = this.getFolderUrlFromQueryString();
        }

        Dialog.alert(folderUrl);
        break;
      }
    default:
      throw new Error('Unknown command');
  }
}

private getFolderUrlFromQueryString(): string {
  const id = this.getQueryStringParameter("Id");
  const rootFolder = this.getQueryStringParameter("RootFolder");

  var url = id != null ? id : rootFolder;
  if (url === undefined) {
    // in case of root folder
    url = this.context.pageContext.list.serverRelativeUrl;
  }

  return decodeURIComponent(url);
}

private getQueryStringParameter(paramToRetrieve: string) {
  if (document.URL.indexOf("?") == -1)
    return null;

  var params = document.URL.split("?")[1].split("&");
  var strParams = "";
  for (var i = 0; i < params.length; i = i + 1) {
    var singleParam = params[i].split("=");
    if (singleParam[0].toLowerCase() == paramToRetrieve.toLowerCase())
      return singleParam[1];
  }
}

SPFx has some utility classes to help you get the folder url. Its not available in pageContextInfo or any other page property. However, you can split it from the query string's Id parameter.

Add the below import statement:

import { Log, UrlQueryParameterCollection } from '@microsoft/sp-core-library';

And in your execution logic, use it as:

@override
  public onExecute(event: IListViewCommandSetExecuteEventParameters): void {         

      var queryParameters = new UrlQueryParameterCollection(window.location.href);
      var current_folder_path= url_query_param.getValue("Id") || url_query_param.getValue("RootFolder");

      if (queryParameters.getValue("Id")) {
          var folderUrl = decodeURIComponent(current_folder_path);
          Dialog.alert(`${folderUrl}`);
      }        
  }

End result - in the Shared Document library, have created a folder named Test:

enter image description here

Tags:

Spfx