I'm new to Grails. I have a field in my domain object which I define as an String.
String ponum
When i click first time on create page ,the "ponum" field has to display 0001 and later it has to save in database.And When i click on second time the "ponum" field has to display 0002 and later it has to save in database.Everytime i click on create page "ponum" field has to autoincrement and save it database.I google ,but i did not get any document.
thanks
As things get an id anyway (assuming your using a regular rdbms with standard id genaerator), why not just pretend there's a variable ponum which is based on the id?
Just add a getter to your domain class:
class Page {
String getPonum() {
String.format( "%04d", id )
}
}
According to this answer, it is not possible to use hibernate generators (those used for ids) to do that. If you really need to use Hibernate generators, a workaround is described in the answer as well.
In your case, you could use an interceptor to generator your ponum property when inserting a new object:
class Yours {
int ponum
def beforeInsert() {
def lastPonum = Book.list([sort: 'ponum', order:'desc', max: 1])
if(lastPonum)
ponum = (lastPonum.pop().ponum as int) + 1 as String
else
ponum = '0'
}
}
Related
I want to restrict the account lookup (domain) based on the value entered in GL Prefix (I'll actually use some wildcards and some other logic which I'm comfortable adding later), the problem is that I'm getting a logical True or False value returned by self.x_poLineGLprefix rather than the value in the field. How do I get the actual data value of x_poLineGLprefix?
class QuickPOLine(models.Model):
_name = 'purchase.order.line'
_inherit = 'purchase.order.line'
x_poLineGLprefix = fields.Char(string='GL Prefix')
x_poLineGLaccount = fields.Many2one(
'account.account', string="Line Item Expense Account",
domain=lambda self: [('code', '=', self.x_poLineGLprefix)])
Try this
#api.onchange('x_poLineGLprefix')
def onchange_x_poLineGLprefix(self):
if self.x_poLineGLprefix:
return {'domain': {
'x_poLineGLaccount': [('code', '=', self.x_poLineGLprefix)]
}}
You can add dynamic domain to achieve this based on any field. In #api.onchange() function you can return domain for many2one. To add dynamic domain you can refer this link. If you are using both many2one fields refer this link.
I want to get custom S.O. Invoice Template fields using QuickBooks QBFC.
Here's how to read custom fields from a sales order:
Add "0" to the OwnerIDList of the SalesOrderQuery.
Read custom header fields from the DataExtRetList that is attached to SalesOrderRet objects that are returned from the query.
Read custom line item fields from the DataExtRetList in the SalesOrderLineRet and SalesOrderLineGrouptRet objects that are included in each SalesOrderRet (if you're reading line items).
If you're already using the IncludeRetElementList, you must add DataExtRet to the list; if you're not then don't start using IncludeRetElementList until you have custom fields working. Just like any transaction query, you won't see any line item data unless you set the IncludeLineItems flag in the request.
Custom fields are well documented in the QuickBooks SDK Manual. I'd recommend you take a look at the section DataExt: Using Custom Fields and Private Data in the QBSDK Programmers Guide.
To elaborate on Paul Keister's answer, the reason you must add "0" to the query is because that is the Owner ID of the custom field you are attempting to retrieve. 0 is probably likely to be the value, but if the owner ID is different, you will have to use a different value here.
Some example C# code:
//set the owner id of the custom field you are trying to get back
IInvoiceQuery invoiceQuery = requestMsgSet.AppendInvoiceQueryRq();
invoiceQuery.OwnerIDList.Add("0");
//set up query parameters and actually call your query...
//call this method for each invoice to get its custom fields (if they exist)
static void GetInvoiceCustomFields(IInvoiceRet invoice)
{
if (invoice.DataExtRetList == null)
{
return;
}
for (int i = 0; i < invoice.DataExtRetList.Count; i++)
{
IDataExtRet extData = invoice.DataExtRetList.GetAt(i);
Console.WriteLine("external data name: " + extData.DataExtName.GetValue());
Console.WriteLine("external data value: " + extData.DataExtValue.GetValue());
}
}
I have created a domain with a Double field. When the validation occurs it throws the error message with size value showing the number with commas. Following are the detials
Groovy Class
class Quote {
String content;
Double size;
static constraints = {
content(maxSize:1000, blank:false)
size(min: 0.00D, max:999.99D)
}
}
Value entered "11111", error obtained "Size 11,111 is exceeded the limit". I have added the property key/value pair in messages.properties.
Here, I would like to get the message back without the commas. My main aim is to take the key and format the message returned based on my requirements. I require this as I have other fields that need conversion. For example, a date is validated but when showing the error the Gregorian date needs to be converted to an Islamic date and shown to user.
Does anyone know if I can do something to make this work.
I have tried the solution provided in http://ishanf.tumblr.com/post/434379583/custom-property-editor-for-grails but this did not work.
I have also tried modifying the messages values, but this is not flexible in case of my date issue. Example, for a key value pair, instead of using {2} as a place holder I could use {2, date, mm/dd/yyyy}, but for Islamic dates I want to format and show things differently.
Also, please note I have created a separate key for default date formatting for my application.
Would appreciate the help.
In grails, the return of a constrain is an already translated string.
You can create a taglib to format that, or enhance the
Another option would be custom validators. A custom validator can return false or a key when failing.
For example in your domain class, to vaildate a field:
myDateField validator: {val, obj -> obj.myShinyDateValidatorMethod(val) }
private myShinyDateValidatorMethod() {
if (isNotValidDate(val) {
return [the_message_key, val.formatedAsYouWand]
}
}
and, in your properties file you have to have defined the key:
the_message_key=This date: {3} is not valid
The trick here is that in the return from the validator, first string is the key and the rest are parameters for that key, but grails already uses {0}, {1}, {2} placeholders for className, fieldName and value, and the first parameter that you pass will be used as {3} placeholder.
Hope this helps
Why do I need this:
I am working in a project which allows user to choose date in Nepali Bikram Sambat Date format (which is incompatible with Java and SQL's "DATE"). I did it by modifying org.codehaus.groovy.grails.plugins.web.taglib.FormTagLib class's datePicker tagLibrary. And modifying the scaffolding template list.gsp.
My problem :
When user chooses Nepali date from browser and submits the form, I want to read the [day, month, year] and convert it into Java Date object and save into database. (The date will be converted back to Nepali Bikram Sambat when it will be displayed into view).
I tried to print the params in the controller but all the params are already mapped/wrapped into corresponding objects - along with my Nepali Date. So I get sysout of Java's Date from code below :
println params.date
I am wondering how can I intercept the form submit request and modify the date params into English date. I see one solution - using JavaScript ( and rewrite my conversion code into JavaScript) before form submit to convert the params. And just wanted to confirm is there a easy way - like interceptor/filter etc.
Well, assuming you are using input fields with the standard grails datepicker, you should have in your params map the fields being passed, just with a different name. Write a "println params" in your action receiving the request and look for the names of the fields of the datepicker. It was supposed to bring you something like (name of the datepicker field, say * + _year, for year, * + _month for month and so on).
You can create a CustomEditorRegistrar that changes the format from your date before it's wrapped into objects. Like this:
public class CustomDateEditorRegister implements PropertyEditorRegistrar {
public void registerCustomEditors(PropertyEditorRegistry registry) {
String dateFormat = 'dd/MM/yyyy'
registry.registerCustomEditor(Date, new CustomDateEditor(new SimpleDateFormat(dateFormat), true))
}
}
And your Date editor could be something like:
class CustomSimpleDateEditor extends CustomDateEditor {
public CustomSimpleDateEditor(SimpleDateFormat formatter, boolean allowEmpty) {
super(formatter, allowEmpty);
}
public String getAsText() {
Date date = (Date)getValue();
try {
String dateText = new SimpleDateFormat("dd/MM/yyyy").parse(date);
return dateText;
}
catch(Exception e) {
e.printStackTrace();
return "";
}
}
}
Your params.date will be converted before it's passed to objects and saved to the db. Anyway, here's a good link explaining it.
Hope it helps!
I have integer type field in database which is having property "Not Null".
when i create a view & do a validation, if i left that field blank, it will consider it as 0 so i can not compare it with 0 because if someone insert a value 0 then it will be considered as error!
one another problem is that i am using Model error as described in the book "ASP.NET MVC 1.0" # Scott Gu blog. And I am checking the value in partial class of object (created by LINQ-To-SQL). i.e
public partial class Person
{
public bool IsValid
{
get { return (GetRuleViolations().Count() == 0); }
}
public IEnumerable<RuleViolation> GetRuleViolations()
{
if (String.IsNullOrEmpty(Name))
yield return new RuleViolation("Name is Required", "Name");
if (Age == 0)
yield return new RuleViolation("Age is Required", "Age");
yield break;
}
partial void OnValidate(ChangeAction action)
{
if (!IsValid)
throw new ApplicationException("Rule violations prevent saving");
}
}
There is also problem with range.
Like in database if i declared as smallint i.e. short in c#, now if i exceed that range then it gives error as "A Value is reguired".
so finally is there any best way for validation in ASP.NET MVC?
you can change your code with a nullable type?
Dim i As Nullable(Of Integer)
MsgBox(i.HasValue)
'result is false
i = 1
MsgBox(i.HasValue)
'result is true
i = Nothing
MsgBox(i.HasValue)
'result is false
I'm not realy up to speed with the details of MVC, but isn't there a way to change the default value of age to -1? This way you have a value to check on and people can still enter 0.
Another solution could be to use a nullable int. You can do this by appending a ? to the type.
HTH.
Jonathan
I would validate the form on the client first. If the age is 0 then let the user know that it's not a valid age. On the server change the message, it's misleading:
if (Age == 0)
yield return new RuleViolation("0 years is not a valid age", "Age");
I know that because you bind to a model property from your Person entity it gets 0 as the default value - why don't you change that in the database then? Set a default in the database to a value that you consider reasonable for the user age, so that it no longer displays as 0 for new entities.
If you don't want to change the db values, use jQuery to set the textbox values to empty strings on your Create page when it loads. If the user tries to submit such a form you can check on the client to disallow it and on the server you don't have to do anything, the user will get a "A value is required" message back.
By the way, you wrote:
i can not compare it with 0 because if
someone insert a value 0 then it will
be considered as error
I don't see a problem in this particular domain model. Do you think that age of 0 is a good value or not? Ask yourself.
check it with Utilities.GetNullableInt32(textbox1.Text.Trim());
if u check with this GetNullableInt32() function if the user entered value '0' it will saved as NUll in your table