Table sorting causing duplication in meteor - meteor

In my meteor app I have a table of data with sorting for each coloumn. When I keep on clicking the coloumn for sorting, the table itself is getting multiplied.
This is the code for setting session variables.
'click #coloumn_name' : function()
{
var oldOrder = Session.get("sortOrder");
var sortField = 'coloumn1';
Session.set("sortField",sortField );
if(oldOrder == 1)
{
var newOrder = -1;
Session.set("sortOrder",newOrder );
}
else
{
var newOrder = 1;
Session.set("sortOrder",newOrder );
}
}
Here is the code for reading the session variables and fetching data from db.
Template.templatename.vname = function()
{
var filter = {sort: {}};
var sortField = Session.get('sortField');
var sortOrder = Session.get('sortOrder');
if(!sortField)
{
sortField = 'coloumn2';
}
if(!sortOrder)
{
sortOrder = 1;
}
filter.sort[sortField] = sortOrder;
return Groups.find({}, filter);
}
Here is my template
<template name="templatename">
<table>
<tr>
<th>Group Name</th>
<th>Status</th>
</tr>
{{#each vname }}
<tr>
<td> {{name}} </td>
<td> {{status}} </td>
</tr>
{{/each}}
</table>
</template>
This is the table before trying to sort.
This is the image after trying to sort
Does anyone have any idea why this happens ?

Related

ASP.NET Core View - creating dropdown filter for single column

I have ASP.NET CORE app.
In one of my views I have Status column among others which can have 2 possible values: Active or Deactivated.
How can I create filter on that column with simple drop-list that would allow me to filter whole table based on these 2 column values?
All I can find are lengthy tutorials that are not quite covering what I need.
Basically I need someone to give me few links or points me on how to implement this in most simple way.
EDIT
column definition in Model:
[Column(TypeName = "BIT")]
[Display(Name = "Status")]
public bool Status { get; set; }
So in my Index View I have:
<th>
#Html.DisplayNameFor(model => model.Status)
</th>
....
<td>
#(item.Status ? "Active" : "Deactivated")
</td>
How can I turn that header title into title with drop-down list?
Something like this:
Obviously in my case instead of "Company Name" column name would be "Status" and in drop-down values I would have only 2 items - "Active" and "Deactivated".
I made a test based on your needs, below is a working demo:
View:
#model IEnumerable<Product>
#{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "Active",
Value = "Active"
});
listItems.Add(new SelectListItem
{
Text = "Deactivated",
Value = "Deactivated"
});
}
<table id="mytable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<td>
#Html.DisplayNameFor(model => model.Id)
</td>
<td>
#Html.DisplayNameFor(model => model.Name)
</td>
<td>
#Html.DropDownList("Status", listItems, "Status")
</td>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#(item.Status ? "Active" : "Deactivated")
</td>
</tr>
}
</tbody>
</table>
#section scripts{
<script>
$("#Status").on('change', function () {
var val = $("#Status option:selected").text();
$.ajax({
type: 'get',
url: '/Home/FilterByStatus',
data: { status: val },
success: function (result) {
$("#mytable tbody").empty();
$.each(result, function (i, value) {
$("#mytable tbody").append("<tr><td>" + value.id + "</td><td>" +
value.name + "</td><td>" + (value.status ? "Active" : "Deactivated") +"</td></tr>")
})
}
})
})
</script>
}
Controller:
public static List<Product> products = new List<Product>
{
new Product{ Id = 1, Name = "AA", Status = true},
new Product{ Id = 2, Name = "BB", Status = true},
new Product{ Id = 3, Name = "CC", Status = false},
new Product{ Id = 4, Name = "DD", Status = false}
};
public IActionResult Index()
{
return View(products);
}
public IActionResult FilterByStatus(string status)
{
var filterproducts = products.ToList();
if (status == "Active")
{
filterproducts = products.Where(p => p.Status == true).ToList();
return Json(filterproducts);
}
else if(status == "Deactivated")
{
filterproducts = products.Where(p => p.Status == false).ToList();
return Json(filterproducts);
}
return Json(filterproducts);
}
Result:

DataTable Server-side processing ajax error

I have a form/page in which do a search. That action returns datatabel type (this is a requirement) then the results I have to show in jquery datatable and the processing has to be done server-side.
I read the documentation and got some examples but I can't get it work.
$(document).ready(function () {
var table = $("#searchResultTable").DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "Report/CustomServerSideAction",
"type": "POST"
},
"columns":[
{"data": "ID"},
{"data": "Name"},
{"data": "Active"},
{"data": "OrderBy"},
{"data": "StoredProcedure"},
{"data": "SSRSFileName"},
{"data": "SSESStoredProcedure"}
]
//buttons: [
// "csv", "excel", "pdf", "print"
//]
});
});
#using System.Data
#model System.Data.DataTable
<div class="col-sm-12">
<div class="card-box table-responsive">
<table id="searchResultTable" class="testClass table table-striped table-colored table-teal">
<thead>
<tr>
#foreach (DataColumn col in Model.Columns)
{
<th>#col.ColumnName</th>
}
</tr>
</thead>
<tbody>
#foreach (DataRow item in Model.Rows)
{
<tr>
#foreach (DataColumn col in Model.Columns)
{
switch (col.DataType.ToString())
{
case "System.Decimal":
<td class="pull-right">#Convert.ToDecimal(item[col].ToString())</td>
break;
default:
<td>#item[col].ToString()</td>
break;
}
}
</tr>
}
</tbody>
</table>
</div>
</div>
[HttpPost]
public ActionResult CustomServerSideAction()
{
var table = Models.SearchResult.Results;
return Json(new { draw = 100, totalRecors = 30, dislayRecord = 10, data = table }, JsonRequestBehavior.AllowGet);
}
public static class SearchResult
{
public static DataTable Results { get; set; }
}
This gives an error
DataTables warning: table id=searchResultTable - Ajax error. For more
information about this error, please see http://datatables.net/tn/7

Using Handlebars for conditional CSS

In the snippet below I'd expect row a to have the class new-entry and row c to have the class moving-up but neither does.
I'm certain this is a silly mistake but I can't see it
Handlebars.registerHelper("newEntry", function() {
return this.newEntry ? 'class="new-entry"' : '';
});
Handlebars.registerHelper("movingUp", function() {
return this.movingUp ? 'class="moving-up"' : '';
});
var source = document.getElementById('leaderboard-template').innerHTML;
var template = Handlebars.compile(source);
var outlet = document.getElementById('outlet');
outlet.innerHTML = template({leaders: [
{name: 'a', signature_count: 10, newEntry: true},
{name: 'b', signature_count: 8},
{name: 'c', signature_count: 6, movingUp: false},
]});
.new-entry {
background-color:red;
}
.moving-up {
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.6/handlebars.min.js"></script>
<script id="leaderboard-template" type="text/x-handlebars-template">
<table>
<thead>
<th>Constituency</th>
<th>Votes</th>
</thead>
<tbody>
{{#leaders}}
<tr {{newEntry}}>
<td>{{name}}</td>
<td><span {{movingUp}}>{{signature_count}}</span></td>
</tr>
{{/leaders}}
</tbody>
</table>
</script>
<div id="outlet"></div>
Handlebar converts the return value of a helper to an HTML escaped string. Use Handlebars.SafeString like this if you don't want that:
Handlebars.registerHelper("newEntry", function() {
return new Handlebars.SafeString( this.newEntry ? 'class="new-entry"' : '' );
});
Handlebars.registerHelper("movingUp", function() {
return new Handlebars.SafeString( this.movingUp ? 'class="moving-up"' : '' );
});

Meteor search clear results

I would like to make Meteor clear the last query, it does not accumulate my research. If I search in the input "Nº Património" and then doir again in the "Código Informática", I want to clear the first query results. What is happening is that it brings together the first and the second query results. Summing up, i want to se query results independently.Meteor search page
Template
<tbody>
<tr>
<th>Nº Património</th>
<th>Equipamento</th>
<th>Utilizador</th>
<th>Nº Helpdesk</th>
<th>Data Aquisição</th>
<th>Data Saída</th>
<th>Ultima Alteração</th>
</tr>
{{#each pesquisaEquipamentos}}
<tr>
<td>
{{npatrimonio}}
</td>
<td>
{{equipamento}}
</td>
<td>
{{utilizadores}}
</td>
<td>
{{helpdesk}}
</td>
<td>
{{daquisicao}}
</td>
<td>
{{dsaida}}
</td>
<td>
{{createdAt}}
</td>
</tr>
{{/each}}
</tbody>
Helper
if (Meteor.isClient) {
Template.pesquisar.helpers({
pesquisaEquipamentos: function() {
return Equipamentos.find();
}
});
Template.pesquisar.events({
"keypress input": function(event, template) {
if (event.keyCode == 13) {
var search = {};
search.value = event.target.value
search.name = event.target.name
//console.log(search.name, search.value);
Meteor.subscribe("pesquisaEquipamentos", search);
event.target.value = '';
}
}
});
}
Publication
Meteor.publish("pesquisaEquipamentos", function(search) {
//console.log(search.name);
//console.log(search.value);
switch (search.name) {
case 'npatrimonio':
return Equipamentos.find({
npatrimonio: search.value
});
break;
case 'cinformatica':
return Equipamentos.find({
cinformatica: search.value
});
break;
default:
}
});
Try stopping the subscription before you call it again:
var mySub;
Template.pesquisar.events({
"keypress input": function(event, template) {
if (event.keyCode == 13) {
var search = {};
search.value = event.target.value
search.name = event.target.name
if ( mySub ) mySub.stop(); // if you've previously subscribed clear those results
mySub = Meteor.subscribe("pesquisaEquipamentos", search);
event.target.value = '';
}
}
});

How to fetch data from parse.com and render it to table using AngularJs

I am trying to fetch data stored in parse.com collection. I am using Parse Javascript SDK to call the service asynchronously as following:
ctrl.factory('TLDs', function($q){
var query = new Parse.Query(Fahras)// Fahras is the Parse Object initialized earlier in code
query.equalTo("type", "Domain")
var myCollection = query.collection()
return {
fetchDomains: function(){
var defer = $q.defer();
myCollection.fetch({
success : function(results) {
defer.resolve(results.modles);
console.info(results.models)
},
error : function(aError) {
defer.reject(aError);
}
});
console.info(defer.promise)
return defer.promise;
}
}
}) // end of factory topDomains
I have a simple table to show the fetched data
<div id="showdomainshere"> {{domains}}</div>
<table id="domains_table" class="table table-hover">
<thead>
<tr>
<th>Domain</th>
<th>Code</th>
<th>Subjects</th>
<th>Instances</th>
</tr>
</thead>
<tbody id="table_body">
<form id="edit_row" class="form-inline">
<tr ng-repeat="item in domains">
<td><span>{{item.attributes.arTitle}}</span>
</td>
<td><span>{{item.attributes.domainCode}}</span>
</td>
<td><span>{{subclasses}}</span>
</td>
<td><span>{{instances}}</span>
</td>
</tr>
</form>
</tbody>
</table>
</div> <!-- end of main div -->
And hereunder the controller I ma using to render the view:
ctrl.controller('Home', ['$scope','TLDs',function($scope, TLDs) {
$scope.domains = TLDs.fetchDomains()
}])
Using console.info I can see that the result is fetched and I can go through the array of returned models as expected. Problem is that $scope.domains never been updated and as a result the table never been rendered
Fortunately I am able to figure it out.
The controller should be like:
ctrl.controller('Home', ['$scope','TLDs',function($scope, TLDs) {
TLDs.fetchDomains().then(function(data){
$scope.domains = data
})
}
While the factory itself should be like:
ctrl.factory('TLDs', function($q){
var query = new Parse.Query(Fahras)
query.equalTo("type", "Domain")
var myCollection = query.collection()
return {
fetchDomains: function(){
var defer = $q.defer();
myCollection.fetch({
success : function(results) {
defer.resolve(results.models)
return results.models
},
error : function(aError) {
defer.reject(aError)
}
})
return defer.promise;
}
} }) // end of factory

Resources