Overwriting Original Values In Collections - javascript

I am fetching data from database and storing it on $groups. It has different created_at for each entry.
I want to overwrite on created_at field in collection, just before returning it to the view, and have nice ->diffForHumans() version.
$groupsArray = $messages;
foreach($groupsArray as $key => $group) {
var_dump($groupsArray[$key]['created_at']); // works: 2015-10-17 21:55:46.000000'
var_dump($groupsArray[$key]['created_at']->diffForHumans()); // Error: A two digit month could not be found Data missing
$groupsArray[$key]['created_at'] = $groupsArray[$key]['created_at']->diffForHumans(); // Not Working
}
return $groupsArray->toJson();
If I change groupsArray = $messages->toArray();, the '// Error' bit of above chunk changes to Call to a member function diffForHumans() on string.
Eventually, I need to return it as json as it is ajax request. I want to overwrite on created_at, so I can use group[i]['created_at'] in javascript part in the view, after returning and get Carbon versions.

First, make sure 'created_at' is in your $dates array in your model.
Like described on http://laravel.com/docs/5.1/eloquent-mutators#date-mutators
Second, you can iterate and update over a collection by doing the following:
$messages->transform(function ($item, $key) {
$item->difference = $item->created_at->diffForHumans(); // 10 hrs ago
return $item;
});
$messages->toJson();

use &you can replace the original value !
foreach($groupsArray as &$key => &$group) {
var_dump($groupsArray[$key]['created_at']);
var_dump($groupsArray[$key]['created_at']->diffForHumans());
$groupsArray[$key]['created_at'] = $groupsArray[$key] ['created_at']->diffForHumans(); // Not Working
}

Related

Deconstructing a JSON object

A JSON encoded array is passed from PHP to an HTML document. It is not at all clear how to deconstruct that array into javascript-usable pieces. For example, consider the following HTML:
<div id="options">{"foo":[{"id":1},{"id":3}], "bar":[{"id":2},{"id":4}]}</div>
The only a priori known element of this array is that the key id exists. The indices, I know, can be found with
var data = JSON.parse($("#options").text());
$.each(data, function(index) {
// index will be foo & bar
});
The use case is to use the index and id to add an attribute to elements in a document. I have not yet stumbled upon the technique to return the ids associated with each index. How best can that be done?
Edit - a clarification of the use case - the long story
I want to re-enable some options on a form based on properties of an entity (in a Symfony application). Disabled options cannot be modified, but are also not not persisted - their values are set to null. I've built a service to determine the option elements that are disabled and send those elements to the form document as a JSON object. I'm assuming for now that the specific options are not known until the form is created. In the example above, foo & bar represent possible options, and the ids correspond to the option. For example, a Household entity might have Reason options selected but disabled of "Low wages" (id = 3). This would show up in as ...id="options">{"reasons":[{"id":3}]}<.... I would the use this information to remove the disabled="disabled" attribute from the set of checkboxes for the Reason, id=3 (i.e., id="household_reasons_3") field. I hope this makes sense.
Edit #2, by request - the PHP code creating the object.
The result of getMetatData() appears in the document at #options. From the above edit, the Household entity is $object.
public function getMetaData($object) {
$data = array();
$className = get_class($object);
$metaData = $this->em->getClassMetadata($className);
foreach ($metaData->associationMappings as $field => $mapping) {
if (8 === $mapping['type']) {
$data[$field] = $this->extractOptions($object, $field);
}
}
return json_encode($data);
}
private function extractOptions($object, $field) {
$data = [];
$method = 'get' . ucfirst($field);
$itemName = substr($field, 0, -1);
$getter = 'get' . ucfirst($itemName);
$entity = $object->$method();
foreach ($entity as $item) {
if (method_exists($item, 'getEnabled') && false === $item->getEnabled()) {
$data[] = ['id' => $item->getId()];
}
}
return $data;
}
Long before the infinite monkey limit was reached I stumbled on a method to create the results I was looking for. My thanks go out to all who pushed for clarifications. So, for the object
{"foo":[{"id":1},{"id":3}], "bar":[{"id":2},{"id":4}]}
the script
var data = JSON.parse($("#options").text());
var i = 0
var output = [];
$.each(data, function(index, item) {
$.each(item, function(k, v) {
output[i] = "household_" + index + "_" + v.id;
i++;
});
});
output;
produces this:
["household_foo_1", "household_foo_3", "household_bar_2", "household_bar_4"]
I get the strings I need; I can take it from here.

Passing an array from Angular to php

I have a dropdown form where you can select one or more items. The selected items I want to send to a backend php script that will insert the selected values into a database.
This is my angular insert function:
insertRepair: function (id_telefon, id_culoare, arrayPiese) {
console.log(arrayPiese);
http.get('../php/insert_reparatii.php', {
params: {id_telefon: id_telefon, arrayPiese: arrayPiese,
id_culoare: id_culoare}
}).then(function () {
}
}
The call to this function is done like this:
serviceHttp.insertRepair($scope.phoneMP.selected.id, $scope.colorMP.selected.id, $scope.selectedPiesaMP.selected);
If I print into the console the arrayPiese array it will print for 2 selected items, something like this:
["Adezivi_Rama", "Polarizator"]
Now in the backend I retrieve the array list:
$arr = $_REQUEST['arrayPiese'];
If I print the $arr variable I get only one of two items printed.
Need to mention that I migrated from jquery to angular, and from jquery I was able to send the entire array like this:
var arrayPiese = [];
$('.select2-selection__choice').each(function () {
arrayPiese.push($(this).attr('id'));
});
The url looks like this arrayPiese=Adezivi_Rama&arrayPiese=Polarizator&id_culoare=1&id_telefon=18
Do I need to serialize the array before sending it to php? Or what would be the best approach in sending an array to backend??
You can pass array as json,
http.get('../php/insert_reparatii.php', {params: {id_telefon: id_telefon, arrayPiese:angular.toJson(arrayPiese),
id_culoare: id_culoare}
}).then(function () {
}
Then in your PHP script, convert json to PHP array,
$arrayPiese = json_decode($_GET['arrayPiese'], TRUE);
arrayPiese=Adezivi_Rama&arrayPiese=Polarizator will result in a single variable $_REQUEST['arrayPiese'] with the value Polarizator because the latter overwrites the first one.
If you want to pass an array, you have to append brackets to the query parameter name:
arrayPiese[]=Adezivi_Rama&arrayPiese[]=Polarizator
…which will result in a PHP variable $_REQUEST['arrayPiese'] with an array value like:
[
0 => 'Adezivi_Rama',
1 => 'Polarizator'
]

Retrieve data from PHP file using $.getJSON

I'm trying to set up a comments system on photos.
I understand how to use $.getJSON when the array is like this:
get.php:
$var = 5;
echo json_encode(array('var'=>$var));
main.php:
$.getJSON("get.php",function(data){
number = data.var; // number = 5
});
But I have a more complex thing.
My comments table has these 4 columns: id | photo_id | comment | date
For example let's say we're trying to retrieve the comment data from the photo with
photo_id == 1.
We don't know how many comments there might be.
In getcomments.php:
$photoid = 1;
$comment = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photoid'");
while($commentrow = $comment->fetch_assoc()) {
$comments[] = $commentrow;
}
Then you encode it:
echo json_encode($comments);
Which prints something like this (the photo has 2 comments):
[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]
How do I declare variables for the comments array?
$.getJSON("getcomments.php",function(data){
// how do I declare variables for the comments array, especially since you don't know how many there might be?
});
Additionally, I have two json arrays that need to be echoed within the same PHP file. i.e. echo json_encode(array('img1'=>$img1link)) and echo json_encode($comments); need to be echoed within the same PHP file, but it made the code stop working altogether.
If you want to display the comments you need to loop over the array. You can use for loop or forEach function.
$.getJSON("getcomments.php",function(data){
data.forEach(function(comment) {
$('div').append('<span>' + comment.comment + '</span>');
});
});
To display two JSONs you need to combine them into one JSON object.
echo json_encode(array('img' => $img1link, 'comments' => $comments));
[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]
Using this JSON, data is an array and you should manage it as an array. You can loop through it using simple loops (for, while...) or using new functional methods like forEach, map, filter....
Please try with this example:
$.getJSON("getcomments.php",function(data){
data.forEach(function(item, index, all) {
console.log(item.comment);
});
});
Declare an object, and push it to the array.
var commentsArr = [];
for (var i = 0; i < data.length; i++) {
var objToPush = {
id: data.id,
comment: data.comment,
date: data.date
}
commentsArr.push(objToPush);
}

Access Array of Objects after filtering

so I have a JSON object returned from a webservice. Now I want to:
get a subset which matches a categoryTitle i pass as parameter (this seems to work)
from my filtered resultset I want to get another array of objects (helpsubjects), and for each of this subjects I want to extract the SubjectTitle.
Problem: It seems my Array of HelpSubjects does not exist, but I can't figure out why and hope you could help.
Perhaps this piece of commented code makes it more clear:
$.fn.helpTopicMenu = function (data) {
that = this;
var categoryContent = contents.filter(function (el) {
return el.CategoryTitle == data.categoryTitle;
});
debug('categorys Content: ', categoryContent); //see below
var container = $('#subjectList');
var subjectList = categoryContent.HelpSubjects;
debug('Subjects in Category: ', subjectList); // UNDEFINED?!
$.each(subjectList, function (i, item) {
container.append(
$('<li></li>').html(subjectList[i].SubjectTitle)
);
});
the line debug('categorys Content: ', categoryContent); returns the following object as shown in the picutre (sadly I can't add a picture directly to the post yet, so here's the link): http://i.stack.imgur.com/0kKWx.png
so as I understand it, there IS actually a HelpSubjects-Array, each entry containing a SubjectTitle (in the picture there actually is only one entry, but I need to have the Artikel einfügen as my html.
Would be great if you can help me.
The variable categoryContent set is an array of objects.
Try debugging categoryContent[0].HelpSubjects and see if you can access the property. If so, you can also loop this array if need be.

How to append database values to JSON data

I have a JSON which lists the values from database. Below is the JSON data of 2 rows from the database.
[{"Name":"P1","Description":"pd1","Value":"v1","Attribute":"a1"},{"Name":"P1","Description":"pd1","Value":"v2","Attribute":"a2"}]
database values are the result of a left join query. Only 'Value' and 'Attribute' fields are different. Can I append that fields to JSON instead of multiple sets of record? I know there is 'push' to do this, but I am unaware where and how to use this in my code. below is the code for fetching values from db and serializing the values.
GetProfileDataService GetProfileDataService = new BokingEngine.MasterDataService.GetProfileDataService();
IEnumerable<ProfileData> ProfileDetails = GetProfileDataService.GetList(new ProfileSearchCriteria { Name = strProfileName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string strSerProfileDetails = javaScriptSerializer.Serialize(ProfileDetails);
context.Response.ContentType = "text/json";
context.Response.Write(strSerProfileDetails);
Below is my getJSON
$(document).ready(function () {
$.getJSON('ProfileHandler.ashx', { 'ProfileName': 'Profile 1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute+' : '+v.Value);
});
});
});
Please help me here.
There are several things you can do.
Store value and attribute as arrays:
[{"Name":"P1","Description":"pd1","Value":["v1", "v2"],"Attribute":["a1", "a2"]}]
Or store them as a 'symbol'-separated string:
[{"Name":"P1","Description":"pd1","Value":"v1;v2"],"Attribute":"a1;a2"]}]
In order to use the first case, you'll have to try and figure out how to format the ProfileDetails in order to have javaScriptSerializer.Serialize parse it correctly. You will likely have to convert your data first in order for this to work (i.e. convert value and attribute to arrays).
For the second case to work you could modify your GetProfileDataService.GetList method so that values and attributes are merged to symbol-separated strings (something like this: GROUP BY to combine/concat a column)

Categories