Retain Sorting After Specific Action - Grails - grails

I have a gsp form which displays the list of employees with the details (ie., Employee Name,Designation,Department,Status). All these columns are sortable. After calling a specific action in my controller class (ie., Changing the status of the employee from active to inactive and vice versa) the sorting gets disturbed. I am using the following code to sort while retrieving from DB
String strSort = params.sort ?: "empId";
strSort += " "
strSort += params.order?: "asc";
Is there any way I can retain the sort order which was there before posting a "Status change" action? If it is how it can be achieved?

As suggested by rvargas, it is possible through a variety of methods. queuekit plugin isn't released properly as yet so you could clone grails 3 / grails2 branch depending on which it is you are working with and also clone the test site to go with it to mess with this concept within the plugin:
In short You need to separate out your search feature and you can do this via a session value or send it as a subset list iteration.
I decided to not use sessions. Then when I click delete The bean is bound back in with the request sent (which be the id to delete)
At the very end it relists so no need to do any other here:
The most important bit being when I call the ajax reloadPage or even further postAction used by delete function is that I serialize search form. The actual search object is kept in a tidy manner here
But if this is too complex then in the very controller link the session search was commented out. I think you could just enable that forget all this complication and have a searchAgain() feature which renders the _list template like it does if it is xhr in my controller and rather than binding bean it binds the session.search map instead and if you did go down this route you probably want to change from g:render to g:include action="searchAgain"
Hope that helps you understand better

I can think of two ways to do it:
Pass your sort and order parameters to your action and send them back
with the result.
Store in session both parameters every time you update them.
To store and retrive from session use something like this:
private DEFAULT_SORT = 'myDefaultSort'
def myAction() {
if (params.sort && params.sort != session.getAttribute('sort-' + actionName)) {
session.setAttribute('sort-' + actionName, params.sort)
}
params.sort = session.getAttribute('sort-' + actionName)?:DEFAULT_SORT
...
//Your existing logic
}
If you receive a new/different sort parameter you save it into session. Then you try to load existing parameter from session, if you dont have any value stored, you get a default value.

Related

Grails - how to display result page at a unique URL

I have a grails application that takes user input (create page/method), the user then clicks a Save button (save method that executes service) and then the results are displayed (list method) on a page, for example http://localhost:8080/myApp/myclass/save.
The users would like each results run to be saved to a unique URL so they can share it, bookmark it, save it later, whatever. I have NO idea how to go about this and google searches turn up little to nothing.
For example an application run would result in the data being displayed at http://localhost:8080/myApp/myclass/systemname/datetimestring/someuniquedata/
Is this even possible? Any pointers GREATLY appreciated.
EDIT
Here is my urlMappings contents.
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?"{
constraints {
// apply constraints here
}
}
"/" {
controller = "api"
action = "create"
}
"500"(view:'/error')
}
}
When I display the results it's done through the list method shown here.
def list(Integer max) {
List<Api> api = Api.findAllBySessionId(session.id, [sort:'dateCreated'])
api = api[-2..-1]
[apiInstanceList: api, apiInstanceTotal: api.size()]
}
So I have the unique session ID. How do I need to modify "mappings"?
Every domain object that you're saving will have an autogenerated ID (assuming you're using GORM, which is definitely likely). It sounds like all you're asking for is a /show/id page where you can access a particular object via ID.
A url mapping for "/$controller/$action?/$id?" is a pretty straightfoward way to handle this, and is provided by default (and used by scaffolded controllers also).
If you'd rather not use an autogenerated ID (maybe you're moving objects from one database to another, or updating the ID for some reason?) you can consider using java.util.UUID.randomUUID() to generate a random, unique identifier and save that as a field on your object. You could then use .findByUuid with the input parameter.

Reusing json/model object to avoid making extra calls to controller

I've got a groovy userController and a _listMyUsers.gsp.
The _listMyUsers.gsp is using a
<g:dojoRemoteForm
formName="userSearchForm"
id="userSearchForm"
url="[controller:'user',action:'search']"
update="[success:'content']">
The method in the userController (search) is a simple criteria builder which returns the following back to the gsp, You can use controls in the gsp to customize the search criteria parameters (passed to the controller as param.field_name):
render (template:"listUsers",
model:[
users:users,
userTypes:UserTypeLookup.list(),
sortby:params.sortby,
direction:nextDirection,
currentDirection:sortDirection,
pager:pager,
organizations:orgs,
userType:userSearchTypes
])
Now this all works great and the model is then used to build out my usersList table. My problem comes in when I click on one of the users in the results to edit said users data, I then save. The save completes and returns to the main listUsers table. But it re-runs the search method with all searchCriteria wild carded as 'ALL' in the selections (so all users in the DB are returned).
My question is, how can I preserve the initial "custom" search returned so that when I get done editing my user, the original "search" is still there so my UI users don't have to go back and re-do their userSearch criteria again?
Thanks,
The Grails Cache Plugin might help you here. You could cache the output form the search action, using the user's query parameters as method arguments (so they can be used as keys to the cache).
#Cacheable('searchResults')
def search(String sortBy, String sortDirection /* other parameters */) {
// render the output
}
Then in your save action, you can use the CacheEvict annotation to clear the searchResults cache, so the search action will return the latest data:
#CacheEvict(value='searchResults', allEntries=true)
def saveUser() {
//save the user and return a response code
}
See the plugin documentation for details on specifying which items in the cache to evict, etc.

asp.net mvc post data and page refresh (session variable vs tempData vs detect F5)

i am teaching myself MVC and am struggling to work out the best solution to my problem. I have a search controller with a large amount of input fields. I will also have multiple overloads of the search fields eg basic search advanced search searchByCategory etc.
When the search form is posted i redirect to another action that displays the search results. If i press f5 the get action is fired again as opposed to the search results being refreshed in the action that my post redirects to. Ideally i would like to redirect to a search results Action Method without using the query string, or detect when refresh is hit and requery the database and just use different actions within the same search controller. I have read a lot of posts about this and the only 2 solutions i can find is using a session variable or TempData.Can anybody advise as to what is the best practice
From the Comments
Most of the time I prefer to use TempData in place of QueryString. This keeps the Url clean.
Question
Can anybody advise as to what is the best practice
Answer
Once the data is sent to Action Method to get the results from Database after then As per my knowledge you can use TempData to store the posted data. It is like a DataReader Class, once read, Data will be lost. So that stored data in TempData will become null.
var Value = TempData["keyName"] //Once read, data will be lost
So to persist the data even after the data is read you can Alive it like below
var Value = TempData["keyName"];
TempData.Keep(); //Data will not be lost for all Keys
TempData.Keep("keyName"); //Data will not be lost for this Key
TempData works in new Tabs/Windows also, like Session variable does.
You could use Session Variable also, Only major problem is that Session Variable are very heavy comparing with TempData. Finally you are able to keep the data across Controllers/Area also.
Hope this post will help you alot.
I think there is no need to even call Get Method after performing search although its good habit in case of if your are performing any add/update/delete operation in database. But in your case you can just return the View from your post method and no need to store data in tempdata or session until you really don't need them again. So do something like this:
[HttpPost]
public virtual ActionResult PerformSearch(SearchModel model)
{
// Your code to perform search
return View(model);
}
Hope this will help.
Hi thanks
I have had a chance to revisit this. the problem was i neglected to mention that i am using jQuery mobile which uses Ajax by default even for a normal Html.BeginForm. I was also returning a view which i have since learned will not updated the URL but only render new html for the current controller. my solution is to set the action, controller and html attributes in the Html.Beginformas follows :
#Html.BeginForm("Index", "SearchResults", FormMethod.Post, new { data_ajax = "false" })
inside the parameters for the index action of the searchResults controller I have a viewModel that represents the fieldset of the form that i am posting. The data-ajax="false" disables the Ajax on the form post and MVC takes care of matching the form post parameters to my model. This allows the url to update and when i press f5 to refresh the controller re-queries the database and updates the search results.
Thanks everybody for your help. I was aware of TempData but it is good to know that this is preferred over session data so i voted up your answer

How to create multiple domain objects from a GSP page

I have a Person class with two properties: name and address. I want to build a GSP page which allows for 10 users to be created at one time. This is how I'm implementing it and was wondering if there is a better way:
First, make 20 text boxes in the GSP page - 10 with someperson.name and 10 with someperson.address field names (make these in a loop or code them all individually, doesn't matter).
Second, process the submitted data in the controller. The someperson object has the submitted data, but in a not-so-nice structure ([name: ['Bob', 'John'], address: ['Address 1', 'Address 2']]), so I call transpose() on this to be able to access name, address pairs.
Then, build a list of Person objects using the pairs obtained from the previous step and validate/save them.
Finally, if validation fails (name cannot be null) then do something... don't know what yet! I'm thinking of passing the collection of Person objects to the GSP where they are iterated using a loop and if hasErrors then show them... Don't know how to highlight the fields which failed validation...
So, is there a better way (I should probably ask WHAT IS the better way)?
You should use Grails' data-binding support by declaring a command object like this
class PersonCommand {
List<Person> people = []
}
If you construct your form so that the request parameters are named like this:
person[0].name=bob
person[0].address=england
person[1].name=john
person[1].address=ireland
The data will be automatically bound to the personCommand argument of this controller action
class MyController {
def savePeople = {PersonCommand personCommand->
}
}
If you call personCommand.validate() it might in turn call validate() on each Person in people (I'm not sure). If it doesn't you can do this yourself by calling
boolean allPersonsValid = personCommand.people.every {it.validate()}
At this point you'll know whether all Person instances are valid. If they are not, you should pass the PersonCommand back to the GSP and you can use the Grails tags:
<g:eachError>
<g:hasErrors>
<g:renderErrors>
to highlight the fields in errors. If you're not exactly sure how to use these tags to do the highlight, I suggest you run grails generate-all for a domain class and look at the GSP code it generates.

Passing data from Controller to a User Control View with ASP.NET MVC

I have a View class (OrderView.aspx) which shows the details of an order (Account Name, Order Date) as well as a list of order lines via the Repeater control. Each order line is represented by a User Control View (OrderLineView.ascx) which shows the details of the order line (Item Name, Quantity, Price). I have a model object called Order which I use as the data source for all of this, which I pass as the model object for the view.
Each OrderLineView user control has a Save and a Delete button. I have the Save button posting the contents of a form within the OrderLine control to a Save method on the Controller and then RedirectToAction back to the same Order page (this refreshes the whole page, nothing AJAXy about it). I have the Delete button linking to a method on the Controller that tries to delete, and then RedirectToAction back to the same Order page. If the delete fails, however, I want a little error message to show up next to the delete button when the page renders again(remember, there is a delete button for every order line on the page, so I only want the message next to the one I clicked). My questions:
1 - How do I pass this data from my Controller method to the specific User Control? Should I somehow add it in to the model? Seems like a bad idea (since it really isn't part of the model).
2 - Should I have a OrderLineController for the OrderLine operations as well as a OrderController for Order operations? I just want to know if best practice is to have a separate Controller for every view.
3 - I have seen how some people might call RedirectToAction with an anonymous type value like this:
RedirectToAction("ViewOrder", new { Id = 1234, Message = "blabla"});
but this makes the Message value show up in the URL string. I am OK with that, but would prefer that it doesn't show if possible.
4 - Also, for accessing properties of the Model from within the view, I find myself doing this all of the time:
foo(((someModelType) this.ViewData.Model).SomeProperty);
I don't like this for a number of reasons, one of which is the fact that I don't want my view to be coupled with the type of my model (which is why I am using ViewPage instead of ViewPage). I would much prefer to be able to have a call like this:
foo(ModelEval("SomeProperty"));
Is there such a thing? I have written my own, but would like it if I didn't have to.
1
Check out ModelState.
ViewData.ModelState.AddModelError("something.Name", "Please enter a valid Name");
ModelState is actually a dictionary, so you could identify the errors on a per-control basis. I don't know if this is a best practice, but it would probably work.
Try something along the lines of
ViewData.ModelState.AddModelError("something#3.Name", "Please enter a valid Name");
and in your view, you could put
<%= Html.ValidationMessage(string.format({"something{0}.Name", YourUniqueId))%>
4
You can strongly type your view, so you don't need that cast, but if you're concerned about tightly coupling, this may put you off. But having the strong type there is no more tightly coupled than having a magic string point to that property of the model anyway. The former just gives you type safety and the glory that is intellisense.
Since your OrderLine has a unique ID you can use that to construct a key to be placed in the ModelState errors container.
public ActionResult Delete(int? Id)
{
ModelState.AddModelError("OrderLine" + Id.Value, "Error deleting OrderLine# " + Id.Value);
...
}
and then use the ValidatinoMessage helper. This will check the ModelState to see if an error exists and if it does it will display the message. Otherwise it's blank.
<%= Html.ValidationMessage ("OrderLine" + Id)%>
In the next release of MVC Model will become a top level property so the following
foo(((someModelType) this.ViewData.Model).SomeProperty);
can be written as
foo(Model.SomeProperty);
Model objects should already be typed unless you're using public object as a property?

Resources