Need help in grails model association - grails

I am facing problem with Grails model association. Here is problem:
Subscriber and Customer are extended from PartyRole.
A customer may have many subscribers and a subscriber belongs To customer.
A Party may have many PartyRole.
Person and Organization are extended from Party.
A Person belong to Organization.
A Person has many Profile and a profile belongs to Person.
Now I want to edit currently logged-in user(subscriber) which is basically organization type mean has organization properties like orgName and orgSize.
I can find Person(firstName and lastName) and Profile (emails) details using logged-in user(subscriber) but not able to get Organization details. Code is following.
def profile = {
Subscriber loggedinSubscriber = Subscriber.get( springSecurityService.principal.id )
if (loggedinSubscriber == null){
redirect(controller: "login" , action:"login");
}
else{
println loggedinSubscriber
Party person = Person?.get(loggedinSubscriber.party.id)
Party org = Organization?.get(loggedinSubscriber.party.id)
Profile profile = person?.profile
[userInstance: person, authorityList: sortedRoles()]
}
}
When I tried to get Organization details with
Party org = Organization?.get(loggedinSubscriber.party.id)
I got null value but in same way I can get Person details using logged-in user(subscriber) and both are extended from Party.`
Any idea to how to get Organization details.
Person:
package com.vproc.member
import com.vproc.enquiry.Enquiry;
import com.vproc.enquiry.Membership;
import com.vproc.enquiry.Notification;
import com.vproc.enquiry.Team;
class Person extends Party{
String firstName
String lastName
Profile profile
static belongsTo = [Organization]
static constraints = {
lastName nullable:true
firstName blank:false
}
}
**Organization:**
package com.vproc.member
import java.util.Date;
class Organization extends Party{
String orgName
Person contact
int orgSize
boolean isVendor
static constraints = {
}
}
Profile:
package com.vproc.member
import java.util.Date;
import com.vproc.enquiry.Enquiry;
import com.vproc.enquiry.Membership;
import com.vproc.enquiry.Team;
class Profile {
String emailAddress // field governed by privacy policy
String phoneNumber // field governed by privacy policy
Date dateCreated
Date lastUpdated
boolean isDefaultProfile
String status
static belongsTo = [person:Person]
//ProfilePrivacyLevelEnum privacyLevel = ProfilePrivacyLevelEnum.Private
static constraints = {
}
}
Subscriber:
package com.vproc.member
import java.util.Date;
import com.vproc.common.StatusEnum;
import com.vproc.enquiry.Discussion;
import com.vproc.enquiry.Enquiry;
import com.vproc.enquiry.Membership;
import com.vproc.enquiry.Notification;
import com.vproc.enquiry.SharedEnquiry;
import com.vproc.enquiry.Team;
import com.vproc.order.Seat;
class Subscriber extends PartyRole{
transient springSecurityService
String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
StatusEnum status
Date dateCreated
Date lastUpdated
List<Contact> contacts ;
static belongsTo = [ customer: Customer]
static hasMany = [seats: Seat, ownedEnquiries: Enquiry,enquiresSharedWith: SharedEnquiry, enquiriesSharedBy: SharedEnquiry ,
managedTeams: Team , memberships: Membership, contacts: Contact , sharedByContacts: SharedContact, sharedWithContacts: SharedContact,
vContacts: VContact, partOf: VContact, sharedbyVContacts: SharedVcontact, sharedWithVcontacts: SharedVcontact,
notifications: Notification, discussions: Discussion]
static mappedBy = [ managedTeams : "manager" , enquiresSharedWith: "sharedWith" , enquiriesSharedBy: "sharedBy" ,
sharedByContacts : "sharedBy" , sharedWithContacts : "sharedWith" ,
vContacts: "forSubscriber" , partOf :"ofContact",
sharedbyVContacts: "sharedby" , sharedWithVcontacts :"sharedWith"
]
static constraints = {
username validator : { val , obj ->
if (obj.status != StatusEnum.Pending)
val!= null
}
username unique: true
password validator : { val , obj ->
if (obj.status != StatusEnum.Pending)
val != null
}
contacts nullable: true
notifications nullable : true
username nullable: true
password nullable: true
}
static mapping = {
password column: '`password`'
}
Set<Role> getAuthorities() {
SubscriberRole.findAllBySubscriber(this).collect { it.role } as Set
}
def beforeInsert() {
encodePassword()
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}
protected void encodePassword() {
password = springSecurityService.encodePassword(password)
}
}
Party:
package com.vproc.member
import java.util.Date;
class Party {
Date dateCreated
Date lastUpdated
static constraints = {
}
static mapping = {
tablePerHierarchy false
}
}
PartyRole:
package com.vproc.member
import java.util.Date;
class PartyRole {
Party party
Date dateCreated
Date lastUpdated
static constraints = {
}
static mapping = {
tablePerHierarchy false
}
}
BootStrap:
class BootStrap {
def init = { servletContext ->
def userRole = Role.findByAuthority('ROLE_USER') ?: new Role(authority: 'ROLE_USER').save(failOnError: true)
def adminRole = Role.findByAuthority('ROLE_COMPANY_ADMIN') ?: new Role(authority: 'ROLE_COMPANY_ADMIN').save(failOnError: true)
def guestRole = Role.findByAuthority('ROLE_GUEST') ?: new Role(authority: 'ROLE_GUEST').save(failOnError: true)
def csrRole = Role.findByAuthority('ROLE_CSR') ?: new Role(authority: 'ROLE_CSR').save(failOnError: true)
//PersonRole.create adminUser, adminRole
def address = new Address( city : 'Pune' , stateCode : 'MH' , countryCode : 'IN' )
def adminProfile = Profile.findByEmailAddress('sachin.jha#gmail.com' )?: new Profile(
privacyLevel: ProfilePrivacyLevelEnum.Private,
emailAddress: "sachin.jha#gmail.com" ,
phoneNumber: "9325507992",
status : 'Active'
).save( failOnError: true)
def adminPerson = Person.findByProfile( adminProfile) ?: new Person( firstName: 'admin' , lastName : 'user' , profile: adminProfile).save( failOnError: true) ;
def vprocOrganization = Organization.findByOrgName('VPROCURE') ?: new Organization ( orgName: 'VPROCURE' , orgSize : 100 , mailingAddress: address, contact: adminPerson ).save( failOnError: true)
def vprocCustomer = Customer.findByParty( vprocOrganization) ?: new Customer ( party: vprocOrganization, status: StatusEnum.Active ).save(failOnError: true) ;
def adminUser = Subscriber.findByUsername('admin') ?: new Subscriber( username : 'admin' , password : 'passw0rd' , enabled: true , party: adminPerson, customer: vprocCustomer , status: StatusEnum.Active ).save( failOnError: true)
if ( !adminUser.authorities.contains(adminRole)){
SubscriberRole.create adminUser, adminRole
}
JSON.registerObjectMarshaller(Date) {
return it?.format("MM/dd/yyyy")
}
def userProfile = Profile.findByEmailAddress( 'sachin.jha.user#gmail.com') ?: new Profile(
privacyLevel: ProfilePrivacyLevelEnum.Private,
emailAddress: "sachin.jha.user#gmail.com",
phoneNumber : "9325507992",
status : 'Active'
).save( failOnError: true)
def userPerson = Person.findByProfile( userProfile) ?: new Person( firstName: 'plain' , lastName : 'user' , profile: userProfile).save( failOnError: true) ;
def plainUser = Subscriber.findByUsername('plainuser') ?: new Subscriber( username: 'plainuser', password : 'passw0rd' , enabled: true , party: userPerson, customer: vprocCustomer , status: StatusEnum.Active ).save( failOnError : true )
if ( !plainUser.authorities.contains(userRole)){
SubscriberRole.create plainUser, userRole
}
/*vprocCustomer.addToSubscribers(amdinUser)
vprocCustomer.addToSubscribers(plainUser)
vprocCustomer.save( failOnError : true);*/
}
def destroy = {
}
}

Just change in Person domain class
static belongsTo = [Organization]
to
static belongsTo = [organization:Organization]
and access organization info from person instance with person.organization

Related

Proper Criteria for Shiro plugin in Grails

I have Shiro domain classes as below:
class ShiroUser {
String email
String password
static hasMany = [ roles: ShiroRole, permissions: String ]
static constraints = {
email(nullable: false, blank: false, unique: true)
}
}
class ShiroRole {
String name
static hasMany = [ users: ShiroUser, permissions: String ]
static belongsTo = ShiroUser
static constraints = {
name(nullable: false, blank: false, unique: true)
}
}
I received ShiroUser's email from params.email. And I want to find out the permission that belongsTo ShiroUser using criteria().
I tried the below code, but couldn't succeed.
def criteria= permissions.createCriteria().listDistinct {
ShiroRole{
ShiroUser{
eq("email", params.email)
}
}
}
Your criteria is wrongly built. I'd keep it simple and put like:
def permissions = ShiroUser.findByEmail( params.email )?.roles*.permissions.flatten() as Set
If you want to stick with criteria:
def permissions = ShiroRole.createCriteria().listDistinct {
projections{
property 'permissions'
}
users{
eq "email", params.email
}
}

dynamic fnder findAllBy getting null value from join table in many to many relationship using grails

I have 3 domain as Subscriber, Role and a join table as SubscriberRole for many to many relationship. Dynamic finder findAllBy getting null value from SubscriberRole domain.
Subscriber.groovy:
class Subscriber extends PartyRole{
Date dateCreated
Date lastUpdated
List<Contact> contacts = new ArrayList<Contact>();
static belongsTo = [ customer: Customer]
static hasMany = [seats: Seat, ownedEnquiries: Enquiry,enquiresSharedWith: SharedEnquiry, enquiriesSharedBy: SharedEnquiry ,
managedTeams: Team , memberships: Membership, contacts: Contact , sharedByContacts: SharedContact, sharedWithContacts: SharedContact,
vContacts: VContact, partOf: VContact, sharedbyVContacts: SharedVcontact, sharedWithVcontacts: SharedVcontact, tokens : Token,
notifications: Notification, discussions: Discussion]
static mappedBy = [ managedTeams : "manager" , enquiresSharedWith: "sharedWith" , enquiriesSharedBy: "sharedBy" ,
sharedByContacts : "sharedBy" , sharedWithContacts : "sharedWith" ,
vContacts: "forSubscriber" , partOf :"ofContact",
sharedbyVContacts: "sharedby" , sharedWithVcontacts :"sharedWith"
]
StatusEnum status
static constraints = {
contacts nullable: true
notifications nullable : true
}
Set<Role> getAuthorities() {
SubscriberRole.findAllBySubscriber(this).collect { it.role } as Set
}
public Subscriber(){
contacts = LazyList.decorate(contacts, FactoryUtils.instantiateFactory(Contact.class))
}
}
SubscriberRole.groovy:Domain
import org.apache.commons.lang.builder.HashCodeBuilder
class SubscriberRole implements Serializable {
Subscriber subscriber
Role role
Date dateCreated
Date lastUpdated
boolean equals(other) {
if (!(other instanceof SubscriberRole)) {
return false
}
other.subscriber?.id == subscriber?.id &&
other.role?.id == role?.id
}
int hashCode() {
def builder = new HashCodeBuilder()
if (subscriber) builder.append(subscriber.id)
if (role) builder.append(role.id)
builder.toHashCode()
}
static SubscriberRole get(long subscriberId, long roleId) {
find 'from SubscriberRole where subscriber.id=:subscriberId and role.id=:roleId',
[subscriberId: subscriberId, roleId: roleId]
}
static SubscriberRole create(Subscriber subscriber, Role role, boolean flush = false) {
new SubscriberRole(subscriber: subscriber, role: role).save(flush: flush, insert: true)
}
static boolean remove(Subscriber subscriber, Role role, boolean flush = false) {
SubscriberRole instance = SubscriberRole.findBySubscriberAndRole(subscriber, role)
if (!instance) {
return false
}
instance.delete(flush: flush)
true
}
static void removeAll(Subscriber subscriber) {
executeUpdate 'DELETE FROM SubscriberRole WHERE subscriber=:subscriber', [subscriber: subscriber]
}
static void removeAll(Role role) {
executeUpdate 'DELETE FROM SubscriberRole WHERE role=:role', [role: role]
}
static mapping = {
id composite: ['role', 'subscriber']
version false
}
}
Role.groovy domain:
package com.vproc.member
import java.util.Date;
class Role {
String authority
Date dateCreated
Date lastUpdated
static mapping = {
cache true
}
static constraints = {
authority blank: false, unique: true
}
}
As you can see from image, subscriber_role has 3 entries but when I try with findAllBySubscriber, it gives me null value. Any idea,why this is happening?
Problem:. When I fetch data from SubscriberRole table using**
Subscriber subscriber = Subscriber.get(params.id)
def subscriberRole = SubscriberRole.findAllBySubscriber(subscriber)
I am getting NULL [com.vproc.member.SubscriberRole : null] though SubscriberRole table has entries in db.
Is there anything wrong with above dynamic finder.
It's showing you in that format ([com.vproc.member.SubscriberRole : null]). that null must be because you have composite key on SubscriberRole.
But you are getting proper data as needed.
For representation you could add nice toString to your SubscriberRole, like,
public String toString()
{
return "${subscriber} :: ${role}"
}

Error in Grails: Save the transient instance before flushing

I have a problem to get user authentication running in a Grails application with spring-security and LDAP.
The connection to LDAP works fine, I get results. But I didn't get it managed that the the user can log in and that the data is saved in the local database.
I have changed/created the following files:
config.groovy
grails.plugin.springsecurity.ldap. context.managerDn = 'USERNAME'
grails.plugin.springsecurity.ldap. context.managerPassword = 'PASSWORD'
grails.plugin.springsecurity.ldap. context.server ='ldap://LDAPSERVER:389/'
grails.plugin.springsecurity.ldap. authorities.ignorePartialResultException = true // typically needed for Active Directory
grails.plugin.springsecurity.ldap. search.base = 'DC=example,DC=com'
grails.plugin.springsecurity.ldap. search.filter='(sAMAccountName={0})' // for Active Directory you need this
grails.plugin.springsecurity.ldap. search.searchSubtree = true
grails.plugin.springsecurity.ldap.authorities.groupSearchBase ='DC=example,DC=com'
grails.plugin.springsecurity.ldap.authorities.groupSearchFilter = 'member={0}'
grails.plugin.springsecurity.ldap.authorities.retrieveDatabaseRoles = false
grails.plugin.springsecurity.ldap. auth.hideUserNotFoundExceptions = false
grails.plugin.springsecurity.ldap. search.attributesToReturn = ['mail', 'displayName', 'title', 'fullname'] // extra attributes you want returned; see below for custom classes that access this data
grails.plugin.springsecurity.providerNames = ['ldapAuthProvider']
grails.plugin.springsecurity.ldap.useRememberMe = false
grails.plugin.springsecurity.ldap.authorities.defaultRole = 'ROLE_USER'
grails.plugin.springsecurity.ldap.mapper.userDetailsClass = 'CustomUserDetails'
src/grovvy/CustomUserDetailsMapper.grovvy
package com.example
import com.example.CustomUserDetails
import org.springframework.ldap.core.DirContextAdapter
import org.springframework.ldap.core.DirContextOperations
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper
import groovy.sql.Sql
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.security.authentication.DisabledException
class CustomUserDetailsContextMapper implements UserDetailsContextMapper {
private static final List NO_ROLES = [new SimpleGrantedAuthority("ROLE_USER")]
def dataSource
#Override
public CustomUserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<GrantedAuthority> authority) {
username = username.toLowerCase()
User.withTransaction {
User user = User.findByUsername(username)
String firstName = ctx.originalAttrs.attrs['givenname'].values[0]
String lastName = ctx.originalAttrs.attrs['sn'].values[0]
def roles
if(!user){
user = new User(username: username, enabled: true, firstName: firstName, lastName: lastName)
user.save(flush: true)
}
else {
user = User.findByUsername(username)
user.firstName = firstName
user.lastName = lastName
user.save(flush)
}
roles = user.getAuthorities()
}
if( !user.enabled )
throw new DisabledException("User is disabled", username)
def authorities = roles.collect { new SimpleGrantedAuthority(it.authority) }
authorities.addAll(authority)
def userDetails = new CustomUserDetails(username, user.password, user.enabled, false, false, false, authorities, user.id, user.firstName, user.lastName)
return userDetails
}
#Override
public void mapUserToContext(UserDetails arg0, DirContextAdapter arg1) {
}
}
src/grovvy/CustomUserDetails.groovy
package com.example
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.userdetails.User
class CustomUserDetails extends User{
final String firstName
final String lastName
CustomUserDetails(String username, String password, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked,
Collection<GrantedAuthority> authorities,
long id, String firstName, String lastName) {
super(username, password, enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, authorities, id)
this.firstName = firstName
this.lastName = lastName
}
}
src/groovy/CustomUserDetailsService.groovy
package com.example
import grails.plugin.springsecurity.userdetails.GrailsUserDetailsService
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UsernameNotFoundException
class CustomUserDetailsService implements GrailsUserDetailsService {
/**
* Some Spring Security classes (e.g. RoleHierarchyVoter) expect at least one role, so
* we give a user with no granted roles this one which gets past that restriction but
* doesn't grant anything.
*/
static final List NO_ROLES = [new SimpleGrantedAuthority("NO_ROLE")]
UserDetails loadUserByUsername(String username, boolean loadRoles)
throws UsernameNotFoundException {
return loadUserByUsername(username)
}
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User.withTransaction { status ->
User user = User.findByUsername(username)
if (!user) throw new UsernameNotFoundException('User not found', username)
def authorities = user.authorities.collect {new SimpleGrantedAuthority(it.authority)}
return new CustomUserDetails(user.username, user.password, user.enabled,
!user.accountExpired, !user.passwordExpired,
!user.accountLocked, authorities ?: NO_ROLES, user.id,
user.firstName, user.lastName)
} as UserDetails
}
}
conf/resources.groovy
// Place your Spring DSL code here
import com.example.CustomUserDetailsContextMapper
import com.example.CustomUserDetailsService
beans = {
userDetailsService(CustomUserDetailsService)
ldapUserDetailsMapper(CustomUserDetailsContextMapper) {
dataSource = ref("dataSource")
}
}
When I run with this configuration and try to login I get the following error message:
Message: object references an unsaved transient instance - save the transient instance before flushing: com.example.User; nested exception is org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.example.User
I had the same problem. The error message states that the User instance wasn't saved. I fixed it by changing the following line in the CustomUserDetailsMapper.grovvy
user = new User(username: username, enabled: true, firstName: firstName, lastName: lastName)
to
user = new User(username: username, enabled: true, firstName: firstName, lastName: lastName, accountLocked: false, passwordExpired: false, accountExpired: false, password: "test")
and by adding a firstName and lastName to the User domain class.
As you can see I just added some default values to user which is supposed to be created. It doesn't matter that the password is always set to "test". It won't be used because you are using LDAP.
For anyone that instead modified the generated user class from spring security(after running the quickstart script) and got the same error, I have added the nullable: true in the static constraints in the domain user class to all of your custom properties - in this case firstName and lastName. This allows you to save the instance without setting all of the properties explicitly.
Hope this helps someone!
static constraints = {
username blank: false, unique: true
password blank: false
fname nullable: true
lname nullable: true
}

Grails Query with parent

If I have four domain classes like this:
class Branch {
String name
static hasMany = [users:Users]
static mappedBy = [users:'branch']
static mapping = {
id column: 'f_branch_id'
name column: 'f_name'
}
}
class Users {
String name
static hasMany = [account:Account]
static mappedBy = [account:'user']
static belongsTo= [branch:Branch, title:Title]
static mapping = {
id column: 'f_user_id',
name column: 'f_name',
branch column: 'k_branch_id'
}
}
class Account {
String username
static belongsTo = [user:Users]
static mapping = {
id column: 'f_account_id'
user column: 'f_user_id'
username column: 'f_username'
}
}
class JoinTable implements Serializable {
Account account
Role role
static mapping = {
id composite : ['role', 'account']
role column :'k_role_id'
account column :'k_account_id'
version false
}
}
How can i get branch from JoinTable using criteria query
i try this process but fail for alias problem
def criteria = JoinTable.createCriteria()
def list = criteria.list {
account {
user{
branch{
eq("id", "2")
}
}
}
}
Domains
class Branch {
String name
static hasMany = [users:Users]
static mapping = {
id column: 'f_branch_id'
name column: 'f_name'
}
}
class Title {
...
}
class Users {
String name
static hasMany = [account:Account]
static belongsTo= [branch:Branch, title:Title]
static mapping = {...}
}
class Account {
String username
static belongsTo = [user:Users]
static mapping = {...}
}
class Role {
...
}
class JoinTable implements Serializable {
Account account
Role role
static mapping = {
id composite : ['role', 'account']
role column :'k_role_id'
account column :'k_account_id'
version false
}
}
Test
#TestMixin(GrailsUnitTestMixin)
#Mock([Act, Branch, Title, Users, Account, Role, JoinTable])
class EaseTests {
void testCriteria(){
10.times{
def b = new Branch().save(validate:false, flush:true)
10.times{
def u = new Users(branch:b).save(validate:false, flush:true)
10.times{
def a = new Account(user:u).save(validate:false, flush:true)
def joinTableRow = new JoinTable(account: a).save(validate:false, flush:true)
}
}
}
def c = JoinTable.createCriteria()
def results = c{
account{
user {
branch{
idEq(2l)
}
}
}
}
assert results
}
}

how to get contacts created by currently logged in user in grails

I have implemented spring security service for user authentication in my grails application.
I have Subscriber.groovy(user table) and Contact.groovy domains. Once a subscriber(user) logs in, he/she can create contacts.There is hasMany relationship between Subscriber and Contact domain.
Problem: I have implemented search functionality for contacts created by currently logged user or subscriber on contact page. It works fine but it fetch all contacts in system but I want only contacts those are created by currently logged in subscriber(user).
How to search contacts those are created by currently logged in subscriber.
Method for searching contacts from contact table
def searchAJAX = {
def contacts = Contact.findAllByNameLike("%${params.query}%")
//Create XML response
render(contentType: "text/xml") {
results() {
contacts.each { contact ->
result(){
name(contact.name)
//Optional id which will be available in onItemSelect
id(contact.id)
}
}
}
}
}
ContactController.groovy
package com.vproc.member
import grails.converters.*
class ContactController {
def springSecurityService
def subscriberService
def imageUploadService
def searchableService
def autoCompleteService
static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
def index() {
redirect(action: "list", params: params)
}
def list() {
Subscriber loggedinSubscriber = Subscriber.get( springSecurityService.principal.id )
List<Contact>contactsList = new ArrayList<Contact>();
loggedinSubscriber?.contacts.each { it ->
contactsList.add(it)
}
[contactInstanceList:contactsList , contactInstanceTotal: contactsList.size() ]
}
def create() {
[contactInstance: new Contact(params)]
}
def save() {
// params.birthday = Date.parse( 'MM/dd/yyyy', params.birthday )
if (params.birthday){
params.birthday = (new SimpleDateFormat("MM/dd/yyyy")).parse(params.birthday)
}
def contactInstance = new Contact(params)
Subscriber loggedinSubscriber = Subscriber.get( springSecurityService.principal.id )
if (loggedinSubscriber == null)
System.out.println("not able to save")
else {
if (!loggedinSubscriber.contacts){
loggedinSubscriber.contacts = new ArrayList<Contact>();
}
loggedinSubscriber.contacts.add(contactInstance)
if (!loggedinSubscriber.save(flush: true)) {
flash.message = message(code: 'default.created.message', args: [message(code: 'contact.label', default: 'Contact'), contactInstance.id])
render(view: "create", model: [contactInstance: contactInstance])
return
}
}
flash.message = message(code: 'default.created.message', args: [message(code: 'contact.label', default: 'Contact'), contactInstance.id])
redirect(action: "list")
}
// enable search for contacts
def contact_search = {
def query = params.q
if(query){
def srchResults = searchableService.search(query)
render(view: "list",
model: [contactInstanceList: srchResults.results,
contactInstanceTotal:srchResults.total])
}
else{
render "not record found";
}
}
// fetch name from contact table for autocomplete on contact
def searchAJAX = {
def contacts = Contact.findAllByNameLike("%${params.query}%")
//Create XML response
render(contentType: "text/xml") {
results() {
contacts.each { contact ->
result(){
name(contact.name)
//Optional id which will be available in onItemSelect
id(contact.id)
}
}
}
}
}
}
Contact.groovy
package com.vproc.member
import java.util.Date;
import com.vproc.common.Tag;
import com.vproc.enquiry.ContactType;
import grails.converters.JSON;
class Contact {
String name
String phoneNumber
String emailAddress
Gender gender
String url
String note
byte[] image
String address
Date dateCreated
Date lastUpdated
ContactType contactType
Date birthday
static belongsTo = [Subscriber]
static hasMany = [tags:Tag , shares: SharedContact]
static constraints = {
image nullable: true
phoneNumber nullable: true
url nullable :true
address nullable :true
gender nullable :true
note nullable :true
contactType nullable :true
birthday nullable :true
}
static mapping = {
note(type: 'text')
}
//static searchable = [only: ['name', 'emailAddress']]
static searchable = true
static scaffold = true
//static searchable = true
}
Subscriber.groovy
package com.vproc.member
import java.util.Date;
import com.vproc.common.StatusEnum;
import com.vproc.enquiry.Discussion;
import com.vproc.enquiry.Enquiry;
import com.vproc.enquiry.Membership;
import com.vproc.enquiry.Notification;
import com.vproc.enquiry.SharedEnquiry;
import com.vproc.enquiry.Team;
import com.vproc.order.Seat;
class Subscriber extends PartyRole{
transient springSecurityService
String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
StatusEnum status
Date dateCreated
Date lastUpdated
List<Contact> contacts ;
static belongsTo = [ customer: Customer]
static hasMany = [seats: Seat, ownedEnquiries: Enquiry,enquiresSharedWith: SharedEnquiry, enquiriesSharedBy: SharedEnquiry ,
managedTeams: Team , memberships: Membership, contacts: Contact , sharedByContacts: SharedContact, sharedWithContacts: SharedContact,
vContacts: VContact, partOf: VContact, sharedbyVContacts: SharedVcontact, sharedWithVcontacts: SharedVcontact,
notifications: Notification, discussions: Discussion]
static mappedBy = [ managedTeams : "manager" , enquiresSharedWith: "sharedWith" , enquiriesSharedBy: "sharedBy" ,
sharedByContacts : "sharedBy" , sharedWithContacts : "sharedWith" ,
vContacts: "forSubscriber" , partOf :"ofContact",
sharedbyVContacts: "sharedby" , sharedWithVcontacts :"sharedWith"
]
static constraints = {
username validator : { val , obj ->
if (obj.status != StatusEnum.Pending)
val!= null
}
username unique: true
password validator : { val , obj ->
if (obj.status != StatusEnum.Pending)
val != null
}
contacts nullable: true
notifications nullable : true
username nullable: true
password nullable: true
}
static mapping = {
password column: '`password`'
}
Set<Role> getAuthorities() {
SubscriberRole.findAllBySubscriber(this).collect { it.role } as Set
}
def beforeInsert() {
encodePassword()
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}
protected void encodePassword() {
password = springSecurityService.encodePassword(password)
}
}
save action for Contact controller
def save() {
// params.birthday = Date.parse( 'MM/dd/yyyy', params.birthday )
if (params.birthday){
params.birthday = (new SimpleDateFormat("MM/dd/yyyy")).parse(params.birthday)
}
def contactInstance = new Contact(params)
Subscriber loggedinSubscriber = Subscriber.get( springSecurityService.principal.id )
if (loggedinSubscriber == null)
System.out.println("not able to save")
else {
if (!loggedinSubscriber.contacts){
loggedinSubscriber.contacts = new ArrayList<Contact>();
}
loggedinSubscriber.contacts.add(contactInstance)
if (!loggedinSubscriber.save(flush: true)) {
flash.message = message(code: 'default.created.message', args: [message(code: 'contact.label', default: 'Contact'), contactInstance.id])
render(view: "create", model: [contactInstance: contactInstance])
return
}
}
flash.message = message(code: 'default.created.message', args: [message(code: 'contact.label', default: 'Contact'), contactInstance.id])
redirect(action: "list")
}
Note: while saving contacts,I have logged in subscriber in save action of Contact controller but I do not know how to use it below method which is searchAjax for searching contacts.
Assuming Subscriber has an association to Contact as,
class Subscriber {
static hasMany = [contacts: Contact]
}
then, to get all contacts for a subscriber user,
subscriberInstance.contacts
and to query among contacts of the same subscriber use,
subscriberInstance.findByContact('your_query_string')
For reference look up querying associations on the documentation http://grails.org/doc/latest/guide/GORM.html#querying

Resources