How to access a Date Variable from Service class in Controller - grails

I have the following model class
public class User{
String firstName
String lastName
Date startDate
Date endDate
static constraint(){
firstname(nullable:true)
lastname(nullable:true)
startDate
endDate
}
}
My Service class
public class UserService {
public void addUser(String firstName, String lastName, Date startDate, Date endDate){
User user = new User()
user.firstName=firstName
user.lastName=lastName
user.startDate=startDate
user.endDate=endDate
}
}
Now my Question is how can i access my Date variables in my controller
My controller class
public class UserController {
def applyService
def register = applyService.addUser(params.firstName.toString(), params.lastName.toString()
now I don't know how to access my startDate and endDate variable .... i can't access them using params because they are not string...any solution. am new to grails

You are leaving aside one of the most powerful features of Grails: Data Binding
I would do something like:
class UserController {
def userService
def save = {
def user = new User(params)
userService.addUser(user)
}
}
When instantiating a Domain Object with the param maps on a Controller, Grails will figure it out for you what is the proper type of the User's fields and will set them accordingly. On your service you can simply persist the instance.
I would recommend you to have a look to Command Objects as well.

If i were you I will change as follow.
def register = applyService.addUser(params.firstName.toString(),params.lastName.toString()
,parseDate(params['startDate'] ,
parseDate(parmas['endDate']))
And assuming you are using grails version > 2.3 change as follow
A setting in Config.groovy
grails.databinding.dateFormats = [
'MMddyyyy', 'yyyy-MM-dd HH:mm:ss.S', "yyyy-MM-dd'T'hh:mm:ss'Z'"]
import org.grails.databinding.BindingFormat
public class User{
String firstName
String lastName
#BindingFormat('yyyy-MM-dd HH:mm:ss.S') // or any format you like
Date startDate
#BindingFormat('yyyy-MM-dd HH:mm:ss.S')
Date endDate
static constraint(){
firstname(nullable:true)
lastname(nullable:true)
startDate
endDate
}
}
Cheers!

Related

Angular http get wrong datatype of Date property

I use Angular 7 and Net Core Web API.
In web API I have an employee class with birthday property :
public DateTime Birthday { get; set; }
And in Angular:
export class Employee {
public birthday : Date;
...
}
When I call this code:
this.http.get<Employee>(url).subscribe(employee => {
console.log(employee.birthday)
console.log(employee.birthday.constructor.name)
});
The result is:
1995-07-22T00:00:00
String
The property is Date, why it constructor name is String?
How can i get correct datatype?
Thank you.
I think you have to create Employee object in from response like this:
this.http.get<Employee>(url).subscribe(employee => {
const emp = new Employee(employee.birthday);
});
Also have to write constructor for Employee class.

Getting Parent Name null in child class audit log in Grail

I have Parent and Child class which has one to many mapping and I want to log Save action on both classes but at the time of saving log parent object is null in child class but it works fine for Parent class log
Here is my AuditLog, Parent and Child class
class AuditLog{
String objectNameType = null;
def onSave = { newMap ->
String objectName = newMap[objectNameType]; // here I am getting null for child class save
//code for storing logs
}
}
class Parent extends AuditLog{
String name;
List child = new ArrayList()
static hasMany = [ child:Child ]
String objectNameType = name;
public String toString(){
return name;
}
}
class child extends AuditLog{
String childName;
static belongsTo =[ parent : Parent];
String objectNameType = parent;
public String toString(){
return childName;
}
}
I am using Grails 1.3.7 version and audit-logging 0.5.5
Any lead will be appreciated.
Thanks in advance
In Controller when I tried to access child.parent I am getting it as null. So I set it manually by iterating over child and it resolves my issue.

Grails Class with hasMany

I have this domain class that has a one-to-many relationship as with dynamic scaffolding show below:
Domain:
package mienapp
class Announcements {
String user
String title
String comments
Date dateCreated
static hasMany = [tag: Tags]
static mapping = {
comments sqlType: 'text'
}
static constraints = {
}
}
Controller:
package mienapp
class AnnouncementsController {
def scaffold = true
def index() {
redirect(action: list)
}
}
When controller redirects to list, the table shows all fields defined in announcements class. How can I show the value of field from tags in the table as well?
Assuming your list method returns a model with an Announcements instance as
def list() {
..
[announcementsInstance: announcementsInstance, ...]
}
in your view, you can access tags like so
<g:each in="${announcementsInstance.tag}" var="tag">
${tag.someproperty}
</g:each>

how to get parents id while fetching child's information - Grails?

How to access firstname and lastname of user depending on which statusItem is displayed which is the child of the user.
class UserAccount implements Serializable {
static transients = ['pass','passConfirm','familyPicTmp', 'familyPicTmpFilename', 'photoTmp', 'photoTmpFilename']
static hasMany = [authorities: Authorisation, memberships:FamilyMembership, progenitorIwi:Family, politicItems:PoliticItem,
relationships:Relationship, , agents:UserAccount, media:UserMedia, status:Status]
static mappedBy = [ progenitorIwi:"progenitor",relationships:'relationTo', relationships:'userAccount']
static fetchMode = [memberships:FetchMode.JOIN, agents:FetchMode.JOIN]
static mapping = {
memberships(lazy:false)
agents(lazy:false)
}
static belongsTo = [Authorisation]
STATUS DOMAIN
class Status {
static belongsTo = [userAccount:UserAccount]
def String statusMessage
Date dateCreated
Date lastUpdated
def String statusType
POLITIC DOMAIN
class PoliticItem {
SystemEntity politicItemName
UserAccount userAccount
def String politicItemValue
def boolean shared = false
Date dateCreated
Date lastUpdated
How can we load all the users that belong to all the status on to the politic's views?
I am still not sure which part you dont know. Assuming userAccount has the firstName and lastName field to access them from status try this:
status is the instance of your Status class. The one you need to get the userAccount off of it.
status.userAccount.firstName
or
status.userAccount.lastName

Grails many to many relationship migration

Hello I have two domain classes as following
class Users {
String password
String firstName
String lastName
String emailAddress
String username
Company company
.....
static hasMany = [projects:Projects];
}
Another class
class Projects {
String projectName
String description
Users projectLead
Date dateCreated
Date lastUpdated
static belongsTo = Users
}
These classes obviously has one to many relationship but now I want to change it to many to many relationship by adding "ProjectMembership" class but the problem I have is that my application has already gone into production and there are people who are already using the app. In such a case they already have one user->many projects in the the db. In such a case how can I migrate this existing data and change my prod app to have m2m relationship which will looks like following.
class Users {
String password
String firstName
String lastName
String emailAddress
String username
Company company
.....
static hasMany = [projectMemberships:ProjectMemberships];
}
Another class
class Projects {
String projectName
String description
Users projectLead
Date dateCreated
Date lastUpdated
static hasMany = [projectMemberships:ProjectMemberships];
}
and
class ProjectMemberships{
Users u
Projects p
}
This is best done with a migration tool like Liquibase, and the http://grails.org/plugin/database-migration plugin is probably your best be in Grails since it uses Liquibase and is tightly integrated with GORM. But this one's easy enough to do by hand.
I wouldn't use hasMany since you can easily manage everything from the ProjectMemberships class, so your Users and Projects classes would be
class Users {
String password
String firstName
String lastName
String emailAddress
String username
Company company
.....
}
and
class Projects {
String projectName
String description
Date dateCreated
Date lastUpdated
}
I'd go with a ProjectMemberships class that uses a composite key, which requires that it implement Serializable and have a good hashCode and equals:
import org.apache.commons.lang.builder.HashCodeBuilder
class ProjectMemberships implements Serializable {
Users u
Projects p
boolean equals(other) {
if (!(other instanceof ProjectMemberships)) {
return false
}
other.u?.id == u?.id && other.p?.id == p?.id
}
int hashCode() {
def builder = new HashCodeBuilder()
if (u) builder.append(u.id)
if (p) builder.append(p.id)
builder.toHashCode()
}
static ProjectMemberships get(long userId, long projectId) {
find 'from ProjectMemberships where u.id=:userId and p.id=:projectId',
[userId: userId, projectId: projectId]
}
static ProjectMemberships create(Users u, Projects p, boolean flush = false) {
new ProjectMemberships(u: u, p: p).save(flush: flush, insert: true)
}
static boolean remove(Users u, Projects p, boolean flush = false) {
ProjectMemberships instance = ProjectMemberships.findByUsersAndProjects(u, p)
if (!instance) {
return false
}
instance.delete(flush: flush)
true
}
static void removeAll(Users u) {
executeUpdate 'DELETE FROM ProjectMemberships WHERE u=:u', [u: u]
}
static void removeAll(Projects p) {
executeUpdate 'DELETE FROM ProjectMemberships WHERE p=:p', [p: p]
}
static mapping = {
id composite: ['p', 'u']
version false
}
}
Use ProjectMemberships.create() to add a relationship between a user and a project, and ProjectMemberships.remove() to remove it.
Run grails schema-export to see the updated DDL (it'll be in target/ddl.sql). Run the create table statement for the project_memberships table, e.g.
create table project_memberships (
p_id bigint not null,
u_id bigint not null,
primary key (p_id, u_id)
)
Then populate it with this SQL (depending on your database you might need a slightly different syntax):
insert into project_memberships(p_id, u_id) select id, project_lead_id from projects
and finally drop the project_lead_id column from the projects table.
Of course do a database backup before making any changes.
You can get a user's projects with
def projects = ProjectMemberships.findAllByUsers(user)*.p
and similarly a project's users with
def users = ProjectMemberships.findAllByProjects(project)*.u

Resources