PDA

View Full Version : Grid Rows Disappear After Record Update



heuristicus
5 May 2012, 10:27 PM
Hi all,

I am a newbie of Ext JS and I try to learn the framework by doing some exercises. While doing this, I came across a problem and couldn't figure out how to solve it. My intention was to develop a page with a form which includes a textbox and an html editor, and a grid. One should be able to fill the form fields and, by pressing Save button, insert that record to the database. After that grid should be refreshed. When a row, on the grid, is selected that row's content should appear on the form. After that one can change the content, and by pressing the Save button, update the record in the database or delete selected record by pressing Delete button. Again grid should refresh. I could implement everything except grid refresh of record update. When I select a row, change content, press Save, all record on the grid disappears. With firebug I can see store is reloaded but grid does not show them. Your help will be appreciated.

This is the page code:


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Haberler</title>
<link rel="stylesheet" type="text/css" href="../../extjs/resources/css/ext-all.css" />
<script type="text/javascript" src="../../extjs/ext-all.js"></script>
<script type="text/javascript" src="haber.js"></script>
</head>
<body>
<div id="form_news" style="float:left; margin:5px; width: 99%; height: 48%"></div>
<div id="grid_news" style="float:left; margin:5px; width: 99%; height: 48%"></div>
</body>
</html>
<?php
include("../../kullanici/view/auth.php");
?>


This is Ext JS code:


Ext.require(['Ext.form.*', 'Ext.layout.container.Column', 'Ext.tab.Panel']);
Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('Ext.ux', '../../extjs/examples/ux/');
Ext.require(['Ext.grid.*', 'Ext.data.*', 'Ext.util.*', 'Ext.toolbar.Paging', 'Ext.ux.PreviewPlugin', 'Ext.ModelManager', 'Ext.tip.QuickTipManager']);
Ext.onReady(function(){
Ext.define( 'Haberler', {
extend: 'Ext.data.Model',
fields: ['ID', 'DIL', 'HABER_BASLIK', 'HABER_TEXT', 'TARIH']
});

var store = Ext.create('Ext.data.Store', {
pageSize: 10,
model: 'Haberler',
proxy: {
type: 'ajax',
url: 'haberler_get.php',
reader: {
type: 'json',
root: 'results',
totalProperty: 'total'
}
}
});

store.load(function(records, operation, success) {
if (store.getProxy().getReader().rawData.total == "-1")
Ext.Msg.alert('HATA', "Kullan?c? giri?i yapt???n?zdan emin olunuz!");
});

var form = Ext.create('Ext.form.Panel', {
frame:true,
waitMsgTarget: true,
collapsible: true,
title: 'Haber Yönetim Ekran?',
bodyStyle:'padding:5px 5px 0',
fieldDefaults: {labelAlign: 'top', msgTarget: 'side'},
items: [{
xtype: 'textfield',
name: 'HABER_BASLIK',
fieldLabel: 'Ba?l?k',
anchor: '100%',
allowBlank: false
}, {
xtype: 'htmleditor',
name: 'HABER_TEXT',
fieldLabel: 'Aç?klama',
anchor: '100%',
height: 200
}, {
xtype:'hidden',
name: 'ID',
fieldLabel: 'ID'
}, {
xtype:'hidden',
name: 'DIL',
fieldLabel: 'DIL'
}, {
xtype: 'hidden',
name: 'TARIH',
fieldLabel: 'TARIH'
}],
buttons:[{
text: 'Save',
formBind: true, /*only enabled once the form is valid*/
disabled: true,
handler: function() {
this.up('form').getForm().submit({
url: 'haberler_save.php?oper=UPDATE',
submitEmptyText: false,
waitMsg: 'Kaydediliyor...',
success: function(form, action) {
store.load();
form.reset();
},
failure: function(form, action) {
switch (action.failureType) {
case Ext.form.action.Action.CLIENT_INVALID:
Ext.Msg.alert('HATA', 'Form fields may not be submitted with invalid values');
break;
case Ext.form.action.Action.CONNECT_FAILURE:
Ext.Msg.alert('HATA', 'Ajax communication failed');
break;
case Ext.form.action.Action.SERVER_INVALID:
Ext.Msg.alert('HATA', action.result.msg);
}
}
});
}
}, {
text: 'Clear',
handler: function() {this.up('form').getForm().reset();}
}, {
text: 'Delete',
formBind: true, /*only enabled once the form is valid*/
disabled: true,
handler: function() {
this.up('form').getForm().submit({
url: 'haberler_save.php?oper=DELETE',
submitEmptyText: false,
waitMsg: 'Siliniyor...',
success: function(form, action) {
form.reset();
store.remove(Ext.getCmp('grid').getSelectionModel().getSelection());
},
failure: function(form, action) {
switch (action.failureType) {
case Ext.form.action.Action.CLIENT_INVALID:
Ext.Msg.alert('HATA', 'Form fields may not be submitted with invalid values');
break;
case Ext.form.action.Action.CONNECT_FAILURE:
Ext.Msg.alert('HATA', 'Ajax communication failed');
break;
case Ext.form.action.Action.SERVER_INVALID:
Ext.Msg.alert('HATA', action.result.msg);
}
}
});
}
}]
});

form.render('form_news');



var grid = Ext.create('Ext.grid.Panel', {
id: 'grid',
collapsible: true,
title: 'Haberler',
renderTo: 'grid_news',
store: store,
multiSelect: false,
viewConfig: {id: 'ID', trackOver: false, stripeRows: true},
columns: [
{text: 'No', flex: 50, dataIndex: 'ID'},
{text: 'Dil', flex: 50, dataIndex: 'DIL'},
{text: 'Haber Ba?l?k', flex: 50, dataIndex: 'HABER_BASLIK'},
// {text: 'Haber Metni', dataIndex: 'HABER_TEXT', flex: 50},
{text: 'Tarih', dataIndex: 'TARIH', flex: 50}
],
/* paging bar on the bottom*/
bbar: Ext.create('Ext.PagingToolbar', {
store: store,
displayInfo: true,
displayMsg: 'Haberler {0} - {1} of {2}',
emptyMsg: "Haber bulunamad?!"
})
});

/*little bit of feedback*/
grid.on('selectionchange', function(view, nodes) {
var l = nodes.length;
var s = l != 1 ? 's' : '';
grid.setTitle('<i>('+l+' haber seçili)</i>');
var gridrecord = grid.getSelectionModel().getSelection();
var formFields = form.getForm();
formFields.setValues({
ID: gridrecord[0].data.ID,
DIL: gridrecord[0].data.DIL,
HABER_BASLIK: gridrecord[0].data.HABER_BASLIK,
HABER_TEXT: gridrecord[0].data.HABER_TEXT
})
});
});


This is the code that fetches records from the database:


<?php
include("../../misc/common.php");
include("../../misc/functions.php");


if (isLoggedIn())
{
$con = mysql_connect($common_host, $common_user_name, $common_user_pass)or die (mysql_error ());
$db = mysql_select_db($common_database_name, $con) or die (mysql_error ());
mysql_query("SET NAMES UTF8");

$Dil='tr';
$num_result = mysql_query ("SELECT H.ID, H.DIL, H.HABER_BASLIK, H.HABER_TEXT, H.TARIH
FROM haberler H
where H.DIL='$Dil'") or die (mysql_error());

$start = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
$limit = isset($_REQUEST['limit']) ? $_REQUEST['limit'] : 10;

/* get total data*/
$totaldata = mysql_num_rows($num_result);


$result=mysql_query ("SELECT H.ID, H.DIL, H.HABER_BASLIK, H.HABER_TEXT, H.TARIH
FROM haberler H
where H.DIL='$Dil'
ORDER BY H.ID LIMIT ".$start.", ".$limit ."") or die (mysql_error ());

$data = array();

while ($row = mysql_fetch_object($result))
{
$row->HABER_BASLIK = html_entity_decode($row->HABER_BASLIK, ENT_QUOTES, "UTF-8");
$row->HABER_TEXT = html_entity_decode($row->HABER_TEXT, ENT_QUOTES, "UTF-8");
$data [] = $row;
}
}
else
{
$totaldata = -1;
}

echo '({"total":"'.$totaldata.'","results":'.json_encode($data).'})';
?>


This is the code that makes insert, update, delete:


<?php
include("../../misc/common.php");
include("../../misc/functions.php");
include("../../misc/sequence.php");

$msg = "";

if (isLoggedIn())
{
$con = mysql_connect($common_host, $common_user_name, $common_user_pass) or die (mysql_error());
mysql_select_db($common_database_name, $con);
mysql_query("SET NAMES UTF8");


$ID = $_POST['ID'];
$DIL = 'tr';
$HABER_BASLIK = iyselit_encode($_POST['HABER_BASLIK'], "VARCHAR");
$HABER_TEXT = iyselit_encode($_POST['HABER_TEXT'], "TEXT");

$OPERATION = $_REQUEST['oper'];/*UPDATE,DELETE,INSERT*/

if (!isset($ID) || $ID == 0)
{
$OPERATION = "INSERT";
}

if ($OPERATION == "DELETE")
{
$q = "DELETE FROM haberler WHERE ID='$ID' and dil='$DIL'";
$r = mysql_query($q, $con) or $msg = "CAN NOT DELETE! ".mysql_error();
}
else if ($OPERATION == "UPDATE")
{
$q = "UPDATE haberler A SET
haber_baslik = '$HABER_BASLIK',
haber_text = '$HABER_TEXT'
WHERE A.id='$ID' and A.dil='$DIL'";
$r = mysql_query($q, $con) or $msg = "CAN NOT UPDATE! ".mysql_error();
}
else if ($OPERATION == "INSERT")
{
$ID = get_sequence_id($con, 'HABERLER');

$q = "insert into haberler (id, dil, haber_baslik, haber_text, tarih)
VALUES ('$ID', '$DIL', '$HABER_BASLIK', '$HABER_TEXT', NOW())";

$r = mysql_query($q, $con) or $msg = "CAN NOT INSERT! ".mysql_error();
}

mysql_close($con);

if ($msg == "")
$success = "true";
else
$success = "false";
}
else
{
$success = "false";
$msg = "Kullan?c? giri?i yapmal?s?n?z!";
}

$response = "{
success: ".$success.",
msg: \"".$msg."\"
}";


echo $response;
?>

15 May 2012, 4:57 AM
This problem tells me that the update event is failing and the data that you're trying to load is not coming back in a valid format.

Your approach is very wrong, however. You should be invoking an ajax request to save the data, creating a record, and inserting it during an add operation. not reloading the entire grid.

Same goes for delete. invoke ajax request for delete, upon successful return, simply remove the model from the store. No reload of the store is required.

Lastly, for editing, this pattern is best. Invoke ajax request for the edit, upon successful return, simply APPLY the changes to the model instance. No reload of the store is required.