Need advice with two properties constraints - grails

I need your help in this scenario.
I have the following domain class:
class Payment {
BigDecimal cash
BigDecimal checkValue
static constraints = {
cash nullable: true
checkValue nullable: true
}
}
The cash and checkValue properties are nullable, but at least one of them has to have a value.
I hope I was able to explain my problem.
Thanks for your time!

Custom validator seems to be a good option in this case. Try with:
class Payment {
BigDecimal cash
BigDecimal checkValue
static constraints = {
cash nullable: true, validator: { val, obj ->
val != null || obj.checkValue != null
}
checkValue nullable: true, validator: { val, obj ->
val != null || obj.cash != null
}
}
}
With groovy truth you can simplify the validator closures to something like below:
static constraints = {
cash nullable: true, validator: { val, obj -> val || obj.checkValue }
checkValue nullable: true, validator: { val, obj -> val || obj.cash }
}
For more information take a look at Validation section of grails documentation.

Related

Grails many to many relationship error

I get a problem due to my poor knowledge on GORM and modeling domain object in Grails.
Here is my issue :
| Error Error loading plugin manager:
No owner defined between domain classes [class com.myproject.model.Project] and
[class com.crowdfun.Sector] in a many-to-many relationship.
Example: static belongsTo = com.myproject.model.Sector
(Use --stacktrace to see the full trace)
I can't say what is wrong, because I follow the tutorial of official grails documentations : http://grails.org/doc/latest/guide/GORM.html#manyToMany
My classes :
Project.groovy :
class Project {
String name
Integer nbInvestors
Region region
Integer nbDays
Boolean success
String equity
String currency
Double target
Double raisedAmount
String url
Double valuation
boolean extended = false
static belongsTo = [
site: Site,
sector: Sector
]
static hasMany = [
sectors: Sector
]
static hasOne = [
valuationRange: ValuationRange,
targetRange: TargetRange
]
static constraints = {
name nullable: true
nbInvestors nullable: true
region nullable: true
nbDays nullable: true
success nullable: true
equity nullable: true
currency nullable: true
target nullable: true
raisedAmount nullable: true
url nullable: true, unique: true
valuation nullable: true
}
}
Sector.groovy :
class Sector {
String name
static hasMany = [
projects: Project
]
static constraints = {
name unique: true
}
#Override
public String toString() {
return name
}
def getNbProjects() {
projects.size()
}
}
Site.groovy
class Site {
String name
static hasMany = [
projects: Project
]
static constraints = {
name unique: true
}
#Override
public String toString() {
return name
}
}
Change the class like so:
class Project {
...
Site site
Sector sector
static belongsTo = [Site, Sector]
}

Override getter and setter in grails domain class for relation

How to override getter and setter for field being a relation one-to-many in grails domain class? I know how to override getters and setters for fields being an single Object, but I have problem with Collections. Here is my case:
I have Entity domain class, which has many titles. Now I would like to override getter for titles to get only titles with flag isActive equals true. I've tried something like that but it's not working:
class Entity {
static hasMany = [
titles: Title
]
public Set<Title> getTitles() {
if(titles == null)
return null
return titles.findAll { r -> r.isActive == true }
}
public void setTitles(Set<Title> s) {
titles = s
}
}
class Title {
Boolean isActive
static belongsTo = [entity:Entity]
static mapping = {
isActive column: 'is_active'
isActive type: 'yes_no'
}
}
Thank You for your help.
Need the reference Set<Title> titles.
class Entity {
Set<Title> titles
static hasMany = [
titles: Title
]
public Set<Title> getTitles() {
if(titles == null)
return null;
return titles.findAll { r -> r.isActive == true }
}
public void setTitles(Set<Title> s) {
titles = s
}
}

multiple domain class with belongsTo relationship

I have 3 classes as per below...
Class A
{
E objE;
}
Class B
{
E objE;
}
Class E
{
E objE;
belongsTo:[
a : A,
b : B
]
static constraints = {
a nullable: true
b nullable: true
c nullable: true
}
}
When I am trying to save object of A class it through exception for null.
Try to remove the hasOne on Class Incidents, Problems, Requests and replace it with
E eObj
static constraints = {eObj: unique: true, nullable:true}
static mapping = {
eObj cascade: "delete"
}

How to work on knockout validation localization

I have a view page where i'm validating fields using knockout.js . I want to validate my fields in different country's language like spanish,french etc i.e using localization.
I have added el-GR.js ,fr-FR.js , ru-RU.js etc files into my js folder and referenced them.
Now how can i validate or check into my modalModal.js page?
modalModal.js
ko.validation.rules.pattern.message = 'Invalid.';
ko.validation.configure({
registerExtenders : true,
messagesOnModified : true,
insertMessages : true,
parseInputAttributes : true,
messageTemplate : null
});
var mustEqual = function (val, other) {
return val == other();
};
var modalViewModel= {
firstName : ko.observable().extend({
minLength : 2,
maxLength : 40
}),
lastName : ko.observable().extend({
minLength : 2,
maxLength : 10
}),
organisation : ko.observable().extend({
minLength : 2,
maxLength : 40
}),
email : ko.observable().extend({ // custom message
email: true
}),
password: ko.observable()
};
modalViewModel.confirmPassword = ko.observable().extend({
validation: { validator: mustEqual, message: 'Passwords do not match.', params:
modalViewModel.password }
});
modalViewModel.errors = ko.validation.group(modalViewModel);
// Activates knockout.js
ko.applyBindings(modalViewModel,document.getElementById('light'));
I've done this for my latest KO project
I override the KO validation rules and use the Globalize plugin, like
ko.validation.rules.number.validator = function (value, validate) {
return !String.hasValue(value) || (validate && !isNaN(Globalize.parseFloat(value)));
};
ko.validation.rules.date.validator = function (value, validate) {
return !String.hasValue(value) || (validate && Globalize.parseDate(value) != null);
};
edit: btw, there is a bug in the Globalize plugin, it will accept dot (.) as part of a number even if it isn't, i fixed that like this
Globalize.orgParaseFloat = Globalize.parseFloat;
Globalize.parseFloat = function (value) {
value = String(value);
var culture = this.findClosestCulture();
var seperatorFound = false;
for (var i in culture.numberFormat) {
if (culture.numberFormat[i] == ".") {
seperatorFound = true;
break;
}
}
if (!seperatorFound) {
value = value.replace(".", "NaN");
}
return this.orgParaseFloat(value);
};

Validator with grails : Failed to create the user

I have this:
class Usuario {
String username
String password
String passwordDos
String nombre
String apellidoPaterno
String apellidoMaterno
Date fechaDeNacimiento
String sexo
String correo
static constraints = {
username blank: false, unique: true, validator: { val, obj ->
obj.password != val
return ['usuario.userPassError']
}
password blank: false, validator: { val, obj ->
obj.passwordDos == val
return ['usuario.passDiferentes']
}
passwordDos blank: false
nombre blank: false, maxSize: 64
apellidoPaterno blank: false, maxSize: 64
apellidoMaterno blank: true, maxSize: 64
sexo inList: ["Femenino", "Masculino"]
correo blank: false, maxSize: 128, email:true
}
}
I want to return in the error message, but I'm not doing wrong, I could explain alguein please?
I'd expect there to be some sort of conditional return in the validator closures. As it stands, it looks like they'll always fail, returning the error code.
Try writing your custom validators like:
// username validator
validator: { val, obj ->
obj.password == val ? 'userPassError' : true
}
// password validator
validator: { val, obj ->
obj.passwordDos != val ? 'passDiferentes' : true
}
Note the different message codes that are being returned, too.
Then, make sure you have the following in your appropriate grails-app/i18n/messages* file(s):
usuario.username.userPassError = Username and password cannot be the same
usuario.password.passDiferentes = Password does not match password confirmation

Resources