Referring to Related Record ID In Controller On Save() - grails

I'm still new to Grails and GORM and I got stumped on this and wasn't able to figure out what I am doing wrong. The intent is to automatically relate the record to the logged in user through the Shiro plugin for Grails.
Class User { static hasMany = [stuff: Stuff] }
Class Stuff { static belongsTo = [user:User] }
Class StuffController {
def create = {
params.put('user', User.createCriteria().get{eq('username',SecurityUtils.subject.principal)}.id)
def stuffInstance = new Stuff(params)
stuffInstance.save()
}
}
I saw in the generate-views version of the create scaffold that the relevant field was referred to as name="user.id", but neither it nor variants (such as user_id) seems to work. The query to the Users domain returns the record id necessary, and params.put in this context seems to correctly append the params object with the new value when I render to a test page (so I'm guessing it's not immutable), but this is what I get from the save():
Property [user] of class [class org.stuffing.Stuff] cannot be null
I've even tried flipping it around and going the other way, with the same result:
User.createCriteria().get{eq('username',SecurityUtils.subject.principal)}
.addToStuff(new Stuff(params))`
.save()
Anyone able to enlighten me on what I'm missing here?
Thanks!
EDIT:
Apparently I was being braindead; I was overriding the "create" method, but the default action is "save" in the _form.gsp template, so it wasn't executing that branch.
On the plus side, I did learn about dynamic finders via Burt below, so it wasn't a total wash.
Thanks for your time, guys!

Your code can be a lot cleaner - there's no reason to use createCriteria here. If you're searching by username, use a dynamic finder:
def stuffInstance = new Stuff(params)
def user = User.findByUsername(SecurityUtils.subject.principal)
stuffInstance.user = user
if (!stuffInstance.save()) {
// inspect stuffInstance.errors
}

Related

Grails Session scope for service not working as expected

I'm making a web app that stores reports of various types as domain objects, so I have a domain object HeadOfHousehold which contains name data, and references to other domain objects such as the reports, addresses, and any dependants. I am trying to build a list of recently viewed/created HeadOfHousehold objects. After multiple Google searches, and scouring the manual, it appeared that a service would be an appropriate solution. So I created ClientListService:
#Transactional
class ClientListService {
static scope = "session"
String message // right now I'll be happy to just see the same message across
// pages I can add a list and manipulate it later.
}
I thought I could then reference it in my various controllers, and it would persist Something like this:
def clientListService
def index(){
hasSearched = false
clientListService = new ClientListService(message: "Hello")
[errorMessage: params.errorMessage, clients:clientListService]
}
Which should be available in a later controller:
class HeadOfHouseHoldController {
def clientListService
def index() {
[customer: HeadOfHousehold.get(params.id), clients: clientListService]
}//...
However when I try to get the message, it appears as if the object is null.
From my index.gsp:
***************${clients?.message}********************
So I don't know if I am not defining session properly (I'm not doing anything special to do so), if I'm misunderstanding how the session scope works, or something else. I do see the proper message on the original page which has defined the object, however I don't see it on any subsequent pages.
Also, I'm not sure if this is the proper way to go about this; right now all I really need is the list of HeadOfHouseholds that I would need (so I can add to the list from other pages), however I can see possibly adding other logic and items into such a class.
I think you understood the session scope correctly. Each Spring bean with a session scope is bound to the HTTP session.
But your first controller listing does it all wrong. You are not supposed to instantiate the service class yourself. This is what Spring (Grails) does.
class FooController {
def clientListService // gets autowired by Grails/Spring
def index(){
hasSearched = false
clientListService.message = 'Hello' // only assign a String value to the service
[errorMessage: params.errorMessage, clients:clientListService]
}
}
This means you cannot not do something like
clientListService = new ClientListService(message: "Hello")
and expect your code to work. Hope this helps.

grails and spring security acl: show only some instances of a domain class

I'm using Spring Security ACL in my Grails project to manage access into my application. I can create Admin and User to have different permissions into the application.
Now, I want that a particular user can see only some instances of a domain class object. That is:
following the example domain class object
class Patient
{
String name;
String surname;
...
}
Suppose that there are 3 created Patient objects.
I want that, if I login with
username = test1
password=test1
I can see only Patient that belongs to this User.
I think that is needed that, when I create a new Patient, it is stored that this Patient belongs to the User currently logged.
How can I do that?
EDIT:
Another problem is that, if I change the URL in the part of id to show, I can see all the Patient that are created. I want that, if I change URL manually, I see an access error. Is it possible?
EDIT 2:
How can I get the role of the user currently logged in? I've tried with the following code How to get current user role with spring security plugin? but I cannot perform the getAuthorities() because it tells me that it does not exists
I've solved EDIT2 in the following discussion grails exception: Tag [paginate] is missing required attribute [total]
I need to solve the EDIT1
thanks
If I understand you right you need to define belongsTo. This will create mapping in database from Patient to User.
Edit: to get current logged in user use
class SomeController {
def authenticateService
def list = {
def user = authenticateService.principal()
def username = user?.getUsername()
.....
.....
}
}
To map to user change logic in controller or use events to create mapping
Edit: edit create action:
class PatientController {
def authenticateService
...
def create() {
def patientInstance = new Patient(params)
patientInstance.user = authenticateService.principal()
...
[patientInstance: patientInstance]
}
...
}

Grails: how to retrieve a persistent value for the collection?

I'm writing a Grails application and I need to retrieve a persistent value for the collection of my domain class objects. Let's consider we have got the following domain object:
class UserGroup {
SortedSet<User> users
static hasMany = [ users: User ]
// ...
def beforeUpdate() {
println "BEFORE UPDATE: " + this.getPersistentValue('users');
}
}
class User implements Comparable<User> {
String name
}
And the controller which has the following action:
class UserGroupController {
def addUser() {
UserGroup group = UserGroup.get(params.long('gid'))
User user = User.get(params.long('uid'))
group.addToUsers(user)
group.save(failOnError:true, flush:true)
}
}
The problem is that when beforeUpdate() is called, the users collection already contains the recently added user. So, seems that addTo() method doesn't trigger the beforeUpdate() event.
The same problem occurs when we're talking about isDirty() method. As the changes are applied before the beforeUpdate() is called, the collection is not recognized as dirty field.
Does anyone know how to change this? I'm writing a feature which tracks the history of changes for lots of different object, so I need to have access to the previous value in order to understand whether its value was changed or not.
I have had a similar issue, where things are being updated when I wasn't expecting them when I used the .get() on domain classes. I like to use .read() now because it wont update the database when I'm not expecting it to. Grails does a lot of sneaky things behind the sense which are helpful I think but can be a bit confusing.

Grails Plugins Requiring External Relationships

I posted this on the Grails mailing list yesterday and haven't had any hits. Figured I'd try here as well today.
I'm considering writing a grails plugin but this plugin would require some sort of relationship to an account / user object. However, I don't want to force a particular security model on the plugin. For example, say was writing a comment system plugin (I'm not). I'd have a comment object...
class Comment {
String comment
Date dateCreated
// etc etc
}
The comment is missing a couple of things:
Who added the comment
What the comment was added to.
I'd like to first focus on #1. So someone might be using the Spring security plugin and use the default Person object, or maybe they changed that to User. Who knows. Is there any way that anyone can think of to configure that relationship without hard coding it in the plugin?
One thing I've thought about was to have the grails app extend the plugin's domain classes to add this relationship. so I might do something like...
class ArticleComment extends Comment {
static belongsTo = [user:User]
}
But in a larger plugin, that might be a lot of inheritance requirements. Not the end of the world, but just looking for other possible options.
You can use the same technique employed by the Commentable plugin:
The user of your plugin will need to declare a closure in Config.groovy to evaluate the logged user:
grails.myplugin.user.evaluator = { session.user }
And you can use something like this in your plugin's code to call the user configured closure:
def evaluateUser() {
def evaluator = grailsApplication.config.grails.myplugin.user.evaluator
def user
if(evaluator instanceof Closure) {
evaluator.delegate = this
evaluator.resolveStrategy = Closure.DELEGATE_ONLY
user = evaluator.call()
}
if(!user) {
throw new Exception("No [grails.myplugin.user.evaluator] setting defined or the evaluator doesn't evaluate to an entity. Please define the evaluator correctly in grails-app/conf/Config.groovy")
}
if(!user.id) {
throw new Exception("The evaluated user is not a persistent instance.")
}
return user
}
I think you can do it like SpringSecurity do. Instead of let people extend your Comment class, You can write 2 class CommentUser & CommentPlace; then let others extends them. I think it's more simple.

Grails efficient hasMany-Relationship in View

I'm saving contacts (email, mobile phone, ICQ, AIM etc.) for people like this:
class Person {
static hasMany = {
contacts: Contact
}
}
class Contact {
String code
ContactType type
}
class ContactType {
String name
}
In my view, I've written some Templates for displaying each contact with a select-box for the contact-type and a textfield for the code, spiced up with some JavaScript for adding and deleting.
My question is: Is there an easy and elegant way to update the data similar to personInstance.properties = params or do I have to read out all the fields, deleting removed, updating changed and adding new ones?
I was looking into this some time ago but never got to refactor our code which handles parameters the old-fashioned way.
According to http://www.grails.org/Controllers+-+Data+Binding you can do something like this
def person = new Person(params['person'])
def contact = new Contact(params['contact'])
def conctactType = new ContactType(params['contactType'])
as long as request params are properly namespaced
person.contact.code
person.contact.type.name
You would still have to find out how to handle one to many. Maybe someone who knows can chip in.
Edit:
Came across this doc which describes how to handle one-to-many. It doesn't appear on the main grails site:
http://svn.codehaus.org/grails/tags/GRAILS_DOCS_1_1/src/guide/6.1.6%20Data%20Binding.gdoc

Resources