how to create a javascript function with parameters in another javascript file to use within another javascript? - function

hey, good day. im creating a program that would load a data from a server into a jqgrid. what im trying to do now is create a function from a separate javascript file and just use that function in my other javascript-jqgrid-load-data. here's my code in javascript:
$("#tbl").jqGrid({
url: '',
datatype: 'local',
jsonReader : {
root: function(obj) {
//some codes here
return root;
},
page: "page",
total: "pageCount",
records: "rows",
repeatitems:false,
id: "0"
},
serializeGridData: function(postData) {
var jsonParams = {
.
.//some codes here
.
'sort_fields': postData.sidx
};
if (postData.sord == 'desc')
{
..//some codes
}
else
{
...//some codes
}
jpar = jsonParams;
return 'json=' + jsonParams;
},
loadError: function(xhr, msg, e) {
showMessage('msg error');
},
colNames:['ID',...'Type'],
colModel:[
...//col model
],
rowNum:5,
.
.
.//some codes here
loadonce:false,
caption: "Main Account Group"
});
i want to separate the code:
jsonReader : {
root: function(obj) {
//some codes here
return root;
},
page: "page",
total: "pageCount",
records: "rows",
repeatitems:false,
id: "0"
},
and this:
serializeGridData: function(postData) {
var jsonParams = {
.
.//some codes here
.
'sort_fields': postData.sidx
};
if (postData.sord == 'desc')
{
..//some codes
}
else
{
...//some codes
}
jpar = jsonParams;
return 'json=' + jsonParams;
},
loadError: function(xhr, msg, e) {
showMessage('msg error');
},

I wrote my answer your your next question so that it answer on both from your question. The main idea is that you can either use global functions or better redefine jqGrid defaults with respect of
jQuery.extend(jQuery.jgrid.defaults, {/*your changes to the defaults*/});

Related

How to interpret htlm and css anotation in ajax data to pdfhtml5 datatable

I have a problem exporting with pdfhtml5. I have data on datatable with HTML and CSS style and want to visualize it on pdf or another plugin.
this is the variable exportOptions
var thisExportOptions = {
exportOptions: {
rows: function(idx, data, node) {
var checkedB = sontCoches(".dt-class-checkbox", "entireRow");
var dt = new $.fn.dataTable.Api('#datatable-configuration');
$(checkedB).each(function(i, v) {
dt.row(this).select();
});
var selected = dt.rows({ selected: true }).indexes().toArray();
if (selected.length === 0 || $.inArray(idx, selected) !== -1)
return true;
return false;
},
columns: ':visible'
}
};
and this for datatable id
var table = $('#datatable-configuration').DataTable({
"ajax": {
"url": "/backend/index.php",
"dataType": "json",
"type": "GET",
"data": {
"app": get ["app"],
"module": get ["module"],
"element": cElement,
"action": "serverside",
"actionParent": get ["action"],
//"get": get,
}
},
"buttons": [
$.extend(true, {}, thisExportOptions, { text: 'Imprimer', extend: 'print' }),
$.extend(true, {}, thisExportOptions, { text: 'PDF', extend: 'pdfHtml5' }),
{ extend: 'colvis', text: 'Export colonnes', className: 'btn-primary', columns: ":not(.notConcernedByColvis)" }
],
"fnStateLoad": function(oSettings) {
return JSON.parse(localStorage.getItem('dataTableStore'));
},
"stateSaveParams": function(settings, data) {
data.columns.forEach(function(column) {
delete column.visible;
});
}
)}
Php code
$datas[$key]['nom'] = "<span class='font-weight-bold text-success'>" . $brute->raison_sociale . "</span>";
$datas[$key]['nom'] .= (!empty($brute->rcs_siret)) ? "<br /><small><span class='font-weight-bold'>RCS : </span><span class='right'>" . $brute->rcs_siret . "</span></small>" : "";
$datas[$key]['autres'] = '';
And the pdf file is like this
Pdf export with no css and HTML no interpreted
Finally I found WkHtmlToPdf it can convert HTML page to PDF file.
It's very helpfull and free, PHP WkHtmlToPdf provides a simple and clean interface to ease PDF and image creation when you want only use free solution on your project.
For more information : https://github.com/mikehaertl/phpwkhtmltopdf

Laravel and vue.js validation

From my Laravel api I receive the following validation errors within json:
{
"error": {
"billabletime": [
"The billabletime field is required."
],
"time": [
"time bust be a integer."
]
}
}
So how would I show them in vue.js? Right now I've this but that's obviously not working:
showError (message) {
swal({
title: "Fout",
text: message.error,
type: "error",
timer: 2000,
showConfirmButton: false
});
}
Like this:
var errorString = '';
if (message.hasOwnProperty('error')) {
for(var prop in message.error) {
if (Array.isArray(prop)) {
for (var msg in prop) {
errorString += prop[msg] . '<br/>';
}
} else {
errorString += message.error[prop] . '<br/>';
}
}
}
Something simple like this should give you the desired result. Not necessary to know index names.
Edit added functionality to handle stirng/array

typeahead / filter / JSON parse?

Trying to 'parse/read' an external .json file on my typeahead code, but the .json file (which I cannot modify) looks like:
{"**cms_countries**":
[{"**cms_country**":
[{"**countrydisplayname**":"Afghanistan"}
,{"countrydisplayname":"Albania"} ,{"countrydisplayname":"Algeria"}
... ... ... ,{"countrydisplayname":"Zimbabwe"} ] } ,{"TotalRecords":
[ {"TotalRecords":"246"} ] } ] }
So, I think my problem is to know how to parse/read/assimilate/integrate/adopt this .json file, having
cms_countries ,
cms_country ,
and then, my countrydisplayname field on it. (have you seen the tree here ?)
This is my code:
$(document).ready(function() {
var searchablePlaces = new Bloodhound({
datumTokenizer : Bloodhound.tokenizers.obj.whitespace("countrydisplayname"),
queryTokenizer : Bloodhound.tokenizers.whitespace,
prefetch : 'countries.json',
remote : {
url : 'countries/%QUERY.json',
wildcard : '%QUERY',
filter : function(response) { return response.cms_country; }
},
limit : 10
});
searchablePlaces.initialize();
$('#remote .typeahead').typeahead(
{
hint : true,
highlight : true,
minLength : 2
},
{
name : 'countrydisplayname',
displayKey : "countrydisplayname",
source : searchablePlaces.ttAdapter()
})
});
But of course, it is not working:
ANY hint on how to organize my filter... ? or how to do to overcome my nested .json wrappers....
OK, I've got my code working now:
$(window).load(function(){
var movies = new Bloodhound({
limit: 10,
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'countries.json',
filter: function (movies) {
return $.map(movies.cms_countries[0].cms_country, function (paises) {
return {
value: paises.countrydisplayname
};
});
}
}
});
// Initialize the Bloodhound suggestion engine
movies.initialize();
// Instantiate the Typeahead UI
$('.typeahead').typeahead(
{
hint: true,
highlight: true,
minLength: 1
},
{
//displayKey: 'value',
displayKey: function (toto) {
return toto.value;
},
source: movies.ttAdapter()
});
});

Populate model of the model with sails js

I'm trying to populate model of the model with sails unfortunally it doesn't work.
I have 3 models
/**
Conversation.js
**/
module.exports = {
autoCreatedAt: false,
autoUpdatedAt: false,
tableName:'conversation',
attributes: {
idConversation:{
columnName:'IDCONVERSATION',
primaryKey:true,
autoIncrement:true,
unique:true,
type:'integer',
index:true
},
dateStartConversation:{
columnName:'DATEDEBUT',
type:'date',
index:true
},
user1:{
columnName:'IDUSER1',
model:'user',
notNull:true
},
user2:{
columnName:'IDUSER2',
model:'user',
notNull:true
},
article:
{
model:'article',
columnName:'IDARTICLE',
notNull:true
}
}
};
/**
Article.js
**/
module.exports = {
autoPK: false,
autoCreatedAt: false,
autoUpdatedAt: false,
tableName:'article',
attributes: {
idArticle:{
type:'integer',
unique:true,
columnName:'IDARTICLE',
autoIncrement:true,
primaryKey:true
},
title:{
type:'string',
required:true,
columnName:'TITRE',
index:true,
notNull:true
},
utilisateur:{
model:'utilisateur',
columnName:'IDUTILISATEUR',
required:true,
notNull:true,
dominant:true
},
images:{
collection:'image',
via:'article'
},
conversation:{
collection:'conversation',
via:'article'
}
}
};
/**
Image.js
**/
module.exports = {
autoCreatedAt: false,
autoUpdatedAt: false,
tableName:'image',
attributes: {
idImage:{
columnName:'IDIMAGE',
primaryKey:true,
autoIncrement:true,
unique:true,
type:'integer'
},
pathImage:{
columnName:'PATHIMAGE',
required:true,
type:'string',
notNull:true
},
article:{
model:'article',
columnName:'IDARTICLE',
notNull:true,
dominant:true
}
}
};
As you can see in my model, an conversation its between Two user, about one article, and those article cas have one or many Images.
So I want to get all conversations of one user and I able to populate with article but I'm not able to populate article with Image below how I proceed
Conversation.find().populate('article').populate('user1').populate('user2').where({
or : [
{ user1: iduser },
{ user2: iduser }
]})
.then(function( conversations) {
var i=0;
conversations.forEach(function(element,index){
i++;
console.log("article "+index+" "+JSON.stringify(element.article));
Article.findOne({
idArticle:element.article.idArticle
}).populate('images').then(function(newArticle){
//I try to set article with the newArticle but it don't work
element.article=newArticle;
})
if(i==conversations.length){
res.json({
hasConversation:true,
conversation:conversations
});
}
});
})
Because deep populate is not possible using sails, I try to use a loop to populate each article with associate Images and set it in conversation, But article is never set in conversation.
How can I fix it ?
Judging by the if(i==conversations.length) at the end, you seem to have an inkling that you need to write asynchronous code. But you're iterating i inside of the synchronous forEach loop, so your response is happening before any of the database queries even run. Move the i++ and the if inside of the callback for Article.findOne:
Conversation.find().populate('article').populate('user1').populate('user2').where({
or : [
{ user1: iduser },
{ user2: iduser }
]})
.then(function( conversations) {
var i=0;
conversations.forEach(function(element,index){
console.log("article "+index+" "+JSON.stringify(element.article));
Article.findOne({
idArticle:element.article.idArticle
}).populate('images').then(function(newArticle){
// Associate the article with the conversation,
// calling `toObject` on it first
element.article= newArticle.toObject();
// Done processing this conversation
i++;
// If we're done processing ALL of the conversations, send the response
if(i==conversations.length){
res.json({
hasConversation:true,
conversation:conversations
});
}
})
});
})
You'll also need to call toObject on the newArticle instance before assigning it to the conversation, because it contains getters and setters on the images property which behave unexpectedly when copied.
I'd also recommend refactoring this to use async.each, which will make it more readable.
Until this is resolved (https://github.com/balderdashy/sails-mongo/issues/108), you can use this function that I developed to solve this: https://gist.github.com/dinana/52453ecb00d469bb7f12

Kendo Grid Drop-Down column with conditional formatting

I have a grid I'm working on, and some of the columns are Boolean (true/false). I want them to display as "Yes/No" in the column. I also am using a drop-down to change the value. The issue I am having is that once I select the value form the drop-down, it doesn't display the new value when I leave the line. But only if I'm going from "no" to "yes". I think it's something to do with the interaction between my template and the drop-down? That the value isn't getting set to "yes" from the drop down for the template, so it'd falling into the "no" logic.
Here is my data for the drop-down:
indData = [
{ Text: "Yes", boolValue: "true" },
{ Text: "No", boolValue: "false" }
];
And my definition for that column:
Copy code
{
field: "FreeAndReducedInd", width: "150px",
editor: indDropDownEditor,
title: "Free and Reduced",
template: ("# if (FreeAndReducedInd == true) { #" + "Yes" + "# } else { #" + "No" + "#}#")
},
And the editor code:
Copy code
function indDropDownEditor(container, options) {
$('<input data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
dataTextField: "Text",
dataValueField: "boolValue",
dataSource: indData
});
};
What do I have wrong?
thanks
Lisa
Update - I got an answer from Kendo, they suggested I add a Custom Binder and that seems to be working.
kendo.data.binders.widget.boolValue = kendo.data.Binder.extend({
init: function (widget, bindings, options) {
kendo.data.Binder.fn.init.call(this, widget.element[0], bindings, options);
this.widget = widget;
this._change = $.proxy(this.change, this);
this.widget.bind("change", this._change);
},
refresh: function () {
var value = this.bindings.boolValue.get();
this.widget.value(value.toString());
},
change: function () {
var value = this.widget.value();
this.bindings.boolValue.set(value === "true");
},
destroy: function () {
this.widget.unbind("change", this._change);
}
});
I also modified my editor:
function indDropDownEditor(container, options) {
$('<input data-bind="boolValue:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
dataTextField: "Text",
dataValueField: "boolValue",
dataSource: [
{ Text: "Yes", boolValue: "true" },
{ Text: "No", boolValue: "false" }
]
});
};
It would be better if you could give us the full code. Its easier to check locally before giving any solution. But try using the following in template. If it doesn't help please update your post with full code so I can recheck. Thanks.
template: "<td role='gridcell'> #= FreeAndReducedInd == true ? 'Yes' : 'No' # </td>"