Laravel and vue.js validation - json

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

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

TypeError: Cannot read property 'reduce' of undefined in react

I have a form in which I am asking the user to input field values for a couple of fields, storing the field values in an state and displaying the state values in a customised format.
So, I have a couple of input fields and a submit button:
<button onClick={this.handleSubmit}>Submit</button>
{
this.state.credentials &&
//<Credentials value={this.state}/>
<Credentials value={JSON.stringify(this.state, undefined, 2)} />
}
The Credentials function convert the state of the component in JSON format:
const Credentials = ({value} ) => {
return <pre>{formatState(value)}</pre>;
}
The formatState function will basically manipulate the state values and display them in the way I want:
function formatState(state) {
console.log("hi")
console.log(state);
const output = state.groups.reduce((final, s)=> {
console.log(output)
const values = Object.keys(s).reduce((out, o)=> {
out[o] = s[o].map(k => Object.values(k))
return out;
}, {})
final = {...final, ...values}
return final;
}, {})
console.log(output)
}
The state looks like this:
{
"groups": [
{
"typeA": [
{
"name": "abc"
},
{
"number": "13,14"
}
],
"typeB": [
{
"country": "xyz"
},
{
"date1": "2019-05-14"
}
]
}
]
}
But I want the output like this:
groups: {
"typeA": [[abc],[13,14]],
"typeB": [[2019-05-14],[xyz]]
}
SO, reduce function is used to convert the state into the following output. But I getting the error :
"TypeError: Cannot read property 'reduce' of undefined"
Please can anybody tell me why this is happening.
Error is here <Credentials value={JSON.stringify(this.state, undefined, 2)} />. JSON.stringify produces string representaion of some object (this.state in your case). Argument state of formatState has type of string. It seems that you want to have state arguemnt to be object. So you should do
<Credentials value={this.state} />

Some JSON objects is undefined

So I'm working a bit with nodeJS and Steam API to try and make a trade bot
I need to know what items was recieved, but when I do I get
undefined
Here's the JSON:
{
"partner":{
"universe":1,
"type":1,
"instance":1,
"accountid":369917733
},
"id":"2112720622",
"message":"No need to accept, just testing out a bot.",
"state":3,
"itemsToGive":[
],
"itemsToReceive":[
{
"appid":730,
"contextid":"2",
"assetid":"10168993563",
"classid":"1989300153",
"instanceid":"302028390",
"amount":1,
"missing":true,
"icon_url":"IzMF03bi9WpSBq-S-ekoE33L-iLqGFHVaU25ZzQNQcXdB2ozio1RrlIWFK3UfvMYB8UsvjiMXojflsZalyxSh31CIyHz2GZ-KuFpPsrTzBG0qe6yD3n-ZDLdYXKOTVxqTudcPGjZrGLx5ujCF2nASeh-EF9XdfEAo2JLNZiKahtv0oMVu2u_0UdyEhk6f9BKZAarxm1OMLh9m3IWGBD1M58",
"icon_url_large":"IzMF03bi9WpSBq-S-ekoE33L-iLqGFHVaU25ZzQNQcXdB2ozio1RrlIWFK3UfvMYB8UsvjiMXojflsZalyxSh31CIyHz2GZ-KuFpPsrTzBG0qe6yD3n-ZDLdEC3YDlltU-cLND7c92Hxt-SVFGqfFe54SgACdfcFoDJPP82AOBtrhdZZ-Ga9zhwzDhgvNMZJfACpx2EfJbQ1xDhPJM5amiekAf1NktA",
"icon_drag_url":"",
"name":"Sealed Graffiti | Still Happy (Desert Amber)",
"market_hash_name":"Sealed Graffiti | Still Happy (Desert Amber)",
"market_name":"Sealed Graffiti | Still Happy (Desert Amber)",
"name_color":"D2D2D2",
"background_color":"",
"type":"Base Grade Graffiti",
"tradable":true,
"marketable":true,
"commodity":true,
"market_tradable_restriction":7,
"fraudwarnings":[
],
"descriptions":[
{
"type":"html",
"value":"This is a sealed container of a graffiti pattern. Once this graffiti pattern is unsealed, it will provide you with enough charges to apply the graffiti pattern <b>50</b> times to the in-game world.",
"app_data":""
},
{
"type":"html",
"value":" ",
"app_data":""
},
{
"type":"html",
"value":"",
"color":"00a000",
"app_data":{
"limited":"1"
}
}
],
"owner_descriptions":[
],
"actions":[
{
"name":"Inspect in Game...",
"link":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S%owner_steamid%A%assetid%D9253357711394385702"
}
],
"market_actions":{
"0":{
"name":"Inspect in Game...",
"link":"steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D9253357711394385702"
}
},
"tags":[
{
"internal_name":"CSGO_Type_Spray",
"name":"Graffiti",
"category":"Type",
"category_name":"Type"
},
{
"internal_name":"normal",
"name":"Normal",
"category":"Quality",
"category_name":"Category"
},
{
"internal_name":"Rarity_Common",
"name":"Base Grade",
"category":"Rarity",
"color":"b0c3d9",
"category_name":"Quality"
},
{
"internal_name":"Tint5",
"name":"Desert Amber",
"category":"SprayColorCategory",
"category_name":"Graffiti Color"
}
],
"id":"10168993563",
"owner_actions":[
],
"market_marketable_restriction":0
}
],
"isOurOffer":true,
"created":"2017-05-13T09:50:24.000Z",
"updated":"2017-05-13T09:50:48.000Z",
"expires":"2017-05-27T09:50:24.000Z",
"tradeID":"1915564581201455085",
"fromRealTimeTrade":false,
"confirmationMethod":0,
"escrowEnds":null,
"rawJson":"{\n\t\"tradeofferid\": \"2112720622\",\n\t\"accountid_other\": 369917733,\n\t\"message\": \"No need to accept, just testing out a bot.\",\n\t\"expiration_time\": 1495878624,\n\t\"trade_offer_state\": 3,\n\t\"items_to_receive\": [\n\t\t{\n\t\t\t\"appid\": \"730\",\n\t\t\t\"contextid\": \"2\",\n\t\t\t\"assetid\": \"10168993563\",\n\t\t\t\"classid\": \"1989300153\",\n\t\t\t\"instanceid\": \"302028390\",\n\t\t\t\"amount\": \"1\",\n\t\t\t\"missing\": true\n\t\t}\n\t],\n\t\"is_our_offer\": true,\n\t\"time_created\": 1494669024,\n\t\"time_updated\": 1494669048,\n\t\"tradeid\": \"1915564581201455085\",\n\t\"from_real_time_trade\": false,\n\t\"escrow_end_date\": 0,\n\t\"confirmation_method\": 0\n}"
}
I can easily get partner, id, message, state, isOurOffer and all the time things, but when I try to get itemsToRecieve, it just throws undefined
The JSON is gathered through an event and the above is the exact JSON that I recieved
This is the event:
manager.on('sentOfferChanged', function(offer, oldState) {
var state = offer.state;
if(state == 3) {
console.log("Offer " + offer.id + " was accepted");
console.log("[Offer #" + offer.id + "] The following items was recieved: ");
console.log(offer.itemsToReceive);
}
});
Why would it do that for only one of the objects?
Maybe you can use a for to log each item of itemToReceive.
Something like this:
manager.on('sentOfferChanged', function(offer, oldState) {
var state = offer.state;
if(state == 3) {
console.log("Offer " + offer.id + " was accepted");
console.log("[Offer #" + offer.id + "] The following items was recieved: ");
for(var i in itemstoReceive)
{
var name = itemsToReceive[i].name;
console.log(name);
}}
});

How to get an json object in JsonArray using Mongoose

I am trying to update a json object in an array using the following code. The code seems to be finding the json object in the array, however, it fails to update the json object inside the json array. It doesn't give any error so that's what makes it more confusing.
function addOrUpdateAppointment(jsonObject, isDatabaseOperationSuccessful) {
var docID = jsonObject.doctorID; // this is _id from db sent to the doctor upon logging in
console.log("jsonPssed: ", {_id : docID});
DoctorModel.findOne({_id : docID, 'appointmentList.patientID': jsonObject.appointment.patientID}, {'appointmentList.$.patientID': jsonObject.appointment.patientID},function(err, foundData) {
console.log("found data", foundData);
if(err) {
console.error("error in find doctor for adding the appointment", err);
isDatabaseOperationSuccessful(false, foundData);
return;
}
else {
// since no document matched your query, add the appointment
if (!foundData) {
DoctorModel.update(
{_id: docID},
{$push: {appointmentList: jsonObject.appointment}},
function(err, pushedData) {
if(err) {
console.error("error in adding", err);
isDatabaseOperationSuccessful(false, pushedData);
}
else {
console.log("adding successful", pushedData, "inserted: ", jsonObject.appointment);
isDatabaseOperationSuccessful(true, pushedData);
}
}
);
}
// since that appointment already exists, update it
else {
foundData.update({'_id':docID,'doctors.appointmentList.patientID' : jsonObject.appointment.patientID}, {$set: {'doctors.appointmentList.$.dateAndTime': jsonObject.appointment.dateAndTime}},
function(err, updatedData) {
if (err) {
console.error("error in updating", err);
isDatabaseOperationSuccessful(false, foundData);
}
else {
if (!updatedData) {
console.log("updating failed", updatedData);
isDatabaseOperationSuccessful(true, foundData);
}
else {
console.log("updating successful", updatedData);
isDatabaseOperationSuccessful(true, foundData);
}
}
}
);
}
}
});
}
Schema:
doctorSchema = mongoose.Schema({
name : String,
appointmentList : Array // array of jsonObjects of dates and time
});
Data that I am passing to addOrUpdateAppointment(),
{
"docID": "id assigned by mongoDB",
"appointment": {
"patientID": "id assigned by mongoDB",
"dataAndTime": "IIII"
}
}
Your code is almost correct just change foundData with DoctorModel when you want to update the data. So the code becomes:
else {
DoctorModel.update({'_id':docID, 'appointmentList.patientID' : jsonObject.appointment.patientID}, {$set: {'appointmentList.$': jsonObject.appointment}},
function(err, updatedData) {....});

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

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*/});