PDA

View Full Version : Database-query in Formpanel



Tascha
12 Aug 2009, 12:14 AM
Hello!

I want to use a formpanel and show two entries from my database to set a dynamic description for the grid beneath the formpanel.
But I don't know, how to handle that.




simple = new Ext.FormPanel({ ///Allgemeine Daten

proxy: new Ext.data.HttpProxy({
url:'database.php',
method: 'GET'
}),
baseParams:{task: "GETIP_HOST"},
autoLoad: true,
reader : new Ext.data.JsonReader({
root:'results',
totalProperty:'total',
frame: true,
title:'XML Form',
labelAlign: 'right',
labelWidth: 85,
width:340,
waitMsgTarget: true,
id: 'id'
}, [
{name: 'hostname', type:'string', mapping:'hostname'},
{name: 'ipv4_addr', type:'string', mapping:'ipv4_addr'},
{name: 'ipv6', type:'string', mapping:'ipv6'}

]),


items: [
new Ext.form.FieldSet({
title: 'Contact Information',
autoHeight: true,
defaultType: 'label',
items: [{
fieldLabel: 'Hostname',
name: 'hostname',
width:190
}, {
fieldLabel: 'IPv4',
name: 'ipv4_addr',
width:190
}, {
fieldLabel: 'IPv6',
name: 'ipv6',
width:190

}]
})
]

});

In this way it doesn't work, needless to say...
But I want to show, how I imagine that.
Hope, you understand what I mean, otherwise please write back.

Some ideas?

Greetings

Tascha :)

Condor
12 Aug 2009, 12:24 AM
A FormPanel (actually, the inner BasicForm) doesn't have a 'proxy' config option and 'autoLoad' doesn't do what you want.

Remove the proxy and autoLoad config options and specify the url directly as a form config option.

Now you can load the form with:

simple.getForm().load({..});

Tascha
12 Aug 2009, 1:09 AM
Thanks for your help.

with:


simple.getForm().load({url:'database.php' });

It looks better then before. So I see a frame and the headers (Hostname etc). But the query doesn't work. I have to send a task to my database.php to start the query



baseParams:{task: "GETIP_HOST"}, //doesn't work in formpanel?
hmmm... I have no idea

Firebug says: this.form.el is undefined

Condor
12 Aug 2009, 1:40 AM
BasicForm does support baseParams, so I don't understand why they aren't sent.

Could you try:

simple.getForm().load({
url:'database.php',
params:{task: "GETIP_HOST"}
});

Tascha
12 Aug 2009, 1:55 AM
Doesn't work, same errormessage from Firebug.

Before I load the Formpanel, I load the Grid. Could it be, that that the problem exists, because I use the JSON-reader or the database.php before in the grid?

I show you the 'complete' code:




aktuell_DataStore = new Ext.data.Store({

id: 'aktuell_DataStore',
proxy: new Ext.data.HttpProxy({
url:'database.php',
method: 'GET'
}),
baseParams:{task: "GETALL"},
autoLoad: true,
reader: new Ext.data.JsonReader({
root:'results',
totalProperty:'total',
id: 'id'
},[

{name: 'ondemand', type:'string', mapping:'ondemand'},
{name: 'command', type:'string', mapping:'command'},
{name: 'datetime', type:'string', mapping:'datetime'},
{name: 'profile', type:'string', mapping:'profile'},
{name: 'result', type:'string', mapping:'result'}

]),
sortInfo: {field: 'hostname', direction: "ASC"}



});



aktuell_ColumnModel = new Ext.grid.ColumnModel([

expander,//this is important,
{

header: 'Command',
dataIndex: 'command',
width: 170


},{
header: 'OnDemand',
dataIndex: 'ondemand',
width: 70

},{
header: 'Datetime',
dataIndex: 'datetime',
width: 150

},{
header: 'Profile',
dataIndex: 'profile',
width: 100





}]
);
aktuell_ColumnModel.defaultSortable= true;





aktuell_ListingEditorGrid = new Ext.grid.GridPanel({
id: 'aktuell_ListingEditorGrid',
store: aktuell_DataStore,
cm: aktuell_ColumnModel,


plugins: expander,
frame:true,
collapsible: true,
animCollapse: true,
autoWidth: true,
height:642,
columnLines: true,
defaults: {width: 230},
viewConfig: {forceFit: true}

});



simple = new Ext.FormPanel({ ///Allgemeine Daten




reader : new Ext.data.JsonReader({
root:'results',
totalProperty:'total',
frame: true,
title:'XML Form',
labelAlign: 'right',
labelWidth: 85,
width:340,
waitMsgTarget: true,
id: 'id'
}, [
{name: 'hostname', type:'string', mapping:'hostname'},
{name: 'ipv4_addr', type:'string', mapping:'ipv4_addr'},
{name: 'ipv6', type:'string', mapping:'ipv6'}

]),


items: [
new Ext.form.FieldSet({
title: 'Contact Information',
autoHeight: true,

defaultType: 'label',
items: [{
fieldLabel: 'Hostname',
name: 'hostname',
width:190
}, {
fieldLabel: 'IPv4',
name: 'ipv4_addr',
width:190
}, {
fieldLabel: 'IPv6',
name: 'ipv6',
width:190

}]
})
]

});


simple.getForm().load({
url:'database.php',
params:{task: "GETIP_HOST"}
});
In the next sequence the 'simple' and 'aktuell_ListingEditorGrid' were loaded in a tabpanel:





var TabPanel = new Ext.TabPanel({
region: 'center',
activeTab:0,
layoutOnTabChange: true,
items:[{

title: 'Startseite',
closable:false,
autoScroll:true


},{

title: 'Geräte',
layout:'fit',
closable:true,
defaults: {
// implicitly create Container by specifying xtype
xtype: 'container',
autoEl: 'div', // This is the default.
layout: 'form',
columnWidth: 0.5,
style: {
padding: '3px 2px'
}
},
items: [{

items: [simple, aktuell_ListingEditorGrid] ///HERE

}]


/////////////////////////....etc (I think the rest isn't important)
Otherwise works good apart from 'simple'

Condor
12 Aug 2009, 2:06 AM
1. You are putting some config options of FormPanel inside the JsonReader.
2. You can't load a form before it is rendered.

Tascha
12 Aug 2009, 3:10 AM
Stupid failure with the config options, thanks..

But I have problems with render the formpanel. Perhaps you could help me again.

I tested it with : simple.render();

That didn't work. I've searched for some tutorials or other advices to render that, but I'm only find render().

Or perhaps is it on the wrong place?



.......//End Of Formpanel/////////////////

simple.render(document.body);

simple.getForm().load({
url:'database.php',
params:{task: "GETIP_HOST"}
});

Condor
12 Aug 2009, 3:30 AM
You should not render the form yourself. It will already be rendered by the tabpanel container.

Unfortunately, it's on a hidden tab, so it will only be rendered when the tab is shown.

So you either have to load the form in the activate event of the tab item or set deferredRender:false in the tabpanel config.

Tascha
12 Aug 2009, 3:55 AM
Now it works with:




simple.getForm().load({
url:'database.php',
params:{task: "GETIP_HOST"},
method: 'GET' //<---------------------
});

Firebug says:



({"total":"1","results":[{"0":"ABCDEFGH",
"hostname":"ABCDEFGH",
"1":"12.345.67.89",
"ipv4_addr":"12.345.67.89"}]})
That's very good :)

But:


Hostname: /nothing


IPv4: /nothing


IPv6: /nothing

The data from the query doesn't display in formpanel.


I set the deferredRender:false in the config options(in tabpanel config options I tryed too, nothing happens):




var TabPanel = new Ext.TabPanel({
region: 'center',

activeTab:0,
layoutOnTabChange: true,
items:[{

title: 'Startseite',
closable:false,
autoScroll:true


},{

title: 'Ger&auml;te',
layout:'fit',
deferredRender:false,
closable:true,
defaults: {
// implicitly create Container by specifying xtype
xtype: 'container',
autoEl: 'div', // This is the default.
layout: 'form',
columnWidth: 0.5,
style: {
padding: '3px 2px'
}
},
items: [{

items: [simple, aktuell_ListingEditorGrid]

}]

...........

Some idea?

jarlau
12 Aug 2009, 4:03 AM
from the Doc of Ext.form.Action.Load



a success response packet may look like this:


{
success: true,
data: {
clientName: "Fred. Olsen Lines",
portOfLoading: "FXT",
portOfDischarge: "OSL"
}
}

Tascha
12 Aug 2009, 4:06 AM
Hello,

I only want to display some data from my database in the formpanel, I thought I don't need that*?*

jarlau
12 Aug 2009, 4:11 AM
your json return is good for store load, but for the form load you need that format of json.

Tascha
12 Aug 2009, 4:27 AM
In this way, it couldn't work, or?




simple.form.load({
url:'database.php',
deferredRender:false,
params:{task: "GETIP_HOST"},
method: 'GET',
success:true,
success:function(form, action) {

Ext.MessageBox.alert('Message', 'Loaded ok');

},

failure:function(form, action) {

Ext.MessageBox.alert('Message', 'Load failed');

},

data: {
hostname: "<?php echo $data[0]['hostname']; ?>",
ipv4_addr: "<?php echo $data[0]['ipv4_addr']; ?>",
ipv6: "<?php echo $data[0]['ipv6']; ?>"
}

});



Sorry, but I don't get it. I don't know, how or where I have to put it in my code.

Condor
12 Aug 2009, 4:34 AM
What does database.php?task=GETIP_HOST return?

And what does your form reader look like now (or did you remove the reader, because it isn't really required if your data is formatted correctly)?

jarlau
12 Aug 2009, 4:36 AM
do it in server side, your json return should look like this:


{
success:true,
data: {
"0":"ABCDEFGH",
"hostname":"ABCDEFGH",
"1":"12.345.67.89",
"ipv4_addr":"12.345.67.89"
}
}

Condor
12 Aug 2009, 4:38 AM
It probably should return:

{
success:true,
data: {
"hostname":"ABCDEFGH",
"ipv4_addr":"12.345.67.89",
"ipv6":"..."
}
}
and you should remove the reader from the form, because this is the default format.

Tascha
12 Aug 2009, 5:02 AM
I'm confused now...
database.php?task=GETIP_HOST returns:



({"total":"1","results":[{"0":"ABCDEFGH",
"hostname":"ABCDEFGH",
"1":"12.345.67.89",
"ipv4_addr":"12.345.67.89"}]})



And my reader is the same like before:




reader : new Ext.data.JsonReader({
root:'results',
totalProperty:'total',

id: 'id'
}, [
{name: 'hostname', type:'string', mapping:'hostname'},
{name: 'ipv4_addr', type:'string', mapping:'ipv4_addr'},
{name: 'ipv6', type:'string', mapping:'ipv6'}

]),

When I delete the reader, it looks like before.

Condor
12 Aug 2009, 5:45 AM
For form load you also need a success property, e.g.

{
"success":true,
"total":"1",
"results":[{
"hostname":"ABCDEFGH",
"ipv4_addr":"12.345.67.89"
}]
}
and reader:

reader : new Ext.data.JsonReader({
root:'results',
totalProperty:'total',
successProperty:'success',
}, [
{name: 'hostname', type:'string', mapping:'hostname'},
{name: 'ipv4_addr', type:'string', mapping:'ipv4_addr'},
{name: 'ipv6', type:'string', mapping:'ipv6'}
]),

trasherdk
12 Aug 2009, 3:57 PM
Thanks Condor.

I've been struggling with this problem for the last couple of days, searching the
samples, this forum and a lot of googeling to no prevail.

It's probably in there, in the samples, somewhere, but i just couldn't find it I-|

Mogens

Tascha
12 Aug 2009, 10:28 PM
At first:

Thanks for your encouragement!


I've changed the things you say:




simple = new Ext.FormPanel({


frame: true,
title:'XML Form',
labelAlign: 'right',

labelWidth: 85,
width:340,
waitMsgTarget: true,
reader : new Ext.data.JsonReader({
root:'results',
totalProperty:'total',
successProperty:'success', //HERE
}, [
{name: 'hostname', type:'string', mapping:'hostname'},
{name: 'ipv4_addr', type:'string', mapping:'ipv4_addr'},
{name: 'ipv6', type:'string', mapping:'ipv6'}
]),



items: [
new Ext.form.FieldSet({
title: 'Contact Information',
autoHeight: true,

defaultType: 'label',
items: [{
fieldLabel: 'Hostname',
name: 'hostname',
width:190

}, {
fieldLabel: 'IPv4',
name: 'ipv4_addr',
width:190
}, {
fieldLabel: 'IPv6',
name: 'ipv6',
width:190

}]
})
]

});



simple.getForm().load({
url:'database.php',

params:{task: "GETIP_HOST"},
method: 'GET',

failure:function(form, action) {

Ext.MessageBox.alert('Message', 'Load failed');

},

success:true, //AND HERE, but I think it's needless
data: {

Hostname: "<?php echo $data[0]['hostname']; ?>",
ipv4_addr: "<?php echo $data[0]['ipv4_addr']; ?>",
ipv6: "<?php echo $data[0]['ipv6']; ?>"
}

});

But it doesn't work.

Do I have to change something in the database.php?




$query = "select hostname, inet_ntoa( ipv4 ) as ipv4_addr from TEST_$date where inet_ntoa(ipv4) ='$ip_num'";
$result = mysql_query($query);
$nbrows = mysql_num_rows($result);



if($nbrows>0){
while($rec = mysql_fetch_array($result)){

$arr[] = $rec;

}
$jsonresult = JEncode($arr);
$jsonresult= str_replace('\'', '', $jsonresult);

echo '({"total":"'.$nbrows.'","results":'.$jsonresult.'})'; //HERE??
/* f.e.: echo '({"success":true,"total":"'.$nbrows.'","results":'.$jsonresult.'})'; I tryed, but nothing happened...*/
}
else
{

echo '({"total":"0", "results":"})';

}

greetings

Tascha

jarlau
12 Aug 2009, 11:51 PM
Your new JSON return(with success property) should be fine.

But your form.load() dont need success & data properties, instead, you can try add success function to see if the response ok.



simple.getForm().load({
url:'database.php',
params:{task: "GETIP_HOST"},
method: 'GET',
failure:function(form, action) {
Ext.MessageBox.alert('Message', 'Load failed');
},
success:function(form, action) {
Ext.MessageBox.alert('Message', 'Load succeed.');
}
});


Beside, as Condor said, the JsonReader is optional for form since its default format. But once you decide not to use the JsonReader, your JSON returns should look something like below:


{
success:true,
data: {
"hostname":"ABCDEFGH",
"ipv4_addr":"12.345.67.89",
"ipv6":"..."
}
}

Tascha
13 Aug 2009, 12:19 AM
Now, I get 'Load succeed'- message.

And the response from database.php in firebug is:




({"success":"true","total":"1",
"results":[{"0":"ABCDEF",
"hostname":"ABCDEF","1":"12.345.67.89",
"ipv4_addr":"12.345.67.89"}]})

By the way, so far, I learned much :)

Do I have to delete the JsonReader to get the other form or rather, is this form...



{
success:true,
data: {
"hostname":"ABCDEFGH",
"ipv4_addr":"12.345.67.89",
"ipv6":"..."
}
}
...required to display the results in the Fieldsets? Until now I still don't see the results in the fieldsets.

And when I don't use the JsonReader, what do I have to use instead of..?

jarlau
13 Aug 2009, 12:31 AM
don't quote the "true", success property requires Boolean.

it's up to you to use reader or not. but in your case, I don't see any reason why you need the reader. just remove the reader config, Extjs will handle the mapping for you. but remember to change the JSON return format.

Tascha
13 Aug 2009, 12:45 AM
Okayyy, last question ;)




if($nbrows>0){
while($rec = mysql_fetch_array($result)){

$arr[] = $rec;

}
$jsonresult = JEncode($arr);
$jsonresult= str_replace('\'', '', $jsonresult); //macht Anführungszeichen weg

echo '({"success":true,"total":"'.$nbrows.'","results":'.$jsonresult.'})';
}
else
{

echo '({"total":"0", "results":"})';

}

Do I have to delete "results" and "total", when I delete the JsonReader?




reader : new Ext.data.JsonReader({ /*And the last question in a question, you mean delete the whole Reader config, or configs in the reader? If I delete the whole, I get the message: 'Load failed' */
root:'results',
totalProperty:'total',
successProperty:'success',

}, [
{name: 'hostname', type:'string', mapping:'hostname'},
{name: 'ipv4_addr', type:'string', mapping:'ipv4_addr'},
{name: 'ipv6', type:'string', mapping:'ipv6'}
]),

In all I'm understanding, but I don't know how using this 'understanding'.

Thanks a lot!!

jarlau
13 Aug 2009, 12:55 AM
remove the whole Reader, totals & results!!

make the JSON return look like this:


{
success:true,
data: {
"hostname":"ABCDEFGH",
"ipv4_addr":"12.345.67.89",
"ipv6":"..."
}
}


From the Doc of Ext.form.Action.Load


Response Packet Criteria

A response packet must contain:

* success property : Boolean
* data property : Object
The data property contains the values of Fields to load. The individual value object for each Field is passed to the Field's setValue method.

Tascha
13 Aug 2009, 1:27 AM
How can I delete this stupids ' [ ] ' ?




("success":true,[{"0":"AAKMST0ACRR5D01",
"hostname":"AAKMST0ACRR5D01",
"1":"10.205.48.10",
"ipv4_addr":"10.205.48.10"}])



Sorry,it's probably simple, but I don't get this little thing.

jarlau
13 Aug 2009, 1:37 AM
I don't know php...
But for me form data always return 1 record only, so you probably don't need to while() loop your resultset & simply set your $rec to the json?

or maybe other php developer can help with this.

Tascha
13 Aug 2009, 3:34 AM
So, I search some hours in the internet, but I find nothing usefull.I think, I will make a new thread with: how to change $jsonresult format??

Thanks for your help :)

I've learned much so far !!


greetings

Tascha

trasherdk
13 Aug 2009, 10:28 AM
Hi Tascha

My mysql_fetch look like this:

(The number of records is controlled by your query)



<?php
/** mysql query stuff **/

$cnt = mysql_num_rows($res);

$response = "[";

while ($row = mysql_fetch_assoc($res))
{
if ($response != "[") // if more than one row of data
$response .= ",";

$response .= json_encode($row);
}
$response .= "]";

echo "{success: 'true', total: $cnt, results: $response

return;
?>


This will result in a json response a jsonreader can "consume".



{success: 'true', total:1, results:[{
"id":"1"
,"manager":"0"
,"fname":"Mogens"
,"lname":"Melander"
,"init":"MBM"
,"location":"Trader Internet Thailand"
,"phone":"+11 22 33 44 55 66"
,"mobile":""
,"email":"[email protected]"
,"login":"xxxxxxxxx"
,"passwd":"yyyyyyyyyyyyyyyyyyyyy"
,"admin":"1"
,"readwrite":"1"
}]
}


And here's the jsonreader that recieves above response:
(Not that returned data and reader don't match 100%, and that's not a problem)



// form stuff
,reader : new Ext.data.JsonReader({
root:'results',
,totalProperty:'total'
,successProperty:'success'
}, [{
name: 'id', type:'int', mapping: 'id'}
,{name: 'manager', type:'int', mapping: 'manager'}
,{name: 'fname', type:'string', mapping: 'fname'}
,{name: 'lname', type:'string', mapping: 'lname'}
,{name: 'init', type:'string', mapping: 'init'}
,{name: 'location', type:'string', mapping: 'location'}
,{name: 'phone', type:'string', mapping: 'phone'}
,{name: 'mobile', type:'string', mapping: 'mobile'}
,{name: 'email', type:'string', mapping: 'email'}
,{name: 'time', type:'string', mapping: 'time'}
])
, // more form stuff


Hope that help.

Mogens

trasherdk
13 Aug 2009, 10:34 AM
Change:

echo "{success: 'true', total: $cnt, results: $response

to

echo "{success: 'true', total: $cnt, results: $response}";

Sorry.

Mogens

Tascha
13 Aug 2009, 10:48 PM
Hello trasherd,

I did it in your way:




$result = mysql_query($query);
$nbrows = mysql_num_rows($result);
}

$response = "[";

while ($rec = mysql_fetch_assoc($result))
{
$arr = $rec;
if ($response != "[") // if more than one row of data
$response .= ",";

$response .= JEncode($arr);

}
$response .= "]";

echo "{success: 'true', total: $nbrows, results: $response}";

return;

And the response in firebug is:




{success: 'true', total: 1, results: [{
"hostname":"ABCDEFGHIJ"
,"ipv4_addr":"12.345.67.89"
}]
}It's the same like yours.

And the JsonReader is the same too, but the fieldsets in my formpanel are still empty.:s

trasherdk
14 Aug 2009, 7:06 AM
Let me get back to you after the week-end. I'm at a party, for the next 2 days B)

Mogens

trasherdk
17 Aug 2009, 9:55 PM
Tasca,

Post your complete form panel, and i will take a look.

Mogens

rex0098
15 Dec 2009, 7:17 PM
tascha,

i also tried the code of trasherdk but i always get a load failed message...can you help me figure out why??
here is my code:


Ext.onReady(function(){

Ext.QuickTips.init();

var fieldset1 =
{
xtype : 'fieldset', // 1
flex : 1,
border : false, // 2
labelWidth : 60,
defaultType : 'field',
defaults : {anchor : '-10',allowBlank : false},
items :
[{
fieldLabel : 'First',
name : 'first_name'
},
{
fieldLabel : 'Last',
name : 'last_name'
}]
}


var fieldsetContainer =
{
xtype : 'container',
layout : 'hbox',
height : 120,
layoutConfig : {
align : 'stretch'
},
items : [fieldset1]
}

var myFormPanel = new Ext.form.FormPanel({
renderTo : Ext.getBody(),
width : 200,
title : 'Our complex form',
height : 100,
frame : true,
id : 'myFormPanel',
layout : 'vbox',
layoutConfig : {
align : 'stretch'
},
items : [fieldsetContainer]
});

var form = Ext.getCmp('myFormPanel');
form.getForm().load({
url : 'getdata.php',
root:'data',
failure:function(form, action) {
Ext.MessageBox.alert('Message', 'Load failed');
},
success:function(form, action) {
Ext.MessageBox.alert('Message', 'Load succeed.');
}
});
});


and i tried using these codes for my getdata.php.....
and here is the first:


$dbhost = "localhost"; // this will ususally be 'localhost', but can sometimes differ
$dbname = "test2"; // the name of the database that you are going to use for this project
$dbuser = "root"; // the username that you created, or were given, to access your database
$dbpass = "root"; // the password that you created, or were given, to access your database

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());


$result=mysql_query ("SELECT first_name,last_name FROM names WHERE name_id = '2'") or die (mysql_error ());
$get_result = mysql_fetch_array($result);
$first_name = $get_result['first_name'];
$last = $get_result['last_name'];

echo '{ sucess: true,data : {first_name : "'.$first_name.'",last_name :"'.$last.'"}}';




and this isa the second:


$dbhost = "localhost"; // this will ususally be 'localhost', but can sometimes differ
$dbname = "test2"; // the name of the database that you are going to use for this project
$dbuser = "root"; // the username that you created, or were given, to access your database
$dbpass = "root"; // the password that you created, or were given, to access your database

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());

$result=mysql_query ("SELECT first_name,last_name FROM names WHERE name_id = '1'") or die (mysql_error ());

$row = mysql_fetch_object($result);

echo '{sucess:true, data:'.json_encode($row).'}';



but neither of them works..

i get the right response from fire bug which is like this:

{ sucess: true,data : {first_name : "raymund",last_name :"olsen"}}


but the data doesn't appear on my textfields.....

can ypu help me tascha