I have a grid.Panel inside of a viewport that is binded to a store. Once the grid (or store) is loaded, I would like to look at a value in the first row (or any row), and if it's false, hide a column in the grid. I've tried many different events, but here's an example in my controller:
Ext.define('HelperBatchForm.controller.BatchController', {
extend: 'Ext.app.Controller',
stores: [
'Batches'
],
models: [
'Batch'
],
views: [
'batch.BatchGrid',
'batch.BatchEdit'
],
init: function () {
this.control({
'batchgrid': {
itemdblclick: this.editBatch
,viewready: this.onGridLoad
}
});
},
onGridLoad: function(grid){
stop;
},
"Stop" throws an error and opens the debugger in my IE browser. On the browser itself I can see the grid, and the rows, fully rendered. In the debugger, I can look at grid.store.data.items[0] and see the first row. So it seems that everything is well, and I should be able to put a condition in the function based on that data which hides the grid. But that doesn't work - here is where things start to get weird.
If I replace "stop;" with "debugger;", and reload, this time we get the visual studio debugger. But now, in the IE screen, I can only see the grid headers, and none of the data. And grid.store.data.items is an empty array. The instant I resume, I see the full grid.
But that's not all. If my function is:
onGridLoad: function (grid) {
alert('onGridLoad');
debugger;
},
Now, with the visual studio debugger loaded, I can see the full grid and data in IE. And grid.store.data.items[0] gives me the first row. If I replace "debugger" with my conditional code, it works! In other words, I have code that doesn't work, but suddenly starts working if I throw an alert() before it.
To summarize, the code below will hide the column:
onGridLoad: function (grid) {
alert('onGridLoad');
if (grid.store.findExact('is_rcm', false) >= 0) {
grid.columns[6].hide();
}
},
But if the alert is commented out, it will not hide the column.
Any ideas or explanations to why this might be would be greatly appreciated.
My guess the issue here is related to async loading of the store. You are probably seeing a race condition of a split second between the view is ready but the store is not yet populated. Just like in quantum physics the observation of the event is changing its outcome :)
My suggestion is to put a load listener on the store instead and inject your processing at that point.
I think that #dbrin is correct in assuming the data in the store is not yet loaded. But doing the processing on store load might also be problematic, when store load time is very fast, and the view is not yet ready. The following should work when the data is ready either after or before the view:
viewready: function(grid){
grid.getView().on({
refresh: {
fn: function(){
if (grid.store.findExact('is_rcm', false) >= 0) {
grid.columns[6].hide();
}
},
single: true
}
});
}
And here is a fiddle, where you can set the store load delay to test for different load times.
Related
I hope its not to harsh to ask not to mince matters.
Here we go:
I have a problem developing a custom Plugin for Shopware 5.
I already have a working plugin which lists orders for certain criteria.
Now I want a Button (which i already have) in the toolbar of this grid-window.
The Button should open the Batch Process Window which is already available in the native "Order" Window of shopware.
Q: How Can I open this app with the selected Ids of my grid?
Heres what I have:
[...]
createToolbarButton: function () {
var me = this;
return Ext.create('Ext.button.Button', {
text: 'Batch Processing Orders',
name: 'customBatchProcessButton',
cls: 'secondary',
handler: function () {
me.onClickCustomBatchProcessButton(me);
}
});
},
onClickCustomBatchProcessButton: function(me){
var thisGrid = me.getTransferGrid();
var records = thisGrid.getSelectionModel().getSelection();
console.log("Grid");
console.log(thisGrid);
console.log("records");
console.log(records);
Shopware.app.Application.addSubApplication({
name: 'Shopware.apps.Order',
action: 'batch',
params: {
mode: 'multi',
records: records
}
});
}
[...]
It always opens the normal view of the order window. (no error in console)
Anybody has a suggestions?
That would be great!
Thanks for your time :)
Greetings
EDIT:
Hey, thank you for your reply so far.
I managed to open the Batch-process-window like this:
me.getView('Shopware.apps.Order.view.batch.Window').create({
orderStatusStore: Ext.create('Shopware.apps.Base.store.OrderStatus').load(),
records: orderRecords,
mode: 'multi'
}).show({});
But now the Problem ist, the Event for the Batch-Process isn't applied on the button on the form...
I am still on try and error.
Many Shopware ExtJS SubApplications can be executed from another app with certain parameters exactly the way you're trying to. Unfortunately I don't see any code in the Order plugin that might lead to the desired result. You can see what actions/params a Shopware SubApplication supports by reading the init function of the main controller -> Shopware.apps.Order.controller.Main
Shopware.apps.Customer.controller.Main from the Customer plugin for example accepts an action like you are using it – it is checking for this:
if (me.subApplication.action && me.subApplication.action.toLowerCase() === 'detail') {
if (me.subApplication.params && me.subApplication.params.customerId) {
//open the customer detail page with the passed customer id
...
In the Order plugin there is similar code, but it just takes an order ID and opens the detail page for the corresponding order. It apparently doesn't feature the batch.Window
You might be able to reuse this class somehow, but that might be a ton of code you need to adapt from the actual Order plugin. If you really need this feature, you can carefully read how the Order plugin is initializing the window and its dependencies and have a try.
I'd rather go for developing a lightweight module in this scenario (It's a frame within a backend window that just uses controllers and template views with PHP/Smarty/HTML)
I have a not too big grid (30x20) with numbers in cells. I have to display all, calculate them in different ways (by columns, rows, some cells, etc.) and write values to some cells. This data is also written and read from db table fields. Everything is working, excluding simple (theoretically) mask tools.
In time of e.g. writing data to the field in the table I try to start mask and close it on finish. I used such a “masks” very often but only in this situation I have a problem and can’t solve it.
I prepare this mask the following way:
msk = new Ext.LoadMask(Ext.getBody(), { msg: "data loading ..." });
msk.show();
[writing data loops]
msk.hide();
msk.destroy();
I also tried to use grid obiect in place of Ext.getBody(), but without result.
I found also that the program behaves in a special way – loops which I use to write data to the table field are "omitted" by this mask, and it looks like loops are working in the background (asynchronously).
Would you be so kind as to suggest something?
No, no, no, sorry guys but my description isn’t very precise. It isn’t problem of loading or writing data to the database. Let’s say stores are in the memory but my problem is to calculate something and write into the grid. Just to see this values on the screen. Let me use my example once again:
msk = new Ext.LoadMask(Ext.getBody(), { msg: "data loading ..." });
msk.show();
Ext.each(dataX.getRange(), function (X) {
Ext.each(dataY.getRange(), function (Y) {
…
X.set('aaa', 10);
…
}
msk.hide();
msk.destroy();
And in such a situation this mask isn’t visible or is too fast to see it.
In the mean time I find (I think) a good description of my problem but still can’t find a solution for me. When I use e.g. alert() function I see this mask, when I use delay anyway, mask is too fast. Explanation is the following:
The reason for that is quite simple - JS is single threaded. If you modify DOM (for example by turning mask on) the actual change is made immediately after current execution path is finished. Because you turn mask on in beginning of some time-consuming task, browser waits with DOM changes until it finishes. Because you turn mask off at the end of method, it might not show at all. Solution is simple - invoke store rebuild after some delay.*
I have no idea how is your code looks in general but this is some tip that you could actually use.
First of all loading operations are asynchronously so you need to make that mask show and then somehow destroy when data are loaded.
First of all check if in your store configuration you have autoLoad: false
If yes then we can make next step:
Since Extjs is strongly about MVC design pattern you should have your controller somewhere in your project.
I suppose you are loading your data on afterrender or on button click event so we can make this:
In function for example loadImportantData
loadImportantData: function(){
var controller = this;
var store = controller.getStore('YourStore'); //or Ext.getStore('YourStore'); depends on your configuration in controller
var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
myMask.show();
store.load({
callback: function (records, operation, success) {
//this callback is fired when your store load all data.
//then hide mask.
myMask.hide();
}
});
}
When data is loaded your mask will disappear.
If you have a reference to the grid, you can simply call grid.setLoading(true) to display a loading mask over the grid at any time.
I have two jQuery mobile pages (#list and #show). There are several items on the #list page with different IDs. If I click on item no.5, the ID no5 will be stored in localStorage and I will be redirected to page #show
Now the problem:
Storing the ID in localStorage works, but the next page shows me not the item no.5, but it shows me an old item, that was in the localStorage before.
script from page #list
localStorage.setItem("garageID", $(this).attr('id'));
window.location.replace("#show");
I encountered this problem too (and not on a mobile : on Chromium/linux).
As there doesn't seem to be a callback based API, I "fixed" it with a timeout which "prevents" the page to be closed before the setItem action is done :
localStorage.setItem(name, value);
setTimeout(function(){
// change location
}, 50);
A timeout of 0 might be enough but as I didn't find any specification (it's probably in the realm of bugs) and the problem isn't consistently reproduced I didn't take any chance. If you want you might test in a loop :
function setLocalStorageAndLeave(name, value, newLocation){
value = value.toString(); // to prevent infinite loops
localStorage.setItem(name, value);
(function one(){
if (localStorage.getItem(name) === value) {
window.location = newLocation;
} else {
setTimeout(one, 30);
}
})();
}
But I don't see how the fact that localStorage.getItem returns the right value would guarantee it's really written in a permanent way as there's no specification of the interruptable behavior, I don't know if the following part of the spec can be legitimately interpreted as meaning the browser is allowed to forget about dumping on disk when it leaves the page :
This specification does not require that the above methods wait until
the data has been physically written to disk. Only consistency in what
different scripts accessing the same underlying list of key/value
pairs see is required.
In your precise case, a solution might be to simply scroll to the element with that given name to avoid changing page.
Note on the presumed bug :
I didn't find nor fill any bug report as I find it hard to reproduce. In the cases I observed on Chromium/linux it happened with the delete operation.
Disclaimer: This solution isn't official and only tested for demo, not for production.
You can pass data between pages using $.mobile.changePage("target", { data: "anything" });. However, it only works when target is a URL (aka single page model).
Nevertheless, you still can pass data between pages - even if you're using Multi-page model - but you need to retrieve it manually.
When page is changed, it goes through several stages, one of them is pagebeforechange. That event carries two objects event and data. The latter object holds all details related to the page you're moving from and the page you're going to.
Since $.mobile.changePage() would ignore passed parameters on Multi-page model, you need to push your own property into data.options object through $.mobile.changePage("#", { options }) and then retrieve it when pagebeforechange is triggered. This way you won't need localstorage nor will you need callbacks or setTimeout.
Step one:
Pass data upon changing page. Use a unique property in order not to conflict with jQM ones. I have used stuff.
/* jQM <= v1.3.2 */
$.mobile.changePage("#page", { stuff: "id-123" });
/* jQM >= v1.4.0 */
$.mobile.pageContainer.pagecontainer("change", "#page", { stuff: "id-123" });
Step two:
Retrieve data when pagebeforechange is triggered on the page you're moving to, in your case #show.
$(document).on("pagebeforechange", function (event, data) {
/* check if page to be shown is #show */
if (data.toPage[0].id == "show") {
/* retrieve .stuff from data.options object */
var stuff = data.options.stuff;
/* returns id-123 */
console.log(stuff);
}
});
Demo
I have a page on my site that displays sale listings, and users can either scroll down it as it is, or apply filters. If the user chooses not to apply any filters and just scroll down it as is, it works perfectly. When they choose to apply filters, I update the parameters of the infinite scroll instance so that it's loading more of the filtered results. Then, the very first time they scroll, the plugin tries to load 2 pages at once, then it crashes and unbinds itself.
Here's the function I'm using to apply the infinite scroll initially:
function initInfiniteScroll( $container, flag ){
//Initialize the plugin
console.log('Initializing infinite scroll');
$container.infinitescroll({
navSelector : "#paginationControl",
nextSelector : "#paginationControl a#next",
itemSelector : "#json_pen",
bufferPx : 200,
animate : false,
debug : true,
loading : {
img : "/includes/gif/loading.gif",
finishedMsg : "No more stuff.",
msgText : ""},
errorCallback : function(){
$("#loader.grid").fadeOut('normal');
}
},
function( entry_json ){
/* I'm loading a block of JSON to throw to Backbone instead of
grabbing html. */
console.log( 'Adding more stuff' );
//Parse the entries
var entries = JSON.parse( $(entry_json).html() );
//Throw them to the grid
Grid.addPage( entries );
});
//Mark it as having been applied
$container.addClass(flag);
}
And here is the code to update Infinite Scroll:
//Replace the pagination controls
$("#main #paginationControl").html( $("#listing_pen #paginationControl").html() );
var nextPage = $('#main #paginationControl #next').attr('href');
var basePath = nextPage.slice( 0, nextPage.length - 2 ); //Cut off the last character
//Overwrite path
$("#grid").infinitescroll({ state : { currPage : 1 },
path : [ basePath+'/', ' #json_pen' ] });
After this is called, as soon as the user tries to scroll, the next two pages try to load simultaneously and crash the plugin. I put in a few log statements to try to tell what's going on. Here's the console log:
loading /organize/10002/listings/all/10001/1001v/all/all/all
Updating the page scheme
initializing masonry
["math:", 1274, 1635]
in scroll calling the retrieve function
defined begin ajax
setting during ajax to true
["heading into ajax", Array[2]]
retrieving /organize/10002/listings/all/10001/1001v/all/all/all/2 #json_pen
["Using HTML via .load() method"]
["heading into ajax", Array[2]]
retrieving /organize/10002/listings/all/10001/1001v/all/all/all/3 #json_pen
["Using HTML via .load() method"]
["Error", "end"]
["Binding", "unbind"]
As far as I can tell, it looks like the scroll function in the plugin calls retrieve once, but retrieve calls beginAjax twice twice. Does anyone have any idea what could be going on here?
The issue wasn't caused by the plugin itself. When the opts.loading.start function is defined, it shows your loading spinner with a jQuery function call, then attaches a callback function which calls the beginAjax function to retrieve the next page of results. I modified this slightly, to:
opts.loading.start = opts.loading.start || function() {
$(opts.navSelector).hide();
$('#loader').show(opts.loading.speed, function () {
beginAjax(opts);
});
};
And it just so happened when I was grabbing the next page of results, I was also grabbing its loader. I didn't know that this was possible, but the $('#loader') was matching both the original loader and the one from the retrieved page, so the callback got executed twice, once for each loader. I added a :first to the selector and now it's working perfectly.
The way I figured this out was by riddling the retrieve function with console.log statements, then logging the scroll function the same way to find out that both were only being called once. From there it was relatively simple to figure out that it was the beginAjax function being called twice, and a quick look at the jQuery documentation explained why. Hopefully now this answer won't be completely useless to everyone else.
I use Ext.form.ComboBox in very similar way as in this example:
http://extjs.com/deploy/dev/examples/form/forum-search.html
What annoys me is that when the ajax call is in progress it shows loading text and I cannot see any results from before.
Eg I input 'test' -> it shows result -> I add 'e' (search string is 'teste') -> result dissapear and loading text is shown, so for a second I cannot see any result and think about if it's not what I'm searching for...
How can I change this to simply not to say anything when 'loading'...
The solution is to override 'onBeforeLoad' method of Ext.form.ComboBox:
Ext.override(Ext.form.ComboBox,
{ onBeforeLoad:
function() {this.selectedIndex = -1;}
});
Please be warned, that this overrides the class method, so all of the ComboBox instances will not have the LoadingText showing. In case you would like to override only one instance - please use plugins (in quite similar way).
You may also look at Ext.LoadingMask to set an appropriate loading mask to aside element if you wish.
If you don't show loading message to user how user will know what is happening? User will notice that its already loading results so may wait to see the results, but if nothing displayed then user wouldn't know if its bringing new data or not.
You may monit the expand event of the combobox and set picker loading to false.
// in the controller
init: function() {
this.control({
"form combobox[id=fieldId]": {
expand: function(combobox) {
combobox.getPicker().setLoading(false);
}
}
});
}