UI5 remove duplicate feed list items - javascript

I have a Feed List for posting comments in my UI5 xml view
<layout:content>
<m:FeedInput post="onFeedPost" class="sapUiSmallMarginTopBottom"/>
<m:List id="feedList" showSeparators="Inner" items="{path: '/table', sorter: {path: 'DATE', descending: true}}">
<m:FeedListItem sender="{MEMBERID}" timestamp="{DATE}" text="{COMMENT}" convertLinksToAnchorTags="All"/>
</m:List>
</layout:content>
I want to not display duplicate comments that have the same text and date, but keep them in the database. My idea was to in the controller iterate over over the items to do this, but I am not sure what to do with the resulting array
var results = [];
var comments = feed.getItems();
for (var n = 0; n < comments.length - 1; n++) {
var contained = false;
for (var m = n + 1; m < comments.length; m++) {
if (comments[n].getText() === comments[m].getText() &&
comments[n].getDate() === comments[m].getDate()) {
comments.pop(m);
contained = true;
if (!results.includes(comments[n])) {
results.push(comments[n]);
}
}
}
if (!contained && !results.includes(comments[n])) {
results.push(comments[n]);
}
}
// replace list items with results array
I can't figure out how to replace the feed list's items with the new array as there is a getItems function but not a setItems function. It occurs to me there is probably a simpler more idiomatic UI5 way to do this but I haven't found it yet.

First off, the correct way to handle this situation is in the OData service. The service should remove the duplicates before sending the data to the client. If we assume, however, that you can't do this server side, then you have some options.
1.) Do not bind the list items to anything. Instead, use the ODataModel to read the data, then filter out duplicates, create a new list item and add it to the list
Read the data using the ODataModel, then pass the results to a method that will filter and add them items to the list
oModel.read("/EntitySet", {
success: function(oResponse) {
this._addCommentsToList(oResponse.results)
}.bind(this)
})
In your method to handle the results, you'll need to do three things -- create a new FeedListItem, set the binding context of the list item, and then add the list item to the list
var aDistinctComments = //use your logic to filter out duplicates
aDistinctComments.forEach(function(oComment) {
//to set the binding context, you'll need the entity key/path
var sCommentKey = oModel.createKey("/EntitySet", oComment)
//create a new binding context
var oContext = oModel.createBindingContext(sCommentKey)
//create a new FeedListItem
var oItem = new FeedListItem({
sender: "{MemberId}",
...
});
//set the context of the item and add it to the list
oItem.setBindingContext(oContext);
oList.addItem(oItem);
})
2.) Bind the list directly to the OData entity set and then when the list receives the data, iterate over the items and hide the duplicates
<List items="{/EntitySet}" updateFinished="onListUpdateFinished"....>
----- onListUpdateFinished ---
var aItems = oList.getItems();
for (var m = n + 1; m < aItems.length; m++) {
//set a boolean, true if duplicate
var bDuplicate = aItems[m].getText() ==== aItems[n].getText() &&
aItems[m].getDate() === aItems[n].getDate();
//set the visibility of the item to true if it is not a duplicate
aItems[m].setVisible(!bDuplicate)
}
3.) Read the data manually, remove duplicates, and stash it in a JSON model, and bind the table to your JSON model path
oModel.read("/EntitySet", {
success: function(oResponse) {
this._addCommentsToJSONModel(oResponse.results)
}.bind(this)
})
You can stash an array of objects in your JSON model, and then bind the table items to that path
var aDistinctComments = // your logic to get distinct comments
oJSONModel.setProperty("/comments", aDistinctComments)
oList.setModel(oJSONModel);
-----
<List items="{/comments"}....>
4.) Bind your list items to your entity set, iterate over the items, and then remove duplicates from the list. I don't recommend this approach. Removing items manually from lists bound to an entity set can lead to trouble with duplicate IDs.
var oItem = //use your logic to find a duplicate list item
oList.removeItem(oItem)
I recommend first handling this server side in the OData service, and if that's not an option, then use option 1 above. This will give you the desired results and maintain the binding context of your list items. Options 2 and 3 will get you the desired results, but depending on your applicaiton, may make working with the list more difficult.

Here is one approach :
Do not directly bind the list to your oData.
You can create a JSON model which will be the resulting model after removing duplicate items.
Bind the JSON model to the List as such:
var oList = this.getView().byId("feedList");
oList.bindAggregation("items", "pathToJsonArray", template);
(The template is feedlistitem in this case).

Related

How can I do ng-repeat with a firebase Array?

Context
In a Firebase DB I'm storing "events" and "users". Users can have favorite events, to manage them I only store the event's id in the favorite user's DB location. So to grab favorite events informations, I need to firstable grab the event id and then go to the DB events location, to collect all the datas I need.
Problem
I would like to store in an Array all the favorite events informations (each event would be an Object with inside it : "key" : "value"), to use that Array in my HTML view and print the informations. But it doesn't work the way I coded it... :(
// This ref is too grab favorite event id (in my case only 2) in the user DB location
var refUserFavoris = firebase.database().ref().child("users/"+user.uid+"/events/favoris");
$scope.favorisTmp = $firebaseArray(refUserFavoris);
// This shows one array, with two objects (wich are my two user's favorite events) wich include ids
console.log($scope.favorisTmp);
// This is to load the objects and with the foreEach, grab there ids to use them in the next ref call
$scope.favorisTmp.$loaded().then(function()
{
angular.forEach($scope.favorisTmp, function(favoris)
{
// This shows two lines : the id of each object
console.log(favoris.$id);
// Call a new ref to reach the event informations (in a different location of the DB) using the previous id
firebase.database().ref("events/"+favoris.$id).once('value').then(function(snapshot)
{
// Attempt to store events datas for each id I have (in my case, only two)
snapshot.forEach(function(favorisSnap)
{
var favSnap = favorisSnap.val();
// This shows a lot of "undefined" lines, wich I don't want. I would like two objects, with all informations inside
console.log(favSnap.nbPersonne);
// $scope.favorisF is an Array that I would like to use in a ng-repeat to print all datas for each event
// For now this doesn't show anything
$scope.favorisF = favSnap;
});
// If using favSnap out of the previous function, I got a "favSnap" is undifined error
console.log(favSnap);
});
});
});
<ion-item ng-repeat="f in favorisF" class="item-avatar">
{{f.nbPersonne}}
</ion-item>
EDIT 1 :
I tried a new way to have my data, but a new problem came, how to fill an Array inside a loop ? I've tried "push" and "$add" methods, but no one worked. Any ideas ?
var newFav = [];
var user;
user = firebase.auth().currentUser;
var refUserFavoris = firebase.database().ref().child("users/"+user.uid+"/events/favoris");
$scope.favorisTmp = $firebaseArray(refUserFavoris);
$scope.favorisTmp.$loaded().then(function()
{
angular.forEach($scope.favorisTmp, function(favoris)
{
console.log(favoris.$id);
var refFavoris = firebase.database().ref("events/"+favoris.$id);
refFavoris.on('value', function(snap)
{
//This is where I'm trying to fill "newFav" in each steps of the loop
newFav.push(snap.val());
console.log("Scope newFav vaut :", $scope.newFav);
});
});
});
I think you made a typo here.
var refUserFavoris = firebase.database().ref("events/favoris/"+favoris.$id).once('value')
Thanks a lot Abdel, I fixed my problem :
Here is the solution
$scope.newFav = [];
console.log($scope.newFav);
$scope.favorisTmp.$loaded().then(function()
{
angular.forEach($scope.favorisTmp, function(favoris)
{
console.log(favoris.$id);
var refFavoris = firebase.database().ref("events/"+favoris.$id);
refFavoris.on('value', function(snap)
{
$scope.newFav.push(snap.val());
console.log("Scope newFav vaut :", $scope.newFav);
});
});
});

Parse.com issues while querying array of pointers, .include not getting nested pointer data in cloud code

I am having trouble getting data from the nested pointers in my array of pointers from a query. I have an array of pointers like so: [{"__type":"Pointer","className":"QuizData","objectId":"rmwJrV55c7"},{"__type":"Pointer","className":"QuizData","objectId":"2132q8i9np”}, etc…]
That QuizData class also has a column named “ad” which is a Pointer to the “Ads” class. I can get the QuizData in a query using the following include statements on my query like so:
var __quizAdQueueQuery = new Parse.Query(QuizAdQueue);
__quizAdQueueQuery.equalTo("user", __request.user);
__quizAdQueueQuery.include("quizAdArr”);
__quizAdQueueQuery.include(["quizAdArr.QuizData"]);
BUT Neither of these or both combined don’t work as when I try to get column data from the ad it’s always undefined:
__quizAdQueueQuery.include(["quizAdArr.QuizData.ad"]);
__quizAdQueueQuery.include(["quizAdArr.QuizData.Ads"]);
This is my return from that query, where the column data "mediaType" that I am trying to access is always undefined:
return __quizAdQueueQuery.first().then(function(__resultsObj)
{
__quizQueueObj = __resultsObj;
__userQuizQueueArr = __quizQueueObj.get("quizAdArr");
var __quiz;
var __ad;
var __seenAd;
var __lengthInt = __userQuizQueueArr.length;
var __mediaTypeStr = __request.params.mediaType;
var __matchedQuizzesArr = [];
for (var __i = 1; __i < __lengthInt; __i++)
{
__quiz = __userQuizQueueArr[__i];
// console.log('__quiz.get("name") = '+__quiz.get("name"));
__ad = __quiz.get("ad");
// console.log("__ad.id = "+__ad.id);
//THE MEDIA TYPE IS ALWAYS RETURNING UNDEFINED HERE!!!
console.log('__ad.get("mediaType") = '+__ad.get("mediaType")+', __mediaTypeStr = '+__mediaTypeStr);
if (__ad.get("mediaType") == __mediaTypeStr)
{
//put all matches in array to be sorted
__matchedQuizzesArr.push(__userQuizQueueArr[__i]);
console.log("__matchedQuizzesArr.length = "+__matchedQuizzesArr.length);
}
}
return __matchedQuizzesArr;
});
Thanks for any help you can give! I also posted this as a bug in the Parse/Facebook issue reporter but was redirected here, so if this is a bug I can reopen it: https://developers.facebook.com/bugs/923988310993165/
EDIT Here is the updated, working query with nested includes for clarity:
var __quizAdQueueQuery = new Parse.Query(QuizAdQueue);
__quizAdQueueQuery.equalTo("user", __request.user);
__quizAdQueueQuery.include('quizAdArr');
__quizAdQueueQuery.include('quizAdArr.ad');
This should work (you only need to list the column names):
query.include('quizAdArr.ad');
Here's why:
You're querying QuizAdQueue so you don't need to list that
The QuizAdQueue class has an array in quizAdArr so you include it: query.include('quizAdArr');
Each quizAdArr element is a QuizData with an ad so you include it: query.include('quizAdArr.ad');
The issue was that you were including QuizData which is the name of a class and not a column name

Alfresco: update data list line

I have data being sent to a custom data list from the following code:
// Get the site name and dataLists
var site = siteService.getSite("Testing");
var dataLists = site.getContainer("dataLists");
// Check for data list existence
if (!dataLists) {
var dataLists = site.createNode("dataLists", "cm:folder");
var dataListProps = new Array(1);
dataListProps["st:componentId"] = "dataLists";
dataLists.addAspect("st:siteContainer", dataListProps);
dataLists.save();
}
// Create new data list variable
var orpList = dataLists.childByNamePath("orplist1");
// If the data list hasn't been created yet, create it
if (!orpList) {
var orpList = dataLists.createNode("orplist1","dl:dataList");
// Tells Alfresco share which type of items to create
orpList.properties["dl:dataListItemType"] = "orpdl:orpList";
orpList.save();
var orpListProps = [];
orpListProps["cm:title"] = "Opportunity Registrations: In Progress";
orpListProps["cm:description"] = "Opportunity registrations that are out for review.";
orpList.addAspect("cm:titled", orpListProps);
}
// Create new item in the data list and populate it
var opportunity = orpList.createNode(execution.getVariable("orpWorkflow_nodeName"), "orpdl:orpList");
opportunity.properties["orpdl:nodeName"] = orpWorkflow_nodeName;
opportunity.properties["orpdl:dateSubmitted"] = Date().toString();
opportunity.properties["orpdl:submissionStatus"] = "Requires Revisions";
opportunity.save();
This correctly creates data list items, however, at other steps of the workflow require these items to be updated. I have thought of the following options:
Remove the data list item and add another with the updated information
Simply update the data list item
Unfortunately I have not found adequate solutions elsewhere to either of these options. I attempted to use orpWorkflow_nodeName, which is a unique identifier generated at another step, to identify a node to find it. This does not seem to work. I am also aware that nodes have unique identifiers generated by Alfresco itself, but documentation doesn't give adequate information on how to obtain and use this.
My question:
Instead of var opportunity = orpList.createNode(), what must I use in
place of createNode() to identify an existing node so I can update its
properties?
You can use this to check existing datalist item.
var opportunity = orpList .childByNamePath(execution.getVariable("orpWorkflow_nodeName"));
// If the data list Item is not been created yet, create it
if (!opportunity ) {
var orpList = orpList .createNode(execution.getVariable("orpWorkflow_nodeName"),"dl:dataList");}

How to pull only the nodes/values from firebase and not the keys?

How do you only pull only the nodes from firebase and not the keys using javascript? In other words, I only want the values of the key-value pairs from the below firebase, which means I don't want the unique keys below but just what's underneath.
Currently, my code is..
function PullFirebase() {
new Firebase('https://myfirebase.firebaseIO.com/quakes').on('value', function (snapshot) {
var S = snapshot.val();
function printData(data) {
var f = eval(data);
console.log(data + "(" + f.length + ") = " + JSON.stringify(f).replace("[", "[\n\t").replace(/}\,/g, "},\n\t").replace("]", "\n]"));
}
printData(S);
});
}
PullFirebase();
This produces the following in the console
[object Object](undefined) = {"-JStYZoJ7PWK1gM4n1M6":{"FID":"quake.2013p618454","agency":"WEL(GNS_Primary)","depth":"24.5703","latitude":"-41.5396","longitude":"174.1242","magnitude":"1.7345","magnitudetype":"M","origin_geom":"POINT (174.12425 -41.539614)","origintime":"2013-08-17T19:52:50.074","phases":"17","publicid":"2013p618454","status":"automatic","type":"","updatetime":"2013-08-17T19:54:11.27"},
"-JStYZsd6j4Cm6GZtrrD":{"FID":"quake.2013p618440","agency":"WEL(GNS_Primary)","depth":"26.3281","latitude":"-38.8725","longitude":"175.9561","magnitude":"2.6901","magnitudetype":"M","origin_geom":"POINT (175.95611 -38.872468)","origintime":"2013-08-17T19:45:25.076","phases":"13","publicid":"2013p618440","status":"automatic","type":"","updatetime":"2013-08-17T19:48:15.374"},...
but I'd like to only have the dictionaries , such as
[{"FID":"quake.2013p618454","agency":"WEL(GNS_Primary)","depth":"24.5703","latitude":"-41.5396","longitude":"174.1242","magnitude":"1.7345","magnitudetype":"M","origin_geom":"POINT (174.12425 -41.539614)","origintime":"2013-08-17T19:52:50.074","phases":"17","publicid":"2013p618454","status":"automatic","type":"","updatetime":"2013-08-17T19:54:11.27"},{"FID":"quake.2013p597338","agency":"WEL(GNS_Primary)","depth":"5.0586","latitude":"-37.8523","longitude":"176.8801","magnitude":"2.2362","magnitudetype":"M","origin_geom":"POINT (176.88006 -37.852307)","origintime":"2013-08-10T00:21:54.989","phases":"17","publicid":"2013p597338","status":"automatic","type":"","updatetime":"2013-08-10T03:42:41.324"}...]
If I understand you correctly, you want to get all child objects under quakes.
You generally have two approach here:
Get the value of the parent node and loop over the children
Monitor as children are added/updated/removed to the parent node
Your approach matches with #1, so I'll answer that one first. I'll also give an example of approach #2, which is more efficient when your data set changes.
Iterate children of a Firebase ref
In your on('value', handler you can skip the unique IDs using forEach:
new Firebase('https://myfirebase.firebaseIO.com/quakes').on('value', function (snapshot) {
var quakes = [];
snapshot.forEach(function(childSnapshot) {
quakes.push(childSnapshot.val());
});
var filter = new crossfilter(quakes);
});
The forEach function is sychronous, so we can simply wait for the loop to finish and then create the crossfilter.
Monitor children of a Firebase ref
In that case, the best construct is:
var quakes = new Firebase('https://myfirebase.firebaseIO.com/quakes');
var quakeCount = 0;
quakes.on('child_added', function (snapshot) {
var quake = snapshot.val();
quakeCount++;
console.log("quakeCount="+quakeCount+", FID="+quake.FID);
});
quakes.on('child_removed', function (old_snapshot) {
var quake = old_snapshot.val();
quakeCount--;
console.log("quakeCount="+quakeCount+", removed FID="+quake.FID);
});
With this code construct you're actively listening for quakes that are added and removed. You'll still have to keep an array of all the quakes, which you then modify in child_added, child_changed and child_removed.
How they compare
When you first run the code, monitoring for children will result in the same data as the on('value', construct. But when children are added/removed later on('value', will receive all quakes again, while on('child_added', and on('child_removed', will only be called for the quake in question.

Accessing child stories from parent record

I am building a rallygrid to display parent level stories. For each row, I want to iterate all the children of that story and pull some information from each child story. e.g.
Ext.Array.each(data, function(record) {
//Perform custom actions with the data here
//Calculations, etc.
recName=record.get('Name');
if (recName.search(/\[Parent\]/i) != -1) {
// Grab Child Iterations
if (record.get('Children').length) {
var childlist = record.get('Children');
for (var child in childlist) {
// I want to get each child's Iteration !!!
}
} else {
childIter = "none";
}
records.push({
FormattedID: record.get('FormattedID'),
ScheduleState: record.get('ScheduleState'),
Name: recName,
NumChildren: record.get('Children').length,
PRDNumber: record.get('PRDNumber')
});
}
});
But, the record.get('Children') retuns objects that look like:
_rallyAPIMajor "1"
_rallyAPIMinor "34"
_ref "https://rally1.rallydev.com/slm/webservice/1.34/hierarchicalrequirement/7272142216.js"
_refObjectName "[Comp] User Story"
_type "HierarchicalRequirement"
I'm assuming there's some Ext call that will take the _ref URI, download it and parse out the JSON into a nice object I can start doing childrecord.get('field') on, but for the life of me, I can't find the right function to call.
You can use the load method of the record's model to retrieve a specific item as mentioned in this question/answer:
Rally App2.0 - Retrieve a specific story
In your case you can get the model from the existing record:
var model = record.self;
model.load(child.get('ObjectID'), {
//options
});
However in your case if you're just looking for some info on each child story's iteration you can probably just include it in the fetch of your initial WsapiDataStore used to load the parent:
fetch: ['Children', 'Iteration', 'StartDate', 'EndDate']

Categories