DataTables unable to display the field of related object in LWC - javascript

I have a data table which displays 'Name' field and 'Address' field (Address related to another object). The 'Name' field is displayed properly but if I iterate over the list in html for pcon.Address__r.Name it gives error. If only pcon.Address__r is given , it shows [object object] in table. Can anybody resolve this issue?
HTML:
<table class="slds-table slds-table--bordered">
<thead>
<tr>
<th style="background-color: #151963;color: white;">Name</th>
<th style="background-color: #151963;color: white;">Address</th>
</tr>
</thead>
<tbody>
<template for:each={pconfig} for:item="pcon" for:index="i">
<tr class={pcon.row} data-id={pcon.Id} data-index={i} key={pcon.Id} onclick{getquotes} >
<td>{pcon.Name}</td>
<td>{pcon.Address__r.Name}</td>
</tr>
</template>
</tbody>
</table>
</lightning-layout-item>
JS:
#wire(Vendor_getProduct,{ basketId: 'fef0E0000dwedjh' })
getProducts({error,data})
{
if(data)
{
//console.log( 'Fetched Data ' + JSON.stringify( data ) );
this.pconfig = JSON.parse( JSON.stringify( data) );
console.log('products are:',data);
}
else if(error){
this.error=data;
console.log('error is undefined');
}
}
class:
public class c {
#AuraEnabled(cacheable=true)
public static List<Product_Configuration__c> getProduct (Id basketId) {
return [select id,
name,
Address__r.name,
from Product_Configuration__c
where Product_Basket__c =:basketId];
}

Related

json.parse not working with template engine handlebars

I have a search box which I wish to use to populate my table so i want to access the data sent to the view template in the script tag
ERROR IN SCRIPT
1 Uncaught SyntaxError: "[object Object]" is not valid JSON
at JSON.parse (<anonymous>)
at 1:164:25
<div class="FieldElement2" style="margin-top: 3%;">
<div class="input-field ">
<input id="search_masterTable" type="text" class="validate">
</div>
<table class="highlight centered responsive-table" style="width: min-content;" >
<thead>
<tr>
<th></th>
<th>Ledg.No.</th>
<th>File No.</th>
<th>Name</th>
<th>Phone</th>
</tr>
</thead>
<tbody id="searchResultsBody">
{{#each accounts_array}}
<tr>
<td><button class="viewButton">View Chart</button></td>
<td class="Ledg_No" scope="row">{{ledger_num}}</td>
<td class="File_Num" scope="row">{{file_num}}</td>
<td class="Name">{{client_name}}</td>
<td class="gPhoneNumber3">{{phone_number6}}</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
<script>
document.getElementById('search_masterTable').addEventListener('input',()=>{
const search_value = document.getElementById('search_masterTable').value.toUpperCase().split(' ')
// NOT WOKING
const data = JSON.parse("{{accounts_array}}")
const result_array = data.filter(function(r){
return search_value.every(function(word){
console.log(word)
return column_name_array.some(function(colIndex){
console.log(r[colIndex])
if(r[colIndex] == null){
return false
}else{
return r[colIndex].toString().toUpperCase().indexOf(word) !== -1
}
});
});
})
function to_populate_masterTable(){
}
</script>
insted of sending the search value back to the server i want to perfom the search opearation in the frontend and send display the result for every search input
BACK END
router.get('/masterTable/:id', ensureAuth, async (req, res) => {
const title = 'Master Table'
var account = parseInt(req.params.id)
db.query(`SELECT * FROM mt_`+account+``, async (err,accounts_array) => {
res.render('masterTable', {
accounts_array,
title
})
})
})
THIS IS WHAT THE account_array LOOKS LIKE
[
RowDataPacket { // <= this is the error
id: 1,
ledger_num: 'VM364',
file_num: 'VM364',
client_name: 'MUTHU KUMAR',
phone_number1: '9791716460',
status: 'UNSETTLED'
},
RowDataPacket {
id: 1,
.,
.,
.,
},
RowDataPacket {},
RowDataPacket {}
]
error that i got
Uncaught SyntaxError: Unexpected token '{' (at 1:169:21)
This might work by first stringifying the variable and using the tag syntax to pass the stringified JSON to the template:
const data = JSON.parse(<%= JSON.stringify(accounts_array) %>);

Make an array from object to iterate over it by *ngFor

I got response from my api it simple one record from my database.
getFilledForm() {
const reservation = this.hotels[0].reservation;
this.accidentFormService.getAccidentForm(reservation).subscribe(
res => {
this.form = res;
console.log('this.form: '+JSON.stringify(this.form));
this.test = Object.keys(this.form).map(key => ({ type: key, value: this.form[key] }));
console.log('this.test: ' +this.test);
},
error => {
console.log(error);
}
)
}
this.form is a object and output looks like:
this.form: {"id":1,reservation":1234,"hotel_name":"BB Hotels"}
I tried to make an array but my array of objects looks like ( this.test )
this.test: [object Object],[object Object],[object Object]
after stringify
this.test: [{"type":"id","value":1},{"type":"reservation","value":null},{"type":"hotel_name","value":"BB Hotels"}]
I want output like: "id":1 no "type":"id","value":1
How sould it be ? I want to make a table from output using *ngFor
-Edit
Added HTML
<table *ngIf="checkForm" class="table table-sm align-items-center table-hover table-flush responsive">
<thead class="thead-light">
<tr>
<th scope="col" class="lPart">ID</th>
<th scope="col" class="lPart">Hotel Name</th>
</tr>
</thead>
<tbody>
<tr
*ngFor="let form of form | paginate: { itemsPerPage: 10, currentPage: p }; let i = index">
<td id="lPart">{{ form.id }}</td>
<td id="lPart">{{ form.hotel_name }}</td>
</tr>
</tbody>
</table>

Error loading row data from DataTable into localStorage using a custom Button

I am using the DataTables Jquery plugin and I am trying to create a custom Button plugin using the documentation on the DataTable website. where I could load the row data into localStorage. Let's call this button 'Save Internally'
"buttons": [
{
text: 'Save Internally',
action: function ( e, dt, node, config ) {
var data = dt.rows( { selected: true } ).data();
localStorage.setItem("datatable1", JSON.stringify(data));
}
}
]
When I implement and test it, I don't seem to be able to store anything into the localStorage. I tried console.log-ing the row data with JSON.stringify to see if the data is extractable from the event, but then I get the error TypeError: Converting circular structure to JSON. Without the JSON.stringify it gives me Object Object.
I try to test the row data with
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(key);
to see if the object has any properties or keys, but it does not.
The way the row is structured in the front-end is as below.
<div class="jumbotron container" id="viewtableresult">
<table id="example" class="display table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>Column 1</th>
<th>Name</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Column 1</th>
<th>Name</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
</tfoot>
</table>
</div>
I know that I can only store strings into localStorage, but not knowing the structure of the object, I wouldn't know how to properly stringify the object. I am sure there must be an easy way to be able to store the row data from the DataTable plugin into localStorage.
Update :
I figured out that there is an API method called : buttons.exportdata()
Using this I changed the code to the following :
text: 'Save Internally',
action: function ( e, dt, node, config ) {
var rows = dt.rows( { selected: true } ).data(); //irrelevant now
var data = table.buttons.exportData( {
modifier: {
selected: true
}
} );
console.log( JSON.stringify(data) ) //was able to show the data in strings
localStorage.setItem("testdata", JSON.stringify(data));
}
and was able to find the data which has a 'header' and 'body' property. Now I need to figure out how to setItem() this data into localStorage, as it still does not get stored into localStorage.
When you are calling .data() you are getting an object with all rows and functions. You only need rows so you should call .toArray().
var data = dt.rows( { selected: true } ).data().toArray();
I also created jsFiddle example where I am saving to local storage and reading from it: jsFiddle link
Relevant code for storing and loading data:
$('#example').DataTable( {
dom: 'Bfrtip',
buttons: [
{
text: 'Export',
action: function ( e, dt, node, config ) {
var data = dt.rows( { selected: true } ).data().toArray();
var json = JSON.stringify(data)
localStorage.setItem('exportedData', json);
}
},
{
text: 'Load',
action: function ( e, dt, node, config ) {
var data = JSON.parse(localStorage.getItem('exportedData'));
dt.clear();
dt.rows.add(data).draw();
}
}
]
} );

ng-repeat in AngularJs doesnt show data in table but show empty rows

I'm using AngularJs in Asp.net Mvc5 for create single page application.
I have a problem , when i use ng-repeat for show data in table , my data doesn't show in table but show empty rows
This is my Home Controller
angularFormsApp.controller("HomeController",
function ($scope, $location, DataService) {
DataService.getEmployees().then(
function (results) {
$scope.names = results.data;
console.log(results.data);
console.log("This is console");
},
function (error) {
// on error
alert("error read data" + error);
}
);
});
This is my DataService
angularFormsApp.factory('DataService',
function ($http) {
var getEmployees = function () {
return $http.get("Employee/GetEmployees");
};
return {
getEmployees: getEmployees
};
});
This is My Html Page
<div ng-app="angularFormsApp">
<div ng-controller="HomeController">
{{ Namef }}
<table class="table table-hover ">
<thead>
<tr>
<th>Name Employee</th>
<th>Note</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in names">
<td>{{ item.FullName }}</td>
<td>{{ item.Note }}</td>
<td>
Edite
Delete
</td>
</tr>
</tbody>
</table>
</div>
</div>
This is My EmployeeController
public class EmployeeController : Controller
{
// GET: Employee
DataLayer.WebapplicationContext db = new DataLayer.WebapplicationContext();
public ActionResult GetEmployees()
{
var data = db.Employees.ToList();
var camelCaseFormatter = new JsonSerializerSettings();
camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
var jsonResult = new ContentResult
{
Content = JsonConvert.SerializeObject(data, camelCaseFormatter),
ContentType = "application/json"
};
return jsonResult;
//return new HttpStatusCodeResult(404, "Our custom error message...");
}
When i run this project i saw empty rows , it's above picture show my problem.
Picture
And this is console log enter image description here
I'm try this code and solve it my problem.In EmployeeController change ActionResult to JsonResult
public JsonResult GetEmployees()
{
using (WebapplicationContext Obj = new WebapplicationContext())
{
List<Employee> Emp = Obj.Employees.ToList();
return Json(Emp, JsonRequestBehavior.AllowGet);
}
}

HTML Table gets randomly "unsorted", dont know why

Problem
I am making a Meteor.js app, and are importing .csv files via Papaparse.js, which I save in a Mongo collection for later use in a table. The data is saved in a standard Papaparse.js structure:
results = {
data: [ ... ], // parsed data
errors: [ ... ], // errors encountered
meta: { ... } // extra parse info
}
The data array looks like this (from Chrome console):
image
I output this in a front-end view, where this data is shown as a table. But sometimes, the data gets all unsorted. This often happens if I move the DB to another server or import the DB to local. Look at this image for a comparison: image
The question is why, and how I can fix it.
This is my table template:
(note that projectData.data is from Iron Router, which is the Papaparse data (results.data))
<template name="table">
<div class="table-responsive">
<table class="table table-striped table-hover sortable-theme-bootstrap table-fixedheader" data-sortable>
<thead>
<tr>
{{#each addStatusColToArray projectData.meta.fields}}
<th>{{this}}</th>
{{/each}}
<th class="data-controls-header"></th>
</tr>
</thead>
<tbody>
{{#each projectData.data}}
<tr>
{{#each tableObjectToKeyPairs this}}
<td class="{{key}}">
{{value}}
</td>
{{/each}}
<td class="data-controls">
<span class="glyphicon glyphicon-menu-right" aria-hidden="true"></span>
</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
</template>
And this is the corresponding JS file:
Template.embedTable.helpers({
rowClassPropId: function (parentContext) {
var colLink = parentContext.projectData.meta.colLink;
var propId = this[colLink];
return propId;
},
tableObjectToKeyPairs: function (object) {
var filteredObject = _.omit(object, "_id"); // Omit the "_id" value
return _.map(filteredObject, function (value, key) {
return {
key: key,
value: value
};
});
}
});
Template.registerHelper("addStatusColToArray", function (array) {
if (array) {
array.push("Status"); // Pushes the "Status" last into array
return array; // Returns the modified array
}
});

Categories