Extjs tree not able to load nested object - object

I have a class called Zone1s in java which has 2 fields text(name of zone) and list of Zone1s.
when i convert it to json i get following response :
{"text":"Papa","Zone1s":[{"text":"Beta1","Zone1s":[{"text":"BetaBeta1","Zone1s":[]},{"text":"BetaBeta2","Zone1s":[]}]},{"text":"Beta2","Zone1s":[]}]}
i wrote a Extjs model,store and panel below:
Ext.define('Zone1s', {
extend: 'Ext.data.Model',
fields: [
{ name: 'text', type: 'string' }
],
proxy: {
type: 'ajax',
url : 'test.htm',
reader: {
type : 'json',
record: 'Zone1s'
}
},
hasMany: {model: 'Zone1s', name: 'Zone1s'},
belongsTo: 'Zone1s'
});
var store =Ext.create('Ext.data.Store', {
model: 'Zone1s',
autoLoad: true
});
Ext.create('Ext.tree.Panel', {
title: 'Simple Tree',
width: 200,
height: 150,
store: store,
renderTo: Ext.getBody()
});
i am getting following error:
me.store.getRootNode is not a function...
Can anyone please Guide me where i am wrong ?
i have gone through
How do I show nested data into a tree?
but here my Zone1s can have Zone1s in themselves that's the difference.

You should add a root attribute to your Store :
var store =Ext.create('Ext.data.Store', {
model: 'Zone1s',
autoLoad: true,
root: {
text: 'Zone1s',
id: 'Zone1s',
expanded: true
}
});
If you do not want to see the root node, use the rootVisible attribute :
Ext.create('Ext.tree.Panel', {
title: 'Simple Tree',
width: 200,
height: 150,
store: store,
rootVisible : false,
renderTo: Ext.getBody()
});

Related

how to handle multiple request keys with the same value?

For this project, I'm building out models and passing in values from the body of a POST request. I want to understand how I should be declaring the models.
Sample of JSON which I want to be posted to MongoDB.
{
"signageId": "5cd857c4965f863b7c88d24a",
"parameters": {
"imageURL": "url.com",
"page": {
"pageHeight": "100", //want to change to "height"
"pageWidth": "100" //want to change to "width"
},
"density": {
"height": "300",
"width": "300"
}
}
}
I want to name pageHeight and pageWidth just "height" and "width" within the JSON, like I have done for the density segment, but I'm having difficulties knowing how to declare the models and grab the values from the request.
Model I'm using:
const ObjectSchema = new Schema({
signageId: {
type: String,
require: true
}
parameters: {
imageURL: {
type: String,
require: true
}
},
page: {
pageHeight: {
type: String
},
pageWidth: {
type: String
}
},
density: {
height: {
type: String
},
width: {
type: String
}
}
}
});
Post router
router.post('/', (req, res) =>{
const object = new Objects({
signageId: req.body.signageId,
imageURL: req.body.imageURL,
page: req.body.page,
pageHeight: req.body.pageHeight,
pageWidth: req.body.pageWidth,
density: req.body.density,
height: req.body.height,
width: req.body.width
});
try {
object.save();
res.json({object});
}
catch (err) {
res.json({message: err});
}
});
Your new object should be something like this.
const newObject = new Objects({
signageId: req.body.signageId,
parameters: {
imageURL: req.body.imageURL,
page: {
height: req.body.pageHeight,
width: req.body.pageWidth,
},
density: {
height: req.body.height,
width: req.body.width,
}
}
});
Notes:
1. Give your mongoose schema another name, in order to avoid javascript conflicts.
2. You can use height and width properties for different objects.
page: {
height: {
type: String
},
width: {
type: String
}
},
density: {
height: {
type: String
},
width: {
type: String
}
}
3. the model properties should be required, not require

jtable child table not POSTing key value

I have a Jquery jtable that has a child table. As far as I can see it is set up as per the example in the jtable demos. The main tables= (contacts) and the child tables (categories) display without any problem. My problem is that the delete action on the category child table is not posting the row key value (categoryID) as I would expect it to and I cannot see why not. The similar action on the main table posts its just fine. Note the two console.log lines in the code below that output the postData variable, the first one reports the ID of the contact table line (ID), but the second one prints an empty array instead of the CategoryID. Any help appreciated.
Thanks
function ReturnAjax(theurl, postdata, errorfn) {
return $.ajax({
url: theurl,
type: 'POST',
dataType: 'json',
data: postdata,
cache: false,
error: errorfn
});
}
$('#ContactsTableContainer').jtable({
title: 'Contacts',
paging: true,
pageSize: 30,
sorting: true,
defaultSorting: 'LastName ASC',
selecting: true,
selectOnRowClick: true,
openChildAsAccordion: true,
deleteConfirmation: false,
actions: {
listAction: function(postData, jtParams) {
console.log("ContactsTableContainer - Loading list from custom function...");
return $.Deferred(function($dfd) {
$.ajax({
url: 'ContactsData.php?action=list&jtStartIndex=' + jtParams.jtStartIndex + '&jtPageSize=' + jtParams.jtPageSize + '&jtSorting=' + jtParams.jtSorting,
type: 'POST',
dataType: 'json',
data: postData,
success: function(data) {
if(data['RowIDs']) { RowIDs = data['RowIDs'].toString().split(','); }
$dfd.resolve(data);
},
error: MyError
});
});
},
deleteAction: function(postData) {
console.log('deleting from contacts - custom function..., '+JSON.stringify(postData));
$.when(
ReturnAjax(
'ContactsData.php?action=list&ContactID='+postData['ID'],
postData,
MyError
)
).then(
function(data) {
if (data.Result != 'OK') { alert(data.Message); }
var msg = '';
var len = data.Records.length;
if(len>0) {
msg = '\t'+data.Records[0].Category;
for(var i=1 ; i<len ; i++) { msg += '\n\t'+data.Records[i].Category; }
msg = 'Contact is in the following categories\n'+msg;
}
msg += '\n\nConfirm deletion of this contact';
if(confirm(msg)) {
$.when(
ReturnAjax(
'ContactsData.php?action=delete',
postData,
MyError
)
).done(
$('#ContactsTableContainer').jtable('reload')
);
} else {
$('#ContactsTableContainer').jtable('reload'); // Had to put this here to ensure that same delete button could be used again
}
}
).fail( function() { console.log('ajax call went wrong'); } );
}, // end of delete action
}, // end of actions
fields: {
ID: {
key: true,
create: false,
edit: false,
list: false,
visibility: 'hidden'
},
Categories: {
title: '',
width: '5%',
sorting: false,
create: false,
display: function(contact) {
var $img = $('<img src="Images/layers.png" title="Show contact\'s categories" />');
//Open child table when user clicks the image
$img.click(function() {
console.log('display function (contact)..., '+JSON.stringify(contact));
$('#ContactsTableContainer').jtable(
'openChildTable',
$img.closest('tr'), //Parent row
{
title: contact.record.Name + ' - Categories',
selecting: true,
selectOnRowClick: true,
actions: {
listAction: 'ContactsData.php?action=list&ContactID=' + contact.record.ID,
deleteAction: function(postData) {
console.log('deleting from custom category function..., '+JSON.stringify(postData));
$.when(
ReturnAjax(
'ContactsData.php?action=deleteAssignment&ContactID=' + contact.record.ID,
postData,
MyError
)
).done(
$('#ContactsTableContainer').jtable('reload')
);
}
},
fields: {
CategoryID: { key: true, create: false, edit: false, list: false, visibility: 'hidden' },
ContactID: { type: 'hidden', defaultValue: contact.record.ID },
Category: { title: 'Category' }
}
},
function(data) { data.childTable.jtable('load'); }
);
});
//Return image to show on the person row
return $img;
}
},
FirstName: {
  title: 'Forename',
  width: '25%',
},
LastName: {
  title: 'Surname',
  width: '25%',
},
HomePhone: {
title: 'Phone',
width: '15%',
sorting: false,
},
Mobile: {
title: 'Mobile',
width: '15%',
sorting: false,
},
Email: {
title: 'Email',
width: '20%',
sorting: false,
},
Name: {
  type: 'hidden'
},
}
});
//Load list from server
$('#ContactsTableContainer').jtable('load');
OK, I solved it, sorry to bother anyone who may have spent time looking at this. The problem was that my child table variable names were wrong they should have been category_ID and Contact_ID

Grid store config throws "Uncaught TypeError: Cannot read property 'buffered' of undefined"

I have form and grid. the user must enter data in form fields then display related records in the grid.
I want to implement a search form, e.g: user will type the name and gender of the student,
then will get a grid of all students have the same name and gender.
So, I use Ajax to send form fields value to PHP and then create a json_encode which will be used in grid store.
I am really not sure if my idea is good. But I haven't found another way to do that.
The problem is there is a mistake in my store but I couldn't figure out what it is. I get this error:
Uncaught TypeError: Cannot read property 'buffered' of undefined
My View:
{
xtype: 'panel',
layout: "fit",
id: 'searchResult',
flex: 7,
title: '<div style="text-align:center;"/>SearchResultGrid</div>',
items: [{
xtype: 'gridpanel',
store: 'advSearchStore',
id: 'AdvSearch-grid',
columns: [{
xtype: 'gridcolumn',
dataIndex: 'name',
align: 'right',
text: 'name'
}, {
xtype: 'gridcolumn',
dataIndex: 'gender',
align: 'right',
text: 'gender'
}
],
viewConfig: {
id: 'Arr',
emptyText: 'noResult'
},
requires: ['MyApp.PrintSave_toolbar'],
dockedItems: [{
xtype: 'PrintSave_tb',
dock: 'bottom',
}]
}]
}
My Controller:
.
.
.
xmlhttp.open("GET","AdvSearch.php?search_name="+search_name,true);
xmlhttp.send(null);
My PHP script:
if (!$con) {
throw new Exception("Error in connection to DB");
}
$query ="SELECT name, gender FROM students WHERE name ILIKE '%$search_name%' ";
$result = pg_query($query);
while ($row = pg_fetch_array($result)) {
$Arr[] = array('name' => $row[0], 'gender' => $row[1]);
}
$searchResult_list = array();
$searchResult_list['success'] = true;
$searchResult_list['Arr'] = $Arr;
$searchResult_list['totalCount'] = count( $searchResult_list['Arr'] );
echo json_encode($searchResult_list);
if (!$result)
die("Error in query: " . pg_last_error());
pg_close($con);
My Store, Model:
Ext.define('AdvSearchPost', {
extend: 'Ext.data.Model',
proxy: {
type: 'ajax',
url: 'AdvSearch.php',
reader: {
type: 'json',
root: 'Arr',
totalProperty: 'totalCount'
}
},
fields: [{
name: 'name'
}, {
name: 'type_and_cargo'
}
]
});
advSearchStore = Ext.create('Ext.data.Store', {
pageSize: 10,
model: 'AdvSearchPost'
});
Well it is just a typo of your storename.
The error Uncaught TypeError: Cannot read property 'buffered' of undefinedonly indicates that the store could not be bound. It may be a bit misleading.
Try the grid with either
store: advSearchPost
or
store: Ext.StoreMgr.lookup('AdvSearchPost') // if in any form a controller takes care about your store
and it will work.
Edit
I guess you haven't any controller so I recommend you to create your store like this
Ext.create('Ext.data.Store', {
pageSize: 10,
model: 'AdvSearchPost',
storeId: 'AdvSearchPost'
});
That will enable you to receive the store by the StoreManager from everywhere (after it is created). That will also enable the last statement to work without any controller.
Even if you call like this..
store: Ext.StoreMgr.lookup('bla bla bla') won't throw any error in the console.
Replace store parameter with storeId and then assign your actual store to it which will connect to your actual store. storeId:advSearchPost

Ext JS 4: Custom object property value based on condition

I'm trying to create custom property values (based on a condition of a function) for my Ext objects, instead of specifying just a value.
Example 1:
old code (working)
this.buttons = [
{
text: 'Save',
new code (not working)
this.buttons = [
{
text: function() {
return 'Save X';
},
Example 2:
old code (working)
}, {
width: 270,
labelAlign: 'right',
xtype: 'textfield',
name: 'user_id',
fieldLabel: 'User ID',
hidden: true
}]
new code (not working)
}, {
width: 270,
labelAlign: 'right',
xtype: 'textfield',
name: 'user_id',
fieldLabel: 'User ID',
hidden: function() { return true; }
}]
Example 3:
Ignore entire textfield object (lazy instance) completely based on a condition:
}, {
width: 270,
labelAlign: 'right',
xtype: 'textfield',
name: 'employee_number',
fieldLabel: 'Employee Number'
}]
You simply can't do it this way. It is not possible to replace a type with a function. In your case you assign a function reference to a variable which is expected to be boolean, same for the string.
Solution A.
You should consider to write yourself a field factory. Within that factory you can then execute any function before assigning configs. (Sort of same then B but can be used to reduce function calls)
Solution B.
Use a function reference itself. This one should then get executed. (spare the requirement of class extension and is over that reuseable)
// The data store containing the list of states
var states = Ext.create('Ext.data.Store', {
fields: ['abbr', 'name'],
data : [
{"abbr":"AL", "name":"Alabama"},
{"abbr":"AK", "name":"Alaska"},
{"abbr":"AZ", "name":"Arizona"}
//...
]
});
Ext.namespace('my.util.helper');
my.util.helper.decideHide = function() { return true; }
// Create the combo box, attached to the states data store
Ext.create('Ext.container.Container', {
renderTo: Ext.getBody(),
items: [{
xtype: 'combo',
fieldLabel: 'Choose State',
store: states,
queryMode: 'local',
displayField: 'name',
valueField: 'abbr',
test: my.util.helper.decideHide(),
listeners: {
afterrender: function(n) {
alert(n.test);
}
}
}]
});
Solution C.
And the solution I use most in such cases are simplified if else statements
// ... // more code
{
    text: myCondition ? 'Text A' : 'Text B',
// more code
}
// ... // more code
Yeah that is not going to work, some Ext configs take a function that will be evaluated but most of them don't. Instead of creating anonymous functions and not invoking them I would do something like this:
Ext.define('UserPanel', {
extend : 'Ext.panel.Panel',
initComponent : function() {
this.items = [{
xtype : 'button',
text : this._getSaveButtonText()
}, {
width : 270,
labelAlign : 'right',
xtype : 'textfield',
name : 'user_id',
fieldLabel : 'User ID',
hidden : this._isUserIdHidden()
}]
this.callParent();
},
_getSaveButtonText : function() {
return 'Save';
},
_isUserIdHidden : function() {
return true;
}
});

ExtJs 4 Reload Application

In my application all component's titles/texts are localized based on store loaded before Application launch. In application i have button that changes store url and reloads the store to switch language. The problem is that all the classess are already loaded so components are rendered with previous locale. Here is the code of the button:
tbar: [{
xtype: 'button',
id: 'btn-test',
text: 'xxx',
handler: function() {
lang = 'en';
i18n.getBundlestore().load({url:'/GSIP/resources/gsip/i18n/bundle-' + lang + '.properties'});
//bun = Ext.create('I18N.ResourceBundle');
Ext.getCmp('mainview').destroy();
Ext.create('Ext.container.Viewport', {
id: 'mainview',
layout: 'border',
items: [
{
xtype: 'gsip_mainpanel',
region: 'center',
items: [{
xtype: 'gsip_categoriestabpanel'
}]
}
]
The exact same viewport creation is in my Application.js. lang and i18n are global variables. Old viewport is destroyed and new is created but how to force to reload classess. I dont want to use window.location.
Code updated:
handler: function() {
lang = 'en';
Ext.getCmp('mainview').destroy();
i18n.getBundlestore().load({url:'/GSIP/resources/gsip/i18n/bundle-' + lang + '.properties',
callback: function() {
Ext.create('Ext.container.Viewport', {
id: 'mainview',
layout: 'border',
items: [
{
xtype: 'gsip_mainpanel',
region: 'center',
items: [{
xtype: 'gsip_categoriestabpanel'
}]
}
]
});
}
});
}
CategoriesTabPanel:
Ext.define('GSIP.view.CategoriesTabPanel' ,{
extend: 'Ext.tab.Panel',
alias : 'widget.gsip_categoriestabpanel',
layout: 'fit',
items: [{
xtype: 'gsip_planytabpanel',
title: i18n.getMsg('key-1')
},{
xtype: 'gsip_adresytabpanel',
title: i18n.getMsg('key-2')
}],
initComponent: function() {
this.callParent(arguments);
}
});
and ResourceBundle (i18n variable is an instance of this class):
Ext.define('I18N.ResourceModel',{
extend: 'Ext.data.Model',
fields: ['key', 'value']
});
Ext.define('I18N.ResourceStore',{
extend: 'GSIP.core.RegisteredStore',
model: 'I18N.ResourceModel',
autoLoad: true,
proxy: {
type: 'ajax',
url: '/GSIP/resources/gsip/i18n/bundle-' + lang + '.properties',
reader: {
type: 'json',
root: 'pl',
successProperty: 'success'
}
}
});
Ext.define('I18N.ResourceBundle' ,{
config: {
bundlestore: Ext.create('I18N.ResourceStore'),
},
constructor: function(config) {
this.initConfig(config);
return this;
},
getMsg: function(key) {
return this.bundlestore.getAt(this.bundlestore.findExact('key', key)).get('value');
}
},function(){
//callback function, called before store load :(
}
);
Within the definition of widget.gsip_categoriestabpanel you set items as a config. This means it will always reference the same object (and not the updated one). As first step, you should move the items definition to initComponent, there you can also console.log(i18n) to see it's the right one.

Resources