Extjs 4.2 autosync dynamic grid store - javascript

I have a grid with dynamic columns:
MODEL
Ext.define('App.mdlCriteriosConcurso', {
extend: 'Ext.data.Model',
fields: [
]
});
STORE
Ext.define('App.strCriteriosConcurso', {
extend: 'Ext.data.Store',
model: 'App.mdlCriteriosConcurso',
autoLoad: false,
proxy: {
type: 'ajax',
api: {
read: 'some url',
update: 'some url',
},
reader: {
type: 'json',
root: 'data',
totalProperty: 'total'
},
writer: {
root: 'records',
encode: true,
writeAllFields: true
}
}
});
GRID
var almacenCriteriosConcurso = Ext.create('App.strCriteriosConcurso');
//Some code ...
{
xtype:'grid',
itemId:'gridCriteriosConcursoV4',
store:almacenCriteriosConcurso,
plugins: [Ext.create('Ext.grid.plugin.CellEditing', {clicksToEdit: 2})],
columns:[]
}
//Some code...
CONTROLLER
Here in the controller I have the next piece of code:
Ext.ComponentQuery.query('viewFichaDetalle #tabpanelsecundario4_1 #gridCriteriosConcursoV4')[0].getStore().addListener('metachange',function(store,meta){
var columnas=0;
var renderer1 = function(v,params,data){
if(v==''){
return '<div style="background-color:#F5FAC3;color:blue;">'+Ext.util.Format.number(0,'0.000,00/i')+'</div>';
}
else{
return '<div style="background-color:#F5FAC3;color:blue;">'+Ext.util.Format.number(v,'0.000,00/i')+'</div>';
}
};
var renderer2 = function(v,params,data){
if(v=='' || v==0){
return '<div style="background-color:#F5FAC3;color:green;">'+Ext.util.Format.number(0,'0.000,00/i')+'</div>';
//return '';
}
else{
return '<div style="background-color:#F5FAC3;color:green;">'+Ext.util.Format.number(v,'0.000,00/i')+'</div>';
}
};
Ext.each(meta.columns,function(col){
if(columnas==2){
meta.columns[columnas].renderer = renderer1;
}
if(columnas>=3){
meta.columns[columnas].renderer = renderer2;
}
columnas++;
},this);
Ext.suspendLayouts();
Ext.ComponentQuery.query('viewFichaDetalle #tabpanelsecundario4_1 #gridCriteriosConcursoV4')[0].reconfigure(store, meta.columns);
Ext.ComponentQuery.query('viewFichaDetalle #tabpanelsecundario4_1 #gridCriteriosConcursoV4')[0].setTitle("<span style='color:red;font-weight:bold;font-size: 12pt'>Criterios del Concurso con ID:</span> "+"<span style='color:black;font-weight:bold;font-size: 12pt'>"+this.IdConcurso+"</span>");
Ext.resumeLayouts(true);
},this);
I create the columns in the php, using the metadata.
With this code I add some renderers to the grid columns. And I see all the data perfect, and can edit the data.
In the php y generate the column and the field like this:
$array_metadata['columns'][]=array("header"=>"<span style='color:blue;'>Resultado</span>","dataIndex"=>"puntos_resultado","width"=>82,"align"=>"right","editor"=>"textfield");
$array_metadata['fields'][]=array("name"=>"puntos_resultado","type"=>"float");
And then pass $array_metadata to 'metaData' response.
But when I try to sync or autosync the store I get this error:
Uncaught TypeError: Cannot read property 'name' of undefined
at constructor.getRecordData (ext-all-dev.js:62247)
at constructor.write (ext-all-dev.js:62192)
at constructor.doRequest (ext-all-dev.js:102306)
at constructor.update (ext-all-dev.js:101753)
at constructor.runOperation (ext-all-dev.js:106842)
at constructor.start (ext-all-dev.js:106769)
at constructor.batch (ext-all-dev.js:62869)
at constructor.sync (ext-all-dev.js:64066)
at constructor.afterEdit (ext-all-dev.js:64162)
at constructor.callStore (ext-all-dev.js:101428)
UPDATE 1
I have fount this thread in Sencha Forums link , and I have tried all posibles solutions and Im getting allways the same error.

The error tells us that you don't fill the model's fields array properly, because that is where name is a required config. In ExtJS 4, you have to add all fields to the model for the sync to work properly.
To be exact, the Model prototype has to be filled with the correct fields before the instances are created.
This means that you will have to override the reader's getResponseData method, because between Ext.decode and readRecords you will have to prepare the model prototype by setting the fields as returned from the server; something like this:
App.mdlCriteriosConcurso.prototype.fields = data.fields;

Related

how to solve Trying to get property 'bids' of non-object error

I want to display data from bid table in a form of datatable. But I get this error
"Trying to get property 'bids' of non-object" if it doesn't have bids.The bids model is connected to auction model and the auction model is connected to media site model. How to make it display blank record if it doesn't have data.
Here is my controller:
<?php
namespace App\Http\Controllers;
use App\Auction;
use App\Bid;
use App\User;
use App\Media;
use App\MediaSite;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class MediaSiteController extends Controller
{
public function show(MediaSite $mediaSite)
{
$auction = $mediaSite->auction;
$bids = $auction->bids;
return view('admin.media-site.show', ['mediaSite' => $mediaSite,'auction' => $auction], compact('auction'));
}
My view:
<body>
<div id="datatable-bid"></div>
</body>
<script>
$(document).ready(function () {
var datatableBid = $('#datatable-bid').mDatatable({
// datasource definition
data: {
type: 'local',
source: {!! json_encode($auction->bids) !!},
pageSize: 10
},
// layout definition
layout: {
theme: 'default', // datatable theme
class: '', // custom wrapper class
scroll: false,
footer: false // display/hide footer
},
// column sorting
sortable: true,
pagination: true,
search: {
input: $('#panel-search')
},
// columns definition
columns: [
{
field: "price",
title: "Price",
}, {
field: "month",
title: "Month",
},{
field: "user_id",
title: "User Id",
}
]
});
</script>
Here is my error:
Trying to get property 'bids' of non-object
place following after $auction = $mediaSite->auction;
if($auction){
$bids = $auction->bids;
}else{
//put following line or whatever you need to do if there is no data comes
$auction = [];
}
In the show() function make these changes
$auction = $mediaSite->auction;
if($auction) {
$bids = $auction->bids;
} else {
$bids = [];
}
// now send $bids to view along with $auction
// may be like this
// return view(..., compact($auction, $bids));
Then, in your view make this change
// datasource definition
data: {
type: 'local',
source: {!! json_encode($bids) !!},
pageSize: 10
},
See if this helps.

Saving Only the changed record on a BackGrid grid?

I am in the process of learning Backbone.js and using BackGrid to render data and provide the end user a way to edit records on an Microsoft MVC website. For the purposes of this test grid I am using a Vendor model. The BackGrid makes the data editable by default (which is good for my purpose). I have added the following JavaScript to my view.
var Vendor = Backbone.Model.extend({
initialize: function () {
Backbone.Model.prototype.initialize.apply(this, arguments);
this.on("change", function (model, options) {
if (options && options.save === false) return;
model.url = "/Vendor/BackGridSave";
model.save();
});
}
});
var PageableVendors = Backbone.PageableCollection.extend(
{
model: Vendor,
url: "/Vendor/IndexJson",
state: {
pageSize: 3
},
mode: "client" // page entirely on the client side.
});
var pageableVendors = new PageableVendors();
//{ data: "ID" },
//{ data: "ClientID" },
//{ data: "CarrierID" },
//{ data: "Number" },
//{ data: "Name" },
//{ data: "IsActive" }
var columns = [
{
name: "ID", // The key of the model attribute
label: "ID", // The name to display in the header
editable: false, // By default every cell in a column is editable, but *ID* shouldn't be
// Defines a cell type, and ID is displayed as an integer without the ',' separating 1000s.
cell: Backgrid.IntegerCell.extend({
orderSeparator: ''
})
}, {
name: "ClientID",
label: "ClientID",
cell: "integer" // An integer cell is a number cell that displays humanized integers
}, {
name: "CarrierID",
label: "CarrierID",
cell: "number" // A cell type for floating point value, defaults to have a precision 2 decimal numbers
}, {
name: "Number",
label: "Number",
cell: "string"
}, {
name: "Name",
label: "Name",
cell: "string"
},
{
name: "IsActive",
label: "IsActive",
cell: "boolean"
}
];
// initialize a new grid instance.
var pageableGrid = new Backgrid.Grid({
columns: [
{
name:"",
cell: "select-row",
headercell: "select-all"
}].concat(columns),
collection: pageableVendors
});
// render the grid.
var $p = $("#vendor-grid").append(pageableGrid.render().el);
// Initialize the paginator
var paginator = new Backgrid.Extension.Paginator({
collection: pageableVendors
});
// Render the paginator
$p.after(paginator.render().el);
// Initialize a client-side filter to filter on the client
// mode pageable collection's cache.
var filter = new Backgrid.Extension.ClientSideFilter({
collection: pageableVendors,
fields: ['Name']
});
// REnder the filter.
$p.before(filter.render().el);
//Add some space to the filter and move it to teh right.
$(filter.el).css({ float: "right", margin: "20px" });
// Fetch some data
pageableVendors.fetch({ reset: true });
#{
ViewBag.Title = "BackGridIndex";
}
<h2>BackGridIndex</h2>
<div id="vendor-grid"></div>
#section styles {
#Styles.Render("~/Scripts/backgrid.css")
#Styles.Render("~/Scripts/backgrid-select-all.min.css")
#Styles.Render("~/Scripts/backgrid-filter.min.css")
#Styles.Render("~/Scripts/backgrid-paginator.min.css")
}
#section scripts {
#Scripts.Render("~/Scripts/underscore.min.js")
#Scripts.Render("~/Scripts/backbone.min.js")
#Scripts.Render("~/Scripts/backgrid.js")
#Scripts.Render("~/Scripts/backgrid-select-all.min.js")
#Scripts.Render("~/Scripts/backbone.paginator.min.js")
#Scripts.Render("~/Scripts/backgrid-paginator.min.js")
#Scripts.Render("~/Scripts/backgrid-filter.min.js")
#Scripts.Render("~/Scripts/Robbys/BackGridIndex.js")
}
When the user edits a row, it successfully fires the hits the model.Save() method and passes the model to the save Action, in this case BackGridSave and it successfully saves the record that changed, but seems to save all of the vendors in model when only one of the vendors changed. Is there a way from the JavaScript/Backbone.js/BackGrid to only pass one Vendor - the vendor that changed?
Update: I realized that it is not sending every vendor, but it is sending the same vendor multiple times as though the change event was firing multiple times.
I guess I answered my own question. Well, at least I am getting the desired result. I just added a call to off after the first on. Seems like this would not be necessary though.
var Vendor = Backbone.Model.extend({
initialize: function () {
Backbone.Model.prototype.initialize.apply(this, arguments);
this.on("change", function (model, options) {
if (options && options.save === false) return;
model.url = "/Robbys/BackGridSave";
model.save();
model.off("change", null, this); // prevent the change event from being triggered many times.
});
}
});

Does ExtJS's BufferedStore work with an OData REST API

I'm working on an application which is supported by an OData REST API. The API works fine in tools like Postman but when we try and use it with our Web App and pull the returned data (which is Json) into a Grid Panel there is an issue.
My company wants to be able to support large data sets, so we choose Ext JS based on it's BufferedStore Grid.
So the problem is we can't get it to work. The way the API is set up is based on the current OData 4 Spec. So it uses $skip and $top exactly in the same way you would use the $startParam and $limitParam within the Proxy of my Ext Store.
So for instance when I want to fetch data from my API the URL would look something like this http://127.0.0.1/odata/BEER/?$skip=0&$top=100 to fetch the first 100 rows of data,
And http://127.0.0.1/odata/BEER/?$skip=1&$top=100 to fetch the for the next 100 rows. The data is in Json and returns back with now issues outside of the BufferedStore Grid.
The Json looks like so
{"#odata.context":"http://127.0.0.1:8080/odata/$metadata#BEER_SAMPLE_LOT","value":[{"Id":17452707,"Name":"BS860-2","Barcode":"BS860-2","Sequence":2578,"Created":null,"Modified":null,"Active":true,"LikedBy":0,"FollowedBy":0,"CI_LOT_NUM":2,"CI_INTENDED_USAGE":"Turbidity Testing","CI_TRIGGER_RUNS":0},{"Id":17452798,"Name":"BS986-2","Barcode":"BS986-2","Sequence":2596,"Created":null,"Modified":null,"Active":true,"LikedBy":0,"FollowedBy":0,"CI_LOT_NUM":2,"CI_INTENDED_USAGE":"Turbidity Testing","CI_TRIGGER_RUNS":0}]}
The problem simple is that when the page loads the Grid will load the first 100 rows, but then as you scroll down the it doesn't prefetch (as the documentation and demos promise it should). It just stops at 100. Nothing we have tried will make it try and fetch the next set. How is this supposed to work?
Here is my code for the store which supports the grid.
var oDataModel = Ext.create('Ext.data.Model',{
fields: []
});
var oDataStore = Ext.create('Ext.data.BufferedStore', {
storeId: 'beerStore',
buffered: true,
autoLoad: true,
model: oDataModel,
leadingBufferZone: 100,
pageSize: 100,
proxy:{
type: 'rest',
url: http:127.0.0.1/odata/BEER
pageParam: false, //to remove param "page"
startParam: '$skip',
limitParam: '$top',
noCache: false, //to remove param "_dc"
method: 'GET',
withCredentials: true,
headers : {
"Content-Type": "text/json",
},
reader:{
type:'json',
rootProperty: 'value',
},
listeners: {
exception: function(proxy, response, operation, eOpts) {
console.log("Exception");
console.log(response);
}
}
}
});
Below is my Grid which is dynamic.
// Create Basic Ext Grid
var oDataGrid = Ext.create('Ext.grid.Panel', {
title: 'oData Entity Table',
store: oDataStore,
height: 400,
loadMask: true,
selModel: {
pruneRemoved: false
},
plugins: [{
ptype: 'bufferedrenderer',
trailingBufferZone: 10,
leadingBufferZone: 10,
scrollToLoadBuffer: 10
}],
renderTo: 'oData-grid'
});
// Add columns to the data grid
_that.buildColumns(_that._properties.property, oDataGrid);
buildColumns: function(__cols,_bGrid){
var _that = this;
// Add the row number first
_bGrid.headerCt.insert(_bGrid.columns.length - 1,{ xtype: 'rownumberer', width: 50 });
var _column = '';
for (var n=0; n<__cols.length; n++) {
//console.log(__cols[n].name);
_column = Ext.create('Ext.grid.column.Column', {
text: __cols[n].name,
width: 100,
dataIndex: __cols[n].name,
filter: true,
renderer: function(__value){
var _val = '';
if(__value instanceof Array){
for(var i = 0; i < __value.length; i++){
_val += __value[i].Barcode + "<br>";
}
} else if (__value instanceof Object){
if(!(__value instanceof Date)){
_val = __value.Barcode + "<br>";
}else{
_val = __value;
}
} else {
_val = __value;
}
return _val;
}
});
_bGrid.headerCt.insert(_bGrid.columns.length - 1, _column); //inserting the dynamic column into grid
}
}

Unable to read Model Records from store by using store.getById()

I am trying to acheive i18n for my sencha Ext JS App.
I used the impl from [https://github.com/elmasse/Ext.i18n.Bundle-touch/blob/master/i18n/Bundle.js][1], but with more simplified version.
Basically, I have a store [webUi.util.rb.ResourceBundle] linked to model [webUi.util.rb.model.KeyValPair], trying to load the json data to the store. Once the data is loaded i am trying to access the loaded data through different store functions . But not getting it..? Can anyone find what I am missing..?
Store class
Ext.define('webUi.util.rb.ResourceBundle', {
extend: 'Ext.data.Store',
requires: [
'webUi.util.rb.model.KeyValPair'
],
constructor: function(config){
config = config || {};
var me = this;
Ext.applyIf(config, {
autoLoad: true,
model: 'webUi.util.rb.model.KeyValPair',
proxy:{
type: 'ajax',
url: webUi.util.AppSingleton.uiRsrcUrl,
noCache: true,
reader: {
type: 'json',
rootProperty: 'bundle'
},
getParams: Ext.emptyFn
},
listeners:{
'load': this.onBundleLoad,
scope: this
}
});
me.callParent([config]);
me.getProxy().on('exception', this.onBundleLoadException, this, {single: true});
},
onBundleLoad: function(store, record, success, op) {
if(success){
this.fireEvent('loaded');
} else{
this.fireEvent('loadError');
}
},
onBundleLoadException: function(){
console.dir(arguments);
},
onReady: function(fn){
this.readyFn = fn;
this.on('loaded', this.readyFn, this);
},
getMsg: function(key){
return this.getById(key)? Ext.util.Format.htmlDecode(this.getById(key).get('val')) : key + '.undefined';
}
});
Model Class
Ext.define('webUi.util.rb.model.KeyValPair', {
extend: 'Ext.data.Model',
config: {
idProperty: 'key',
fields: ['key', 'val']
}
});
JSON Response
{"bundle":[{"key":"one","val":"Oneee"},{"key":"two","val":"Twooo"}]}
my Code
var bundle = Ext.create('webUi.util.rb.ResourceBundle');
bundle.onReady(function(){
console.log('%%%%%%%%%%%%%');
console.log(bundle.getMsg('one'));
console.log(bundle.getById('one'));
console.log(bundle.getAt(0));
});
console.log
%%%%%%%%%%%%%
one.undefined
null
constructor {raw: Object, modified: Object, data: Object, hasListeners: HasListeners, events: Object…}
try using bundle.data.getMsg()

kendoui: How to display foreign key from remote datasource in grid

i have a kendoui grid which list claims. one of the columns is lenders which is a foreign key reference to the lenders table. what i want is to be able to display the lender name in the grid instead of its id reference.
ive setup the lenders datasource as follows
var dsLenders = new kendo.data.DataSource({
transport: {
read: {
url: "../data/lenders/",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation === "read") {
return options;
}
}
}
});
and the grid looks like this
$("#gridClaims").kendoGrid({
dataSource: claimData,
autoSync:true,
batch: true,
pageable: {
refresh: true,
pageSizes: true
},
filterable: true,
sortable: true,
selectable: "true",
editable: {
mode: "popup",
confirmation: "Are you sure you want to delete this record?",
template: $("#claimFormPopup").html()
},
navigable: true, // enables keyboard navigation in the grid
toolbar: ["create"], // adds insert buttons
columns: [
{ field:"id_clm", title:"Ref", width: "80px;" },
{ field:"status_clm", title:"Status", width: "80px;" },
{ field:"idldr_clm", title:"Lender", values: dsLenders },
{ field:"type_clm", title:"Claim Type"},
{ field:"value_clm", title:"Value", width: "80px;", format:"{0:c2}", attributes:{style:"text-align:right;"}},
{ field:"created", title:"Created", width: "80px;", format: "{0:dd/MM/yyyy}"},
{ field:"updated", title:"Updated", width: "80px;", format: "{0:dd/MM/yyyy}"},
{ field:"user", title:"User" , width: "100px;"},
{ command: [
{text: "Details", className: "claim-details"},
"destroy"
],
title: " ",
width: "160px"
}
]
});
however its still displaying the id in the lenders column. Ive tried creating a local datasource and that works fine so i now is something to do with me using a remote datasource.
any help would be great
thanks
Short answer is that you can't. Not directly anyway. See here and here.
You can (as the response in the above linked post mentions) pre-load the data into a var, which can then be used as data for the column definition.
I use something like this:-
function getLookupData(type, callback) {
return $.ajax({
dataType: 'json',
url: '/lookup/' + type,
success: function (data) {
callback(data);
}
});
}
Which I then use like this:-
var countryLookupData;
getLookupData('country', function (data) { countryLookupData = data; });
I use it in a JQuery deferred to ensure that all my lookups are loaded before I bind to the grid:-
$.when(
getLookupData('country', function (data) { countryLookupData = data; }),
getLookupData('state', function (data) { stateLookupData = data; }),
getLookupData('company', function (data) { companyLookupData = data; })
)
.then(function () {
bindGrid();
}).fail(function () {
alert('Error loading lookup data');
});
You can then use countryLookupData for your values.
You could also use a custom grid editor, however you'll probably find that you still need to load the data into a var (as opposed to using a datasource with a DropDownList) and ensure that the data is loaded before the grid, because you'll most likely need to have a lookup for a column template so that you're newly selected value is displayed in the grid.
I couldn't quite get ForeignKey working in any useful way, so I ended up using custom editors as you have much more control over them.
One more gotcha: make sure you have loaded your lookup data BEFORE you define the column. I was using a column array that was defined in a variable I was then attaching to the grid definition... even if the lookup data is loaded before you use the grid, if it's defined after the column definition it will not work.
Although this post past 2 years, I still share my solution
1) Assume the api url (http://localhost/api/term) will return:
{
"odata.metadata":"http://localhost/api/$metadata#term","value":[
{
"value":2,"text":"2016-2020"
},{
"value":1,"text":"2012-2016"
}
]
}
please note that the attribute name must be "text" and "value"
2) show term name (text) from the foreign table instead of term_id (value).
See the grid column "term_id", the dropdownlist will be created if added "values: data_term"
<script>
$.when($.getJSON("http://localhost/api/term")).then(function () {
bind_grid(arguments[0].value);
});
function bind_grid(data_term) {
$("#grid").kendoGrid({
dataSource: ds_proposer,
filterable: true,
sortable: true,
pageable: true,
selectable: "row",
columns: [
{ field: "user_type", title: "User type" },
{ field: "user_name", title: "User name" },
{ field: "term_id", title: "Term", values: data_term }
],
editable: {
mode: "popup",
}
});
}
</script>
For those stumbling across this now, this functionality is supported:
https://demos.telerik.com/aspnet-mvc/grid/foreignkeycolumnbinding

Categories

Resources