I have this grails application and I've added a number field and a button which on click passes on the query parameters, specifically the offset value so the user can navigate to a specific page faster, since the pagination has some 2000+ pages on a max=10 basis, you can imagine navigating that. Anyway, so my problem is that I'm handing the offset with jquery and all fine but when I press enter on the number field that triggers the form which is build in combination with the controller and practically filters back to page 1. So I wonder if someone knows how would I add an extra field that will pass in an offset value as well when form with filters is submitted. Sorry no code to post but this application is a monster and I suck at Grails or Spring boot in general. Any support is appreciated.
Do you mean 2000 pages or rows.
Also i think if you share some few codes from your
Controller method
GSP (Thus the .gps file)
Javascript implementation
it will give a lot of people an insight on how to help us all solve the questions
I'll post the answer for those who might look for this.
Grails pagination uses TwitterBootstrapTagLib class, you'll find the pagination logic there. It looks for an 'offset' variable in the session params and if it doesn't find one it creates one.
Now the solution is a bit trickier than setting an 'offset' variable because when you do so you will disable the paging arrows, why? too long to explain, but trust me, you will.
To avoid having to control all the other parts of the pagination which is done perfectly well from this class you can create a new session variable, e.g. _offset, in the controller that calls the data that needs pagination.
def controllerActionX() {
...
if(params.containsKey('offset') && !params.containsKey('_offset')){
params['_offset'] = params.offset
}
...
}
You need to check first because in a second iteration you don't want to reassign offset to _offset because then you'll be stuck in one page. Also notice that offset already exists in the session, assigned by the bootstrap class.
Then you create your fields in the view:
<input type="submit" class="goto-page" id="goto-page" value="Go To Page"/>
<g:field type="number" class="topage-number" name="_offset" min="1" value="${params._offset?:1}"/>
This is self-explanatory, however, the value from the _offset field is a value entered by a human so we still need to calculate the offset based on the max records per page, i.e. in order to get page 2 on a 10 records-per-page basis, our offset has to be between 11-19, 19 preferably because it makes calculation easier.
And last step in the service layer we calculate everything like this:
def get(HttpSession session, Map params, Xclass xUser, String status) {
....
String offset = '0'
if(params.containsKey('_offset')){
if(params['_offset'] != params.offset){
params.offset = ((params._offset as int) * (max as int)) - 1
}else{
params['_offset'] = (params.offset as int) / (max as int) + 1
}
}
if (params.containsKey('offset')) offset = params.offset
...
def result = executeQuery(resultsQuery,mapping, [max: max, offset: offset])
result
That's it. Remember to cast your variables as integers when you calculate; you don't have to convert them to String after that since that is handled by the session.
By the way this is a poorly written application because the service layer should never handle any endpoint transactions, that is only a controller's job if we're following proper SOLID and MVC principles, but I found this application like this so I had to work with it.
Related
As my work involves viewing many items from a website, I need to know which items have been visited and which not, so as to avoid repeated viewing.
The problem is that the URL of these items include some garbage parameters that are dynamically changing. This means the browser's history record is almost useless in identifying which items have already been viewed.
This is an example of the URL:
https://example.com/showitemdetail/?item_id=e6de72e&hitkey=true&index=234&cur_page=1&pageSize=30
Only the "item_id=e6de72e" part is useful in identifying each item. The other parameters are dynamic garbage.
My question is: how to let Chrome mark only the "example.com/showitemdetail/?item_id=e6de72e" part as visited, and ignore the rest parameters?
Please note that I do NOT want to modify the URLs, because that might alarm the website server to suspect that I am abusing their database. I want the garbage parameters to be still there, but the browser history mechanism to ignore them.
I know this is not easy. I am proposing a possible solution, but do not know whether it can be implemented. It's like this:
Step: 1) An extension background script to extract the item_id from each page I open, and then store it in a collection of strings. This collection of strings should be saved in a file somewhere.
Step: 2) Each time I open a webpage with a list of various items, the background script verifies whether each URL contains a string which matches any one in the above collection. If so, that URL would be automatically added to history. Then that item will naturally be shown as visited.
Does the logic sound OK? And if so how to implementable it by making a simple extension?
Of course, if you have other more neat solutions, I'd be very interested to learn.
Assuming that the link to the items always have the item_id, that would work, yes.
You would need the following steps:
Recording an element
content_script that adds a code to the product pages and tracks it.
On accessing the product page:
i. You can extract the current product id by checking the URL parameters (see one of these codes).
ii. You use storage api to retrieve a certain stored variable, say: visited_products. This variable you need to implement it as a Set since it's the best data type to handle unique elements.
iii. You check whether the current element is on the list with .has(). If yes, then you skip it. If all is good, it should always be new, but no harm in checking. If not, then you use add() to add the new product id (although Set will not allow you to add a repeated items, so you can skip the check and just save add it directly). Make sure you store it to Chrome.
Now you have registered a visit to a product.
Checking visited elements
You use a content_script again to be inserted on product pages or all pages if desired.
You get all the links of the page with document.querySelectorAll(). You could apply a CSS selector like: a[href*="example.com/showitemdetail/?item_id="] which would select all the links whose href contains that URL portion.
Then, you iterate the links with a for loop. On each iteration, you extract the item_id. Probably, the easiest way is: /(?:item_id=)(.*?)(?:&|$)/. This matches all characters preceded by item_id= (not captured) until it finds an & or end of the string (whichever happens first, and not captured).
With the id captured, you can check the Set of the first part with .has() to see whether it's on the list.
Now, about how to handle whether it's on the list, depends on you. You could hide visited elements. Or apply different CSS classes or style to them so you differentiate them easily.
I hope this gives you a head start. Maybe you can give it a try and, if you cannot make it work, you can open a new question with where you got stuck.
Thanks a lot, fvbuendia. After some trial and error elbow grease, I made it.
I will not post all the codes here, but will give several tips for other users' reference:
1) To get the URL of newly opened webpage and extract the IDs, use chrome.tabs.onUpdated.addListener and extractedItemId = tab.url.replace(/..../, ....);
2) Then save the IDs to storage.local, using chrome.storage.local.set and chrome.storage.local.get. The IDs should be saved to an object array.
1) and 2) should be written in the background script.
3) Each time the item list page is opened, the background calls a function in the content script, asking for all the URLs in the page. Like this:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(changeInfo.status == "complete") {
if(tab.url.indexOf("some string typical of the item list page URL") > -1) {
chrome.tabs.executeScript(null, { code: 'getalltheurls();' });
} }
});
4) The function to be executed in content script:
function getalltheurls() {
var urls = [];
var links = document.links;
for (var i = 0; i < links.length; i++) {
if(links[i].href.indexOf("some string typical of the item list URLs") > -1) { urls.push(links[i].href);}
}
chrome.runtime.sendMessage({ urls: urls });
};
5) Background receives the URLs, then converts them to an array of IDs, using
idinlist = urls[i].replace(........)
6) Then background gets local storage, using chrome.storage.local.get, and checks if these IDs are in the stored array. If so, add the URL to history.
for (var i = 0; i < urls.length; i++) {
if (storedIDs.indexOf(idinlist) > -1 ) { chrome.history.addUrl({ url: urls[i] }); }
}
I'm trying to learn Grails but am still pretty much on beginner level.
I made a tiny application, where you can basically add events, and people can write reviews about them and rate them.
So I have an eventController and reviewController. The rating is just an Integer in a review. But now I want to show an overall rating for an event. So the events rating should be the average value of the corresponding ratings value.
This is my event domain code where the rating is initially set, I left out the constraints and toString:
class Event {
Double dRating = 2
static hasMany = [ratings:Rating]
}
The controller is simply:
class EventController {
def scaffold = Event
}
The rating domain file:
class Rating {
String comment
java.util.Date date = new java.util.Date()
Integer rating
Event event
}
and the Rating Controller is:
class RatingController {
def scaffold = Rating
}
Hope I didn't make mistakes, I had to translate variable names so they're understandable.
I'm guessing that where dRating is set, I could somehow add some calculation, but I don't even know how to access the values of the rating, and everything I try ends in lots of errors and having to restart the app again and again. I tried adding calculations in the controller, but there I don't know how to get the value into the database. So where do I actually put the logic, and how do I access the values?
If any other file is important, please tell me.
Hoping to get some hints on how to start doing this, I didn't think it would be this hard.
At first I would recommend start reading grails doc. Later from your question it is not much clear what you are asking a there could be several places or possibilities of setting up the value in domain field and persist it to database. I'm telling all of these which are known to me:
If it is generalised calculation that needs to be applied to your dRating field, then create a setter with standard bean naming convention and do this there. For example, you want to find percentage from say 1000 and then add it to dRating
class Event {
static hasMany = [ratings:Rating]
Double dRating
void setDRating(Double value){
this.dRating = value * 100/1000 // alternatively value /10
}
}
Do it in commandObject: If you don't want to put certain calculations and validation in domain then put these in command objects. See this. You can at any point of time assign values from command object to domain object by .properties binding mechanism. For example,
yourDomainObject.properties = yourcommandObjectObject.properties
Remember properties having same name would be binded.
Do it in service: You can do your calculations in service method, inject that service into your controller and call that method to perform calculations and even to persist to db as well. Remember services are by default transactional.
Hope it helps!
I'm planning on allowing a client to provide a couple codes for each product that I'll need to reference with Javascript on the product pages.
Basically my plan was to use the Big Commerce's 'custom fields' to do so, but I'm having trouble spitting out the custom fields onto the product pages. I've been looking all over for some type of GLOBAL variable that allows me to reference custom fields, but I'm coming up dry. I would think there would be some type of GLOBAL array with all the custom fields in it, or a way to reference them by name directly.
Am I blind, or is there just no way to do this directly in the BC template file?
Thanks.
In Bigcommerce the custom fields can generally be found within the ProductOtherDetails.html Panel which contains a Snippet named ProductCustomFieldItem.html. This snippet has the markup for each custom field that the system outputs.
Inside of the ProductCustomFieldItem.html Snippet are the two codes you are looking for: %%GLOBAL_CustomFieldName%% and %%GLOBAL_CustomFieldValue%%.
I ran into this as well - given that it's quite a long time later, I'm supposing there's no better answer - a decent amount of searching turned up nothing useful as it seems all you can do is output the full set of custom fields as a set of divs.
So, I output them into a div which was hidden:
<div id="fpd-custom-fields" style="display:none;">
%%SNIPPET_ProductCustomFields%%
</div>
and then set up a javascript function to get the value based on the name:
function getCustomFieldValue(label)
{
var value = '';
$('#fpd-custom-fields div.Label').each(function()
{
if($(this).text().toLowerCase() == (label.toLowerCase() + ':'))
{
value = $('div.Value', $(this).parent()).text().trim();
}
});
return value;
}
Doesn't feel quite right as it's not a very clean solution, but was the best I could come up with unfortunately!
I just wasted half a day trying to figure this out, reading about some workarounds, and thinking "it can't be that bad - there must be a straightforward to do edit a collection in Grails, whethere using scaffolded views or my own."
Let's say I have this domain object:
class TreeGroup {
String name
List<Tree> trees
static hasMany = ['trees': MyTree]
}
Just to explain the choice of data structure - I need my records to be unique, but in the order I set. That's why I chose List, AFAIK one cannot rely on order in a Set. So there are 2 pieces to this question - 1) how to remove from any Collection, for example a Set, 2) is List the best replacement for Set in this context (preserving order).
I want to be able to create a group record with no trees in it and make 4 updates:
edit/save
edit the group record to reference 2 trees A and B
add another tree C
remove A
remove B and C
And obviously, I want the desired state after every step. Currently though, I can only add records, and if I even edit/save to list, the list elements are added to it again.
I am using the multiple select tag for this. It looks like this:
<g:select name="trees" from="${allTrees}" optionKey="id"
multiple="true" class="many-to-many"
value="${trees ? trees*.id : treeGroupInstance?.trees*.id}" />
and that's fine, in the sense that it generates an HTTP header with these variables on update:
_method:PUT
version:19
name:d5
trees:1
_action_update:Update
But the data binder only adds new elements, it never lets you edit a list.
What is the cleanest way to do it ? Is it me, not reading something obvious, or is this a design flaw of grails data binding (and of so, when/how will it be fixed) ?
Is there a way perhaps via a hidden HTTP parameter to clear the list before (re)adding elements ?
Thanks
I ended up doing this:
private repopulate(def domainObject, String propertyName, Class domainKlaz) {
if (params[propertyName] != null) {
domainObject[propertyName].clear()
domainObject[propertyName].addAll(
params[propertyName].collect { domainKlaz.get(it) }
)
}
}
and I am calling it in update controller method before save(), for every collection. OMG how ugly.
Ok, I am new at jQuery, but the JQGrid has peaked my interest. While implementing the grid, I have come across two problems that I am not sure how to solve. Both involve loading the grid with results.
How do you load the grid when you have parameters in your route. For instance, http://domain.com/search/results/2010/KY...I am wanting all results matching 2010 in Kentucky. In the javascript section of the grid initialization, I need to supply a URL (such as /search/gridResults/). How does one pass the other route values or at least use them to load the grid.
Same question, but more along the lines of when the page is loaded with posted form values from a search form.
Perhaps the URL is mostly to do with AJAX-y functions. It would be nice to sort and page with AJAX but to load the grid with AJAX is not neccessary.
Sorry for the long post, but I am sure others have faced this problem even though Google tells me otherwise :) PS - I have looked at Phil Haacks (sp?) and Craig something's blogs about using JQGrid, but neither touch upon loading pre-determined search results.
You can specify that directly with the 'url' key. e.g.: /search/gridResults/2010/KY
I actually use a custom javascript method in the postData jqgrid key for this (which you could use to solve your question 1 depending on the situation). This seemed kind of lame to me that I had to write this method, but I found something on the internet and had to keep hacking on it to make it flexible enough for my uses.
Code for custom method below. It reads params from the url directly. For POST params, you would need to do something else obviously, but to get them to jqgrid, it's the same idea:
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(
window.location.href.indexOf('?') + 1
).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
if (hash.length == 2) {
vars.push(hash[0]);
vars[hash[0]] = decodeURIComponent(hash[1].replace("+", "%20"));
}
}
return vars;
}
Hopefully that helps... If you come up with something better, I'd love to hear it. :)