bugfix> javascript > 投稿

次の関数にはcurrentBillCyclePathパラメーターがあり、これを使用して、クエリの実行後に受け取った要素の一部をフィルターで除外する必要があります。 問題はそれです

while内では、その値はもはや定義されていません。しかし、メソッドが開始すると、値はそこにあります。

基本的に私は取得する必要があります: listItemValues.FileRef.split("/")[4]; そして、それが currentBillCyclePath と一致する場合 、それから配列に追加しません。

function GetRelatedBillingDocumentsFromList(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
            $log.info("Retrieving related billing documents for bill cycle with name [" + currentBillCyclePath + "]");                  
            var deferred = $q.defer();
            var webUrl = _spPageContextInfo.webAbsoluteUrl;
            selectProperties = selectProperties.concat("ContentTypeId");
            var viewFields = spService.ConvertSelectPropertiesToViewFields(selectProperties);
            // query must return the documents for the same client but in other bill cycles not the current one
            var camlQuery = '<View Scope="RecursiveAll">' +   viewFields + 
                    '<Query>' +
                        '<Where>' +
                            '<And>' +
                                '<Eq>' +
                                    '<FieldRef Name="ClientCode" />' +
                                    '<Value Type="Text">'+ clientCode + '</Value>' +
                                '</Eq>' +
                                '<Neq>' +
                                    '<FieldRef Name="ContentType" />' +
                                    '<Value Type="Computed">Bill Cycle</Value>' +
                                '</Neq>' +
                            '</And>' +
                        '</Where>' +
                    '</Query>' +
                '</View>';
            var billCyclesListId = "{c23bbae4-34f7-494c-8f67-acece3ba60da}";                    
            spService.GetListItems(billCyclesListId, camlQuery, selectProperties)
            .then(function(listItems) {                 
                var listItemsWithValues = [];
                if(listItems) {
                    var enumerator = listItems.getEnumerator();
                    var promises = [];
                    while (enumerator.moveNext()) {
                        var listItem = enumerator.get_current();
                        var listItemValues = [];                                
                        selectProperties
                        .forEach(function(propertyName) {                               
                            var value = listItem.get_item(propertyName);
                            if(propertyName === "JobCodesMulti"){
                                jobvalue = "";
                                value.forEach(function(jobvalues){
                                    jobvalue+= jobvalues.get_lookupValue() +";";
                                })
                                listItemValues[propertyName] = jobvalue;
                            }else{
                                listItemValues[propertyName] = value;
                            }   
                        });
                        listItemsWithValues.push(listItemValues);
                    }
                    var promises = listItemsWithValues.map(addContentType);
                    $q.all(promises).then(youCanUseTheData);
                    function youCanUseTheData(){
                        /*
                        At this point, each listItem holds the 'Document Type' info
                        */
                        listItemsWithValues.forEach(function(listItem) {
                            var fileDirRef = listItem["FileRef"];
                            var id = listItem["ID"];
                            var title = listItem["Title"];
                            var serverUrl = _spPageContextInfo.webAbsoluteUrl.replace(_spPageContextInfo.webServerRelativeUrl,"");                          
                            var dispFormUrl = serverUrl + "/sites/billing/_layouts/15/DocSetHome.aspx?id="+fileDirRef;
                            var parentLink = listItem["FileRef"];
                            arrayofstrings = parentLink.split("/");
                            var billCycleFolderName = arrayofstrings[arrayofstrings.length-2];
                            arrayofstrings.pop();
                            var hyperLink = '<a href="' + arrayofstrings.join('/') + '">' + billCycleFolderName + '</a>';                           
                            listItem["Bill Cycle"] = hyperLink; 
                            listItemsWithValues["Document Type"] = getContentTypeOfCurrentItem(listItem.ID.toString());
                        });
                        var enhancedListItemValues = spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions);                       
                        deferred.resolve(listItemsWithValues);
                    }
                }   
            })
            .catch (function (message) {
                deferred.reject();
            });
            return deferred.promise;
        }

更新:構文エラー

更新2:GetData関数を追加

function GetData(billCyclePath, clientCode, jobCodes, engagementCode) {             
                var enhanceFunctions = [
                    function(searchResultRow) {
                        return spService.AddHyperLinkOnFields(searchResultRow, config.HyperLinks);
                    },
                    function(searchResultRow) {
                        return spService.AddPresenceOnFields(searchResultRow, config.UserFields);
                    },
                    function(searchResultRow) {
                        return spService.FormatDateFields(searchResultRow, config.DateFields, generalConfig.DateTimeFormat);
                    },
                    function(searchResultRow) {
                        return spService.AddImageMapping(searchResultRow, config.ImageFields);
                    },
                    function(searchResultRow) {
                        return spService.FormatNumberFields(searchResultRow, config.NumberFields);
                    },
                    function(searchResultRow) {
                        // Put link to parent Bill Cycle with name = folder name
                        //var parentLink = searchResultRow["FileRef"];
                        //arrayofstrings = parentLink.split("/");
                        //var billCycleFolderName = arrayofstrings[arrayofstrings.length-2];
                        //arrayofstrings.pop();
                        //var hyperLink = '<a href="' + arrayofstrings.join('/') + '">' + billCycleFolderName + '</a>';                         
                        //searchResultRow["Bill Cycle"] = hyperLink; 
                    }
                ];
                // Get data from SP             
                var selectProperties = spService.TransformFieldsToSelectProperties(config.Fields); // copy array
                var selectPropertiesToShow = spService.TransformFieldsToSelectProperties(config.FieldsToShow); // copy array
                var extendedSelectProperties = selectProperties.slice();
                var hyperLinkedProperties = spService.TransformFieldsToSelectProperties(config.HyperLinks)
                extendedSelectProperties = extendedSelectProperties.concat(hyperLinkedProperties);
                GetRelatedBillingDocumentsFromList(extendedSelectProperties, billCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions)
                .then(function (data) {
                    var trimmedData = spService.SpSearchQuery.TrimSearchResultsToSelectProperties(data, selectPropertiesToShow);
                    // Add data to dataTable
                    var dataTable = $(tableSelector).DataTable();
                    dataTable.clear().rows.add(trimmedData).columns.adjust().draw(); // Resize columns based on new data sizes                                          
                    vm.ValidDataLoaded = true;
                })
                .catch (function (message) {
                    vm.Name = "Error";
                    vm.ValidDataLoaded = true;
                });
            }

更新1:

最初に説明したときに間違って実装されていたため、デバッグ後にフィルター関数を変更しました.console.logを使用しましたが、コンソールに時々trueを出力し、falseを出力することがあります。 ただし、IF内にブレークピントを配置し、プッシュを実行しないため、配列は常に空です。

https://www.screencast.com/t/hRTEgvboCmX

私の更新されたコード:

//フィルタリングされたリストアイテムの値を作成します           var createFilteredListItemsWithValues = createListItemValues(             function(listItemValues){

           var x1=listItemValues && typeof listItemValues.FileRef === "string" && listItemValues.FileRef.split("/")[4];
            var x2= currentBillCyclePath.split("/")[8]
            console.log(x1===x2);

            return !(//pass filter function to createListItemValues
              listItemValues && 
              typeof listItemValues.FileRef === "string" &&
              listItemValues.FileRef.split("/")[4]
            ) === currentBillCyclePath.split("/")[8];
          }
        );

回答 1 件
  • たとえば、コードを少しクリーンアップしようとしました。キャッチを削除し、情報なしで拒否しました。たぶん、あなたはそれを試して、あなたが拒絶を受けるかどうか見ることができます。

    GetRelatedBillingDocumentsFromList の処理の多くが  これらの関数をデバッグして、意図したとおりに動作しているかどうかを確認できる別の関数で実行されます。

    var createQuery = function(viewFields,clientCode) {
      return '<View Scope="RecursiveAll">' +   viewFields + 
                '<Query>' +
                    '<Where>' +
                        '<And>' +
                            '<Eq>' +
                                '<FieldRef Name="ClientCode" />' +
                                '<Value Type="Text">'+ clientCode + '</Value>' +
                            '</Eq>' +
                            '<Neq>' +
                                '<FieldRef Name="ContentType" />' +
                                '<Value Type="Computed">Bill Cycle</Value>' +
                            '</Neq>' +
                        '</And>' +
                    '</Where>' +
                '</Query>' +
            '</View>';
    };
    var createListItemValues = function(filter) {
      return function(listItems,selectProperties) {
        var listItemsWithValues = [];
        if (listItems) {
          var enumerator = listItems.getEnumerator();
          while (enumerator.moveNext()) {
            var listItem = enumerator.get_current();
            var listItemValues = [];
            selectProperties
              .forEach(function (propertyName) {
                var value = listItem.get_item(propertyName);
                if (propertyName === "JobCodesMulti") {
                  jobvalue = "";
                  value.forEach(function (jobvalues) {
                    jobvalue += jobvalues.get_lookupValue() + ";";
                  })
                  listItemValues[propertyName] = jobvalue;
                } else {
                  listItemValues[propertyName] = value;
                }
              });
            if(filter(listItemValues)){//only push if filter returns true
              listItemsWithValues.push(listItemValues);
            }
          }
        }
        return listItemsWithValues;
      };
    };
    var processListItemWithValue = function(listItemsWithValues) {
      return function(listItem) {
        var fileDirRef = listItem["FileRef"];
        var id = listItem["ID"];
        var title = listItem["Title"];
        var serverUrl = _spPageContextInfo.webAbsoluteUrl.replace(_spPageContextInfo.webServerRelativeUrl, "");
        var dispFormUrl = serverUrl + "/sites/billing/_layouts/15/DocSetHome.aspx?id=" + fileDirRef;
        var parentLink = listItem["FileRef"];
        //!!!PLEASE NOTE: made arrayofstrings a local variable
        var arrayofstrings = parentLink.split("/");
        var billCycleFolderName = arrayofstrings[arrayofstrings.length - 2];
        arrayofstrings.pop();
        var hyperLink = '<a href="' + arrayofstrings.join('/') + '">' + billCycleFolderName + '</a>';
        listItem["Bill Cycle"] = hyperLink;
        listItemsWithValues["Document Type"] = getContentTypeOfCurrentItem(listItem.ID.toString());
      }
    };
    function GetRelatedBillingDocumentsFromList(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
      $log.info("Retrieving related billing documents for bill cycle with name [" + currentBillCyclePath + "]");
      //pass filter function to createListItemValues to get a new function that
      //  creates filtered list item values 
      var createFilteredListItemsWithValues = createListItemValues(
        function(listItemValues) {
          return !(//pass filter function to createListItemValues
            listItemValues && 
            typeof listItemValues.FileRef === "string" &&
            listItemValues.FileRef.split("/")[4]
          ) === currentBillCyclePath;
        }
      );
      var webUrl = _spPageContextInfo.webAbsoluteUrl;
      selectProperties = selectProperties.concat("ContentTypeId");
      var viewFields = spService.ConvertSelectPropertiesToViewFields(selectProperties);
      // query must return the documents for the same client but in other bill cycles not the current one
      var camlQuery = createQuery(viewFields,clientCode);
      var billCyclesListId = "{c23bbae4-34f7-494c-8f67-acece3ba60da}";
      //return a promise like here so the caller knows if something went wrong
      return spService.GetListItems(billCyclesListId, camlQuery, selectProperties)
      .then(
        function(listItems){
          console.log("currentBillCyclePath:",currentBillCyclePath);
          var listItemsValues = createFilteredListItemsWithValues
            (listItems,selectProperties);
          return $q.all(listItemsValues.map(addContentType))
          .then(function(){ return listItemsValues; })//finished asynchronously mutating array of listItems
        }
      ).then(
        function(listItemsWithValues) {
          listItemsWithValues.forEach(processListItemWithValue(listItemsWithValues));
          return $q.all(
            spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions)
          )
        }
      )
    }
    
    

あなたの答え