Getting unexpected result if using pagination on random find query in cakephp 4? - cakephp

I am trying to find all products in random order using pagination. But getting an unexpected result.
This is my controller code:
$this->paginate = ['maxLimit' => 20];
$articlesData = $this->Products->find('all');
$articlesData->order('RAND()');
$articles = $this->paginate($articlesData);
So I get random result every time, this is the demand of the page. I have 200 products. Suppose first item is item-12 on page one then if I go to the next page and again go to the previous page then the first item should be item-12 but it changed randomly. Is there any solution for this?
I need pagination because products number going to be 1000 soon. And need random results because I don't want that user to see the same first product on the first page. The first product should be on the first page but not on the same location every time. Is there any way that I make paginated array of 20 items in random order?
All suggestions are welcomed.

Example of how to rearrange results in view template. In the controller select from the latest Articles, but in the template display these 20 results in a different place each time.
#Controller
$this->paginate = ['maxLimit' => 20];
$articlesData = $this->Products->find();
$articlesData->orderDESC('creates');
$articles = $this->paginate($articlesData);
$this->set(compact('articles'));
#template
foreach(shuffle($articles->toArray() as $article) {
echo $article['name'];
}
https://www.w3schools.com/php/func_array_shuffle.asp

When you order them randomly, they are ordered randomly. Every page load will be a new random order. See this for an example of how to make the order predictable; you might seed the generator with the user ID for example, then the order will always be the same for a given user. Or with some combination of user details and the date to give them a different random order tomorrow. Or randomly generate a seed and then save that in the session to control the duration more precisely.

Related

Populate two list with data

I currently have rest api call being done, with responseOne & responseTwo. I then add these response to a list casted to a wrapperclass. And this list is looped on to be displayed on vf page. Issue is that now I need 2 fields from the responseTwo to add these to my vf page. BOth response are linked with an ID with which data in the list can be linked. So from my responseTwo, i need number and Amount field to add this to my responseOne list to be displayed on vf page. I don't know how to achieve this based on adding the Amount to each specific data found in my responseOne.
So am trying to do looping in both datasets received.
for (Data.dataWrapper responseOne : listOne){
for(Data.dataWrapper responseTwo : listTwo){
if(responseOne.Id = responseTwo.id){
/* i need to add the amount field from responseTwo to this specific line of data at ID xxxx */
}
}
}
This is a bad pattern on performance grounds; it is of N*M complexity because you must iterate over every item in listTwo for every item in listOne. This will negatively impact your CPU limits and the responsivity of your interface.
Your wrapper class should typically include all of the data that is required to display a line item. It's not clear why these don't; you have not included any of that context in your question. Here, the most I can recommend is to digest these items into Map<Id, Data.dataWrapper> collections:
Map<Id, Data.dataWrapper> mapTwo = new Map<Id, Data.dataWrapper>();
for (Data.dataWrapper responseTwo : listTwo) {
mapOne.put(responseOne.Id, responseTwo);
}
Then, you can loop over listOne and access its corresponding listTwo entry directly, through the Map keyed on Id. This avoid the multiplicative complexity, because you end up iterating through each list exactly once, and can simply do:
mapTwo.get(responseOne.Id); // yields corresponding responseTwo entity.
You then have the data elements you need and can digest them to meet the specific needs of your Visualforce page.

How do I use the last value in an array as a path for .child() when retrieving a snapshot?

I'm new to Firebase and have a function that writes all of my event ID's to an array. I want to use the last value in that array (the last event ID) to lookup the children of that specific eventID.
I know how to get the last item in the array but how do I put that into my .child() path?
I tried the code below, but it doesn't seem to work. I'm guessing that because .child("(lastEvent)") isn't a valid path.
let lastEvent = eventIDArray.last
refHandle = ref.child("Bouts").child("\(lastEvent)")
How do I plug the lastEvent value in as my path? Or is that even possible? Again, total newbie- alternatives welcome.
Sorting and filtering data
you can use sorting and filtering function to get the item.
To get the last item you can write the query like this.**
let recentBoutsQuery = (ref?.child("Bouts").queryLimited(toLast: 1))!
This will return 1 entry from last of your database which the last entry.
You can learn more from the firebase documentation. Work with Lists of Data

print no of items fetched using pagination in cakephp 3

I want to display count of no of items fetched per page using pagination like
Displaying 10 items
Although limit is set to pagination to 20 but It will not always fetch 20 items when there are only 15 items or 10 items or 25 items.
In these cases it will either have one page result for items count 15 and 10 or two pages result for items count 25.
I want to print the no of items showing on each page. Like for total items 25.
It will show Displaying 20 items on first page and Displaying 5 items on second page.
How is it possible in CakePHP 3.2 ?
This is how I get it working in CakePHP 3.2
There are two ways you can do it.
Using Helpers
create a file paginator-counter.php in /config directory with your tokens and string and add a line in /src/view/AppView.php
public function initialize()
{
$this->loadHelper('Paginator', ['templates' => 'paginator-counter']);
}
This will load the file located at config/paginator-templates.php
And then use it in your view.
For more : http://book.cakephp.org/3.0/en/views/helpers/paginator.html
Using direct string
Just print in view where you want to print the counter
<?= $this->Paginator->counter('Showing {{current}} results out of {{count}}') ?>
More tokens can be found Here : http://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-a-page-counter
I'm using 2nd way to print counter ie., using sting directly

ExtJS 4.2 Accessing Array Elements returned from store

I am unable to access the store elements returned from my store. When I console.log(me.proxy.read(operation)) and expand/navigate in the console I see all of my elements. There are 1000 rows. I am using the same store for a grid and have the pageSize set to 50. Even though I can see 1000 rows when i do a console.log(me.proxy.read(operation.resultSet.records[51])) i get an undefined message. So, it appears that for some reason the number of elements I can access is only 50 as that is what my pageSize is set to.
Long story short, I am using the same store for two scenarios. I want to have paging in my grid that will show 50 rows on each page. However, I want to loop through the entire store and load an array of all 1000 rows. The reason why I want an array of all 1000 is becasue I am going to use a date field in the rows to populate my date picker from an array. I am going to disable the dates in my grid and have the datepicker display only the dates that are in my grid.
I tried to include a screen shot but I am not allowed because i am only a 3 on the reputation system.
var operation = new Ext.data.Operation({action: 'read', start: 0, limit: 1000});
var proxy = new Ext.data.proxy.Ajax({ url: 'http://192.168.0.103/testit/dao_2.cfc?method=getContent'});
me.proxy.read(operation);
console.log(me.proxy.read(operation));
HERE IS UPDATED CODE:
I have this in my controller:
ondatesStoreLoad: function(me,records,success)
{
var s = this.getStore('dates');
for (i = 0; i < s.getCount(); i++) {
MESSAGE_ID = s.getAt(i).get('message_id');
RECIP_EMAIL = s.getAt(i).get('recip_email');
UNIX_TIME_STAMP = s.getAt(i).get('unix_time_stamp')
console.log(i,MESSAGE_ID, RECIP_EMAIL, UNIX_TIME_STAMP);
};}
This puts out all 1,000 of my records to the console but I am not sure how to put them in an array that I can use in my datepicker component. When ever i try to get the store in the datepicker it is always undefined. I suppose it is becasue the store hasn't loaded yet so there is nothing there. Not sure how to get around that. Perhaps a callback handler?
HERE IS ANOTHER UPDATE:
I added a callback in my store.load:
var store = Ext.getStore('dates');
store.load({callback: function(){
console.log(store.data.items[999].data.recip_email);
console.log(store.data.items[999].data.unix_time_stamp);}
})
That took forever to figure out but now I can access all my records and have a smaller problem to work on. At the moment i just have one element hardcoded to do a quick test.
Where do I need to put the code to get it into my date picker disableDates config? I need to put the dates into an array but for quick testing I used minDate: just to see if i could see something work but it shows up as undefined. Now i have the code in a beforrender listener but that seemingly needs to be in some other place or maybe some handler for my date picker....? is there an onload for the datepicker or something i shoudl use for this??
Why not just change the datepicker directly from that ondatesStoreLoad function? Before the loop, disable all dates in the datepicker. Then during the loop, instead of the console.log call, enable the date that was found in that record.
In theory, that should work. However, looking at the docs for Ext, I don't see a way to disable all dates, or to enable a date. You can only set which dates are disabled. But the general idea of updating the datepicker in that ondatesStoreLoad call is still what you should do.
You might need to extend the datepicker class, and add some custom methods to it to be able to enable a specific day.

Paging with reverse cursors in appengine

I am trying to get forward and backwards pagination working for a query I have on my app.
I have started with the example at: https://developers.google.com/appengine/docs/python/ndb/queries#cursors
I would expect that example to do a typical forward/back pagination to create cursors that you can pass to your template in order to be used in a subsequent request for the page after/before the current one. But what it is doing is getting cursors for the same page, one from the beginning and the other from the end (if I have understood correctly).
What I want is a cursor to the beginning of the following page, and a cursor to the beginning of the previous page, to use in my UI.
I have managed to almost get that with the following code, based on the mentioned example:
curs = Cursor(urlsafe=self.request.get('cur'))
q = MyModel.query(MyModel.usett == usett_key)
q_forward = q.order(-MyModel.sugerida)
q_reverse = q.order(MyModel.sugerida)
ofus, next_curs, more = q_forward.fetch_page(num_items_page,
start_cursor=curs)
rev_cursor = curs.reversed()
ofus1, prev_curs, more1 = q_reverse.fetch_page(num_items_page,
start_cursor=rev_cursor)
context = {}
if more and next_curs:
context['next_curs'] = next_curs.urlsafe()
if more1 and prev_curs:
context['prev_curs'] = prev_curs.reversed().urlsafe()
The problem, and the point of this question, is that I use more and more1 to see if there is a next page. And that is not working in the backwards sense. For the first page, more1 is True, in the second page more1 is False, and subsequent pages give True.
I would need something that gives False for the first page and True for every other page. It seems like this more return value is the thing to use, but maybe I have a bad Query setup, or any other thing wrong.
Thanks everyone!
Edit: Since I didn't find a simple solution for this, I switched to using ndbpager.
There's no such thing.
You know thats theres (at least) one page before the current page if you started the query with a cursor (the first page usualy dosnt have a cursor).
A common trick to access the previous page is inverting the sort-order.
If you have a list, sorted by creationdate desc, you could take the creationdate of the first element of your current page, query for elements with creationdate < this creationdate using inverted sort order. This will return the oldest elements which are newer then the given creationdate. Flip the list of retrived elements (to bring them into the correct order again) and there you have the elements of the page before, without using a cursor.
Note: this requires the values of your sortorder beeing distinct.
In some cases, its also possible to use a prebuild index allowing random-access to different pages, see https://bitbucket.org/viur/server/src/98de79b91778bb9b16e520acb28e257b21091790/indexes.py for more.
I have a workaround and not the best solution. it is baiscally redirecting back to the previous page.
Previous
I think PagedQuery has the capability but still waiting for someone to post a more comprehensive tutorial about it.

Resources