GRAILS g:each problem - grails

I cant get the g:each to work. I am trying to iterate over anything but it never works = doesnt generate any html.
index.gsp
<g:each var="i" in="${userList}" controller="user">
<li>Item ${i.name}</li>
</g:each>
userController.groovy
class UserController {
...
def userList = {
User.list()
}
...
}
Then I have User.groovy filled with number of users..
What am i supposed to write in in="${.....}" to iterate for example over users declared as User.groovy ? I have tried : User, users, User.list() ...
Thanks
EDIT:
Let's say i have a
def findOne {
[users : User.findAllByNameLike("%Petr%")
}
in my UserCotroller.
How do i use g:each for it because
<g:each var="user" in="${findOne}">
won't do anything..

In your example. userList is a Closure, so it's the action name, so I'm assuming you're accessing http://localhost:8080/appname/user/userList
If you return something from a controller action to be rendered in the GSP, it has to be in a Map, the "model". Each value in the map is exposed in the GSP using the map key as its name. So the controller action corresponding to your GSP would be
def userList = {
[users: User.list()]
}
and then you can iterate with
<g:each var="user" in="${users}">
<li>Item ${user.name}</li>
</g:each>
The name doesn't matter - it just has to be the same in the model map as in the GSP.

Related

how to bind to sqldate?

I have a simple setup.
import java.sql.Date as SqlDate
class Book {
String name
SqlDate publishedDate
static constraints = {
}
}
In application.yml
grails:
databinding:
dateFormats:
- 'dd/MM/yyyy'
Book Controller save method
def save(){
def book = new Book()
bindData(book, params)
book.save()
render "done"
}
Create page
<g:form action="save">
<g:textField name="name"></g:textField>
<g:textField name="publishedDate"></g:textField>
<g:submitButton name="Submit"></g:submitButton>
</g:form>
When i use normal java date then the date binding works but when i use the sql.Date then bindData() doesnt seem to bind the date. Does bindData not work on sql.Date? Thanks for help!

Getting null or empty when i want to show image from data in MVC

I want to dispaly image from database in Mvc but it show me null or empty error. Value cannot be null or empty. Parameter name: contentPath.
Please tell me any one what are my mistake in this code:
#foreach (tbl_AdminManageProducts item in #Model)
{
<tr>
<td>#item.CategoryCode</td>
<td>#item.ProductName</td>
<td>#item.ProductPrice</td>
<td>#item.ProductDetail</td>
<td><img src="#Url.Content(item.ProductImage)" /></td>
<td>#item.CompanyName</td>
</tr>
}
This is controller:
public class AdminController : Controller {
// GET: /Admin/
public ActionResult Index() {
FYP_WISHEntities db = new FYP_WISHEntities();
return View(db.tbl_AdminManageProducts.ToList());
}
}
Looks like you are trying to call the Url.Content method with a NULL value. The possible reason for this could be a null value is returned from the expression item.ProductImage for one of the iteration of your loop. So adding a null check would fix your error.
<td>
#if(String.IsNullOrEmpty(item.ProductImage))
{
<img src="#Url.Content(item.ProductImage)" />
}
</td>
This code will try to render the image tag markup only if your item has a non null/non empty ProductImage property value.
Url.Content method takes a valid content path to the file. So make sure your item.ProductImage returns that when not null or empty.

Formatting POJO inside Grails/GSP select element

I have the following POJO/POGO:
class Person {
String firstName
String lastName
int age
// ... lots of other fields
}
And a Grails 2.3.6 controller:
class PeopleController {
List<Person> people = new ArrayList<Person>()
def populatePeople() {
// Add lots of people to the 'people' list.
}
def doSomething() {
populatePeople()
render(
view: "people",
model:[
people: people,
]
)
}
}
And then in the GSP:
<div id="peopleSelector">
<g:select name="people" from="${people}" />
</div>
When I run my app I get the <select> element with com.me.myapp.domain.Person#398r4d99-looking values as <option>s. This is obviously Grails not deserializing my Person instances into pretty print form.
I want peoples' first and last names to appear as the select options. Hence, if one of the Person instances in the people list is:
Person smeeb = new Person(firstName: "Smeeb", lastNname: "McGuillocuty")
Then I would expect "Smeeb McGuillocuty" as a select option in the final HTML. How can I accomplish this?
Add the following method to your Person class:
#Override public String toString() {
"$firstName $lastName"
}
And, somewhat unrelated to the actual question, you may have to add an identifier to your option rows to uniquely identify the person. Assuming the Person class has an id property:
<g:select name="people" from="${people}" optionKey="id" />
so that you get the following HTML:
<select name="people" id="people">
<option value="123">Smeeb McGuillocuty</option>
:
Useful link to official doc: http://grails.org/doc/latest/ref/Tags/select.html:
"..The default behaviour is to call toString() on each element in the from attribute.."
If you can't/won't "sacrifice" toString() for rendering in HTML you can also tell the g:select how to render the options. Either by providing the name of a property in optionValue (e.g. optionValue="fullName" and then provide a String getFullName() method (watch out for transients, if you pass a GORM object)) or by providing it directly in the GSP:
<g:select name="person" optionKey="theId" optionValue='${{"$it.lastName, $it.firstName"}}' from="${people}" />

Get error when using findBy() in grails

I have a GSP page:
<g:if test="freelancer">
<g:each in="${ freelancer }" var="freelance">
${ freelance.firstName }
</g:each>
</g:if>
and an action:
def homepage() {
println(params.id)
def user = User.find{
username == params.id
}
if(user){
println(user.username + "!")
return[user:user]
}
}
and a welcome page:
<body>
Welcome ${ user.username }
</body>
in the first GSP page I get firstName link, and when I click on it to view his homepage I get an error:
Cannot get property 'username' on null object
But in the Console of my IDE, println(params.id) prints a username, BUT with square brackets. What is wrong in my code?
In your "homepage" action try
def user = User.find{ it.username == params.id } instead of
def user = User.find{ username == params.id }
Yes, you will have to use brackets in your tag. That's number one.
<g:if test="${freelancer}">
</g:if>
Otherwise, the groovy truth will always evaluate a non-empty string as true, thus your test will be flawed.
Also, I would use the g:link instead of html 'a' tag.
<g:each in="${ freelancer }" var="freelance">
<g:link controller='user', action='homepage', id="${freelance.user.username}">
${freelance.firstName}
</g:link>
</g:each>
As a suggestion, think of using User.findByUsername() instead of find closure.
Let us know if that works. ;)
This is my User domain class:
class User {
String username
String passwordHash
byte[] passwordSalt
Profile profile
static hasMany = [ roles: Role, permissions: String ]
static constraints = {
profile(nullable:false)
username(nullable: false, blank: false, unique: true, size:3..15)
passwordHash(nullable:false, blank:false, minSize:6)
}
static mapping = {
profile lazy:false
}
In the g:if tag I put freelancer to the brackets and changed to User.findByUsername(). But there is the same error. I don't want params.id as list.

Grails checkbox handling

Let's say, i have this scenerio:
But let's say i have hundreds of those checkBoxes, which i need to handle everything at same time after submiting a form. I then will need to save to the BD something based on which boxes are checked, and the id of each block
So, i need this:
a) a way to know which checkboxes are checked, within hundreds of them
b) each checkbox should be 'linked' with an id which im gona pass, so that a specific action will be performed.
I have a <g:each> tag writing me the whole table, reading values from the DB. I would appreciate any help with this,
Thanks in advanced, RR
You can bind the params to a List property of a domain object or command object.
View:
<g:each in="${elements}">
<g:checkBox name="elementSelected[${it.id}]" value="${it.id}" />
</g:each>
Command Object:
class ElementCommand {
List elementSelected
}
Controller:
def execute = { ElementCommand cmd ->
cmd.elementSelected.each {
if (it) {
processId(it.toInteger())
}
}
}
In your gsp you need to display all the checkboxes:
<g:each in="${model}" status="i" var="invoiceItem">
<tr class="${(i % 2) == 0 ? 'odd' : 'even'}">
<td>
<g:checkBox name="invoiceItem_${i}"/>
</td>
</tr>
</g:each>
In the controller action you need to map the selected checkboxes to your domain objects
List invoiceList = session.invoiceList
params.each {
if (it.key.contains("invoiceItem_")){
if (it.value.contains("on")){
InvoiceItem invoiceItem = invoiceList.get((it.key - "invoiceItem_") as Integer)
}
}
}

Resources