im building an gallery app and i need it to be in tree format , im using the jstree extension to build it , and i need the json to be in this format:
$(function () {
$("#demo1").jstree({
"json_data" : {
"data" : [
{
"data" : "A node",
"metadata" : { id : 23 },
"children" : [ "Child 1", "A Child 2" ]
},
{
"attr" : { "id" : "li.node.id1" },
"data" : {
"title" : "Long format demo",
"attr" : { "href" : "#" }
}
}
]
},
"plugins" : [ "themes", "json_data", "ui" ]
}).bind("select_node.jstree", function (e, data) { alert(data.rslt.obj.data("id")); });
});
and im using this database:
categorys:
id
name
id_father
products:
id
name
price
category_id
please help me guys , >_< , im using an MVC structure in my project and its possible to do things like foreach(modelinstance as model) ...
help i realy need it and i have no idea how to build it
This is the function that I use, youll need CNestedSetBehavior in your model though, I recomend this way of setting up hierarquical data, as it is much faster to retrieve:
protected function formatJstree(){
$categories = $this->descendants()->findAll();
$level=0;
$parent = 0;
$data = array();
foreach( $categories as $n => $category )
{
$node = array(
'data'=> "{$category->title}",
'attr'=>array('id'=>"category_id_{$category->category_id}")
);
if($category->level == $level){
$data[$parent]["children"][] = $node;
}
else if($level != 0 && $category->level > $level){
if(!isset($data[$n]["children"])){
$data[$n]["children"] = array();
}
$data[$parent]["children"][] = $node;
}
else
{
$data[] = $node;
$parent = $n;
}
$level=$category->level;
}
return $data;
}
Related
I am facing a problem. I have this json log
{
"log": "Log Info : { \"datetime\" : \"datetime\", \"field1\" : \"value1\", \"field2\" : \"value2\", \"field3\" : \"value3\", \"field4\" : \"value4\", \"field5\" : \"value5\", \"field6\" : \"value6\", \"field7\" : \"value7\", \"field8\" : \"value8\", \"field9\" : \"value9\", \"field10\" : \"value10\", \"field11\" : \"value11\"}\n",
"stream": "stdout",
"kubernetes": {
"pod_name": "pod_name",
"namespace_name": "namespace_name",
"pod_id": "pod_id",
"host": "host",
"container_name": "container_name",
"docker_id": "docker_id",
"container_hash": "container_hash",
"container_image": "container_image"
}
}
I need to get all field inside "log" key. These fields will be increased, so I need to get all fields inside log dynamically. I am using this code to parse json, but the output is this. Maybe someone can help me? Thanks.
const readFile = require("fs").readFile;
readFile("log.json", (err, data) => {
if (err) throw err;
const log = JSON.parse(data);
console.log(log);
});
Output:
{
log: 'Log Info : { "datetime" : "datetime", "field1" : "value1", "
field2" : "value2", "field3" : "value3", "field4" : "value4", "field5" :
"value5", "field6" : "value6", "field7" : "value7", "field8" : "value8"
, "field9" : "value9", "field10" : "value10", "field11" : "value11"}\n',
stream: 'stdout',
kubernetes: {
pod_name: 'pod_name',
namespace_name: 'namespace_name',
pod_id: 'pod_id',
host: 'host',
container_name: 'container_name',
docker_id: 'docker_id',
container_hash: 'container_hash',
container_image: 'container_image'
}
}
You need to JSON.parse also the "inner" json (after you clean it from the prefix)
var obj = {
"log": "Log Info : { \"datetime\" : \"datetime\", \"field1\" : \"value1\", \"field2\" : \"value2\", \"field3\" : \"value3\", \"field4\" : \"value4\", \"field5\" : \"value5\", \"field6\" : \"value6\", \"field7\" : \"value7\", \"field8\" : \"value8\", \"field9\" : \"value9\", \"field10\" : \"value10\", \"field11\" : \"value11\"}\n",
"stream": "stdout",
"kubernetes": {
"pod_name": "pod_name",
"namespace_name": "namespace_name",
"pod_id": "pod_id",
"host": "host",
"container_name": "container_name",
"docker_id": "docker_id",
"container_hash": "container_hash",
"container_image": "container_image"
}
}
var str = (obj.log).substring(obj.log.indexOf(':') + 1);
//console.log(str)
var result = JSON.parse(str);
console.log(result)
Before all
I have model for image as simple as
return [
'id' => 'ID',
'parent_id' => 'Parent ID',
'photo' => 'Photo', <= just for filename
];
the case is
Create Parent model then save then redirect to form for uploading images related to its parent.
all uploading function work proprerly but no with delete function
This is my upload image form
echo FileInput::widget([
'model' => $photo,
'attribute' => 'photo',
'options'=>[
'accept'=>'image/*',
'multiple'=>true
],
'pluginOptions' => [
'uploadUrl' => Url::to(['/controller/upload', 'id'=> $parent->id]),
'initialPreview'=>$pre-initViews-data,
'initialPreviewAsData'=>true,
'initialCaption'=>"Foto Tersangka",
'initialPreviewConfig' => $pre-initConfigs-data,
'overwriteInitial'=>true,
//'deleteUrl'=> Url::to(['/controller/deletephoto']), <= case 2
'showPreview' => true,
'showRemove' => false,
'showUpload' => false,
'maxFileSize'=>2800
],
'pluginEvents' => [
'fileuploaded'=>"function(event, data, previewId, index){
console.log(data);
}",
]
]);
And here my controller side
$imageFile = UploadedFile::getInstance($model, 'photo');
$directory = Yii::$app->basePath. '/images/';
if ($imageFile) {
$fileName = Yii::$app->security->generateRandomString(). '.' . $imageFile->extension;
$filePath = $directory . $fileName;
if ($imageFile->saveAs($filePath) && $model->save(false)) {
$path = '/images/temp/' . $fileName;
Image::thumbnail($directory.$fileName, 120, 120)
->save(Yii::$app->basePath.$path, ['quality' => 80]);
$response = [];
$reponse['initialPreview'] = \Yii::$app->request->BaseUrl.'/images/'.$fileName;
$reponse['initialPreviewConfig']=[
'caption'=>'',
'width'=>'90px',
'key'=>$model->id,
'url'=>Url::to(['/controller/deletephoto']),
'extra'=>['id'=>$model->id]
];
echo json_encode($reponse);
}
}
And will produce JSON data like this :
{
"initialPreview": "\/web\/images\/Kl1IJOabLs5ENzzgkuW8ln_TILcDumy9.png",
"initialPreviewConfig": {
"caption": "",
"width": "90px",
"key": 38,
"url": "\/web\/index.php?r=controller%2Fdeletephoto",
"extra": {
"id": 38
}
}
}
The issue
I try different way like :
case 1 :
at form widget withoud pluginOptions => deleteUrl'=> Url::to(['/controller/deletephoto']),
upload process success, response from controller initialPreview overwriting initial as expected, but initialPreviewConfig seems doesnt fit, so delete button doesnt work/ doesnt give any process when clicked.
case 2 :
at form widget with pluginOptions => deleteUrl'=>
Url::to(['/controller/deletephoto']) , upload process as expected, but when i click delete button post action didnt parse key as below
Query string
r : controller/deletephoto
Form data
key : {empty key}
Finally
Ive spend huge amount of hours, Please review my code, is there something wrong?
a Big thanks for your help.
UPDATE ISSUE RESOLVED
after long hours finally i got the way..
replace
$response = [];
$reponse['initialPreview'] = \Yii::$app->request->BaseUrl.'/images/'.$fileName;
$reponse['initialPreviewConfig']=[
'caption'=>'',
'width'=>'90px',
'key'=>$model->id,
'url'=>Url::to(['/controller/deletephoto']),
'extra'=>['id'=>$model->id]
];
echo json_encode($reponse);
with
return Json::encode([
'initialPreview' => \Yii::$app->request->BaseUrl.'/images/'.$fileName,
'initialPreviewConfig' => [
[
'caption'=>'',
'width'=>'90px',
'key'=>$model->id,
'url'=>Url::to(['/controller/deletephoto']),
'extra'=>['id'=>$model->id]
],
],
]);
dont know why this happen,
My attempts at retrieving the value of a firebase record are failing. My JSON is as follows:
{
"accounts" : {
"-KRPSyO4B48IpBnHBTYg" : {
"dateCreated" : "",
"email" : "",
"provider" : "",
"userId" : ""
}
},
"products" : {
"-KUKRafaNurpFhGF4jQa" : {
"name" : ""
}
},
"total" : 1
}
I'm trying to return the value of "total". Here's the latest attampt:
var totals = firebase.database().ref('total').once('value', function(products) {});
$scope.totalPosts = totals;
and my HTML:
<div class="card" ng-controller="myController">{{totalPosts}}</div>
All I'm getting is an empty {}. What am I doing wrong?
Thanks in advance!
Firebase queries are asynchronous, try this.
firebase.database().ref('total').once('value', function(products) {
$scope.totalPosts = products.val();
});
Read and write Data
I have a jQuery datatable that uses an Ajax data source. The table is defined as follows:
$("#tblNotes").DataTable({
"ajax" : {
"url": "/projects/ajaxGetProjectNotes/",
"type" : "post",
"dataType" : "json",
"data" : {"idProject" : "b92792db-9ea6-49bf-b4dc-1cdf3f441148"}
},
"columns" :
[
{"data" : "dComment", "width" : "130px", "orderable" : true},
{"data" : "cComment", "width" : "270px", "orderable" : false}
]
});
The ajax response from the php script is:
[{"dComment":"","cComment":""}]
I am getting an error:
TypeError: aData is undefined
for ( i=0 ; i<aData.length ; i++ ) {
-------------^
The error is coming from datatables.js (line 15748, col 18).
Here's the source of the ajax source (and the accompanying model function that retrieves the data). Note that this is codeigniter based code (but I don't think that will make much of a difference):
function ajaxGetProjectNotes(){
$id = $_POST["idProject"];
$notes = $this->projects_model->getNotes($id);
if(!isset($notes[0]["cComment"])){
$notes[0]["dComment"]="";
$notes[0]["cComment"]="";
}
echo json_encode($notes);
}
The model code:
function getNotes($idProject){
$this->db->select("*")
->from("projectnotes")
->where("idProject", $idProject);
$query = $this->db->get();
$aResult = $query->result_array();
return $aResult;
}
The error is occuring when the page loads.
Any assistance would be appreciated...
How to check "no_cover" value in thumbnail[0] and replace it to asset/sss.jpg for show listpage
I try to set <img src="{{item.LINKS.thumbnail[0]}}"> in Listpage.html ,this show only thumbnail[0] is http://xxx.jpg, http://xxx.jpg , ,But I have no idea to set "no_cover"
myjson
" DOCSET":{
"DOC":[
{
"LINKS":{
"thumbnail":"http://yyy.jpg",
"thumbnail":"http://....jpg"}
}],
"DOC":[
{
"LINKS":{
"thumbnail":"http://xxx.jpg",
"thumbnail":"http://....jpg"}
}],
"DOC":[
{
"LINKS":{
"thumbnail":"no_cover", <<<<
"thumbnail":"http://....jpg"}
}]
}
EDIT - HOW YOUR JSON SHOULD LOOK
Since I (ivaro18) believe you wrote your JSON by hand and did not copy a response object. Let me show you what valid JSON looks like:
{
"DOCSET" : [
{
"DOC" : {
"LINKS" : [
{
"thumbnail" : "http://.....jpg"
},
{
"thumbnail" : "http://.....jpg"
}
]
}
},
{
"DOC" : {
"LINKS" : [
{
"thumbnail" : "http://.....jpg"
},
{
"thumbnail" : "http://.....jpg"
}
]
}
},
{
"DOC" : {
"LINKS" : [
{
"thumbnail" : "no_cover"
},
{
"thumbnail" : "http://.....jpg"
}
]
}
}
]
}
END OF EDIT
listpage.html
<ion-list>
<ion-item *ngFor="let item of foundRepos">
<ion-thumbnail item-left >
<img src="{{item.LINKS.thumbnail[0]}}"> <!--I have no idea to set it -->
</ion-thumbnail>
</ion-list>
list.page.ts
this.http.get("my_url")
.subscribe(data =>{
this.foundRepos = data.json().DOCSET.DOC;
},error=>{
err => console.error(err),
() => console.log('getRepos completed')
);
So, first of all your JSON you've posted was invalid. edited your question with what it probably is (since you are printing it as you say)
What I understand from your problem is the following, you have <img src="{{item.LINKS.thumbnail[0]}}"> but this throws a 404 when no_cover is returned, that's why, when item.LINKS.thumbnail[0] is equal to 'no_cover' you want to show the image assets/sss.jpg
So, how can we use this to show 'assets/sss.jpg' instead of 'no_cover'? It's called the Elvis operator ( ? : )
Let's assume the following construction for an if-statement:
if(expression) {
result = whenExpressionIsTrue
} else {
result = whenExpressionIsFalse
}
Which we can rewrite with the Elvis operator like this:
result = someExpression ? whenExpressionIsTrue : whenExpressionIsFalse
So, let's check out your problem, how can we do this with an if-statement?
if(item.LINKS.thumbnail[0] == 'no_cover') {
someVariable = 'assets/sss.jpg';
} else {
someVariable == item.LINKS.thumbnail[0];
}
Now shorten it with the Elvis operator:
someVariable = item.LINKS.thumbnail[0] == 'no_cover' ? 'assets/sss.jpg' : item.LINKS.thumbnail[0];
Now this can be used in your HTML like so:
<img
[src]="item.LINKS.thumbnails[0] == 'no_cover' ? 'assets/sss.jpg' : item.LINKS.thumbnails[0]"
/>