How to access a string from one method to another in one controller? - grails

If we have one controller, let's call it document, that has two methods, one that uploads file and another that shows the uploaded file.
I would like to define a new string in the upload method that checks the size of the file and store a specific type name inside that string.
However I would like to access that string in another method which is the list method to be able to show it.
Here is my code:
Class DocumentController {
def list() {
//Here I would like to access that String to show it on the page
[fileSizeType: fileSizeType]
}
def upload {
//define the new String variable
String fileSizeType = ""
if(fileSize < 1000) {
fileSizeType = "type1.."
} else {
fileSizeType = "type2.."
}
}
}
In the gsp page I would like to access the string this way:
<td><g:link>\${fileSizeType}</g:link></td>
I am getting this error when I try the code above:
No such property: fileSizeType for class: file_down.DocumentController

You need to redirect to the list action while passing your argument in the params.
def upload() {
// simplify with ternary expression
def fileSizeType = (fileSize < 1000) ? "type1.." : "type2.."
redirect action:'list', params:[fileSizeType: fileSizeType]
}
// in your list action
def list() {
[fileSizeType: params.fileSizeType]
}

Related

GRAILS: findALL() vs FindBy---(params.id)

Greeting everyone,
I am trying to pass a parameters from a URL to a findAll() method.
LINE3 I use findAll() to define mouse.
LINE2 def house will bring in the parameter DELAWARE when I go to the page: http://localhost:8080/TestApp/home/county/DELAWARE
House will only show one instance instead of a list.. is there anyway to pass the url instead of ["DELAWARE"]? (please see line 3) thanks :)
def county() {
def house = Home.findByCounty(params.id) //sends only user related address to view
def mouse = Home.findAll("from Home h where h.county= ?", ["DELAWARE"]);
if (!house) {
response.sendError(404)
} else {
[house:house, mouse:mouse ]
}
}
Working Code +1 #Danilo
def county() {
def house = Home.findAllByCounty (params.id) //sends only county specified thru URL e.g. http://localhost:8080/TestAPP/home/county/DELAWARE
if (!house) {
response.sendError(404)
} else {
[house:house ]
}
}
findBy* will return at most one row, if you want to get all rows use findAllBy*
In order to understand how the URL will be used by Grails you have to have a look at conf/UrlMappings.groovy. You may find something like this:
static mappings = {
"/$controller/$action?/$id?(.$format)?"{
}
}
this means that when you call TestApp/home/county/DELAWARE what Grails is trying to do is use the home controller (HomeController), invoking the county method (def county(){...}) and passing DELAWARE as id.
This should work correctly if inside county method of the HomeController you have:
def filteredInstances = Home.findAllByCounty(params.id)

Grails parameter passing

Basically I am using the code below for debugging. It renders null and I cannot figure out the
reason. And by the way the else statement will always be executed at this point. At first I
didnt have the save method but I then thought it might fix my issue. May is have to do with
the scope of my domains? As of now I have them set to session scope:
class Info {
static scope = "session"
String name
String smokingStatus
String[] symptom
static constraints = {
}
}
else{//query did not find patient with that id
def patInfo = new Info()
patInfo.name = "Dennis"
patInfo.smokingStatus = "Former Smoker"
patInfo.symptom = ["Cough"]
patInfo.save()
redirect(action:"display", params: [patInfo:patInfo])
//redirect(action:"login")
//return to login action and
}
}
}
def display(){
render params.name
}
Thanks for any help its much appreciated.
You are assign the value of patInfo to variable name patInfo so in the display action you must use:
render params.patInfo
By example if you will use the following:
redirect(action:"display", params: [duck:patInfo])
You must use:
render params.duck

Is it possible to save a variable in controller

I would like to save a variable in the controller to be able to use it for all methods so I declared 3 private strings
public class BankAccountController : Controller
{
private string dateF, dateT, accID;
//controller methods
}
Now this method changes their values:
[HttpPost]
public ActionResult Filter(string dateFrom, string dateTo, string accountid)
{
dateF = dateFrom;
dateT = dateTo;
accID = accountid;
//rest of the code
}
I used a breakpoint and the variables are being changed when I call that controller method, however when I call other controller methods such as these below the private strings are being reset to emtpy strings, how can I prevent it from happening?
public ActionResult Print()
{
return new ActionAsPdf(
"PrintFilter", new { dateFrom = dateF, dateTo = dateT, accountid = accID }) { FileName = "Account Transactions.pdf" };
}
public ActionResult PrintFilter(string dateFrom, string dateTo, string accountid)
{
CommonLayer.Account acc = BusinessLayer.AccountManager.Instance.getAccount(Convert.ToInt16(accID));
ViewBag.Account = BusinessLayer.AccountManager.Instance.getAccount(Convert.ToInt16(accountid));
ViewBag.SelectedAccount = Convert.ToInt16(accountid);
List<CommonLayer.Transaction> trans = BusinessLayer.AccountManager.Instance.filter(Convert.ToDateTime(dateFrom), Convert.ToDateTime(dateTo), Convert.ToInt16(accountid));
ViewBag.Transactions = trans;
return View(BusinessLayer.AccountManager.Instance.getAccount(Convert.ToInt16(accountid)));
}
Every request you make a new instance of the controller will be created, therefore you're data is not shared between requests. There's a few things you can do to save the data:
Session["dateF"] = new DateTime(); // save it in the session, (tied to user)
HttpContext.Application["dateF"] = new DateTime(); // save it in application (shared by all users)
You can retrieve the values in the same way. Of course, you could also save it somewhere else, bottom point is, controller-instances are not shared, you need to save it somewhere else.
The following method is very simple, and makes sure the variable is tied to the current user, instead of that it is used in your entire application. All you need to do is type the following code in the controller:
Session["dateF"] = dateFrom;
Session["dateT"] = dateTo;
Session["accID"] = accountid;
and whenever you want to use that variable, for instance you want to give it as an parameter to a method, you just type this:
MyMethod(Session["dateF"].ToString());
That is how you save and use a variable in ASP.NET MVC
You could use a static field in the controller so it's shared between all requests.
private static List<someObject> yourObjectList;

Save On My Domain Class Object Is Not Working.

I have a User class which has a List field namely pt. This field is not initialized when User register his account. But when user goes this controller action :
def updatePt() {
//performs some action
def user = User.get(springSecurityService.principal.id) //find the user
user.pt = []
//on certain conditions i put values into user.pt like this
user.pt << "E"
//at last I save it
user.save()
}
But using user/show action via scaffolding I found that pt field is not saved on users object. Where I'm making a mistake?
You have to provide a static mapping in the Users domain class so that Grails knows the field must be persisted:
class User {
static hasMany = [pt: String]
}
It's possible because of validation error. Try with
if (!user.save()) {
log.error('User not saved')
user.errors.each {
log.error('User error: $it')
}
}
PS or you can use println instead of log.error

Sending data to "View" from "Controller"

In my controller class have the following code
class MyController {
def flickrService
def index = {
def data = flickrService.search {
tags 'tag,tag2,tag3'
page 3
perPage 14 // Look ma!
}
[urls:data.urls,page:data.page,pages:data.pages]
}
}
I have also created an index.gsp file.
As I am new to groovy grails - i could not figure it out how to access data returned by flickrservice in the view. Can I just access "data" defined above in the index view or I need to set it in the controller before I can loop through the returned data? Any help would be highly appreciated. Thanks
Yes, now you can access data from the view, for example,in index.gsp:
<html><head>Test</head><body>${urls} <br/> ${page} </body></html>
Generally saying, grails return the last value in function by default, so if you want to access many data, you can do like this:
class MyController {
def flickrService
def index = {
def data = ...
def data1 = ...
def data2 = ...
// Here's the return result:
[view_data:data,view_data1:data1, view_data2:data2]
}
}
Then you can access ${view_data},${view_data1},${view_data2} in view.

Resources