This question comes from the problem of another question of mine. In that question, I come across a situation that hasErrors() function doesn't work for non-persistent domain class, even after all the things I did following the instruction, part 7.5 .
Following Victor's way, I fixed the problem by calling validate(), but I don't understand why it works. The Grails documents seem to say nothing about you should call a validate() before hasErrors() function. How could this happen?
It does make sense to me that validate would need to be called before asking an object whether it hasErrors (or save for proper domain objects, which calls validate under the covers). Validate in this context means "check whether this object is valid and indicate any errors if not".
Alternatively the GORM implementation would have to call validate every time any change is made to an object, which to me would be less desirable behaviour, as it might involve lots of work being done often and unnecessarily (some of those constraints could involve a lot of work).
The beginning of section 7.2 states pretty clearly "To validate a domain class you can call the validate method on any instance". It also states that "within Grails there are essentially 2 phases of validation, the first phase is data binding which occurs when you bind request parameters onto an instance such as... At this point you may already have errors in the errors property due to type conversion (such as converting Strings to Dates). You can check these and obtain the original input value using the Errors API. ... The second phase of validation happens when you call validate or save. This is when Grails will validate the bound values againts the constraints you defined."
The documentation for hasErrors also mentions this. You can access this by finding the method call in the navigation frame on the left, when you are on the documentation site. I would always recommend looking on these as well as the more descriptive user guide pages, as they often give a little more detail.
Here's the page for the validate method too.
I've never had a problem calling validate directly - it's very clear to me and I can choose the point where all the work is done and I'm ready for the validation to take place. I can't see an option to change this behaviour anywhere, but if you wanted validate to be called automatically or under certain conditions, you could perhaps use some Groovy meta programming magic by maybe adding invokeMethod to the class and have it call validate before passing certain calls on. Have a look here and here.
(Not sure I would recommend that though! And bear in mind your class would now be dependent on being used within the GORM validation framework, as that validate method might not otherwise exist).
Related
I am new to groovy grails so any help would be appreciated.
I am working on a grails application which tracks employee workplace history. One of the validation requirements is that the start date and end date duration for an employee should not overlap. That means the startDate..endDate range should be unique among his employment dates for every employee.
So my question is that how should I handle this validation ? Should it be done in the static constraint block as a custom validator or it should be done in database level?
While your implementation of this is probably dependent on your specific needs, there is no absolutely correct answer on how you should do this. There are good reasons for one or the other though:
If you are going to import data (or have data somehow created in your database) via means other than your application, then you either have to implement this validation in the database, or handle invalid data safely in your application.
It will be quite a bit easier to handle this validation (and any resulting errors) by using a custom validator.
If you only implement the validation in the database, you're going to have to handle database-specific errors and won't know until data is flushed whether it's valid or not. That will not go well for you.
From my perspective, I'd implement the validator in the application only, then have a way for handling invalid data if it's loaded from elsewhere. If data validity is paramount, then I'd probably implement the validator in both places, being 100% sure that the logic matches!
While reading "The Definitive Guide To Grails", I am a little confused as to Command Objects. They seem to be a wrapper around domain classes to assist with validation but that is functionality already available in domain classes via built in constraints and further via custom validators so then what does a command object do really and what motivates us to need it?
The book starts the discussion on command objects by stating that
"Sometimes a particular action doesn’t require the involvement of a
domain class but still requires the validation of user input."
However, then it demonstrates the declaration of and the usage of a command object with regards to an Album domain class. So, it seems whatever a command object does is still closely related to domain classes. I'm sure my confusion is completely a result of my lack of understanding and so I wish to seek any clarification. Thanks.
They seem to be a wrapper around domain classes...
You can use command objects that way, but that isn't their primary use.
Command objects are useful when you want to encapsulate a group of request parameters and do something with them together. That something might or might not have anything to do with domain classes.
For example, you could have a Grails app which doesn't have any domain classes at all and command objects could still be really helpful. Imagine a Grails app that is just a service layer that receives request from web forms or REST requests with a JSON body or whatever and the Grails app is going to receive those requests, validate the inputs, maybe do some math or anything at all and then make a REST call to some other backend process that might store them in a database or generate reports or whatever. In a situation like that, there are a lot of reasons that you might want to use command objects even though no domain classes are involved at all.
Don't get bound up thinking that command objects have to be tied to domain classes. Sometimes they are, but don't limit your thinking of them to that context. Use command objects when you want to relate a group of request parameters together and do something with them.
I tend to use command objects that match what is happening in the UI layer, form submits can be validated with command objects then passed into services that do the work of persisting them. It many times makes sense to have your domain model be different then the UI flow you are working with.
My domain layer may also have looser constraints than some of the command objects if I want to require certain flows provide enough information.
I'm writing an application that details an applicant's status in our company through Salesforce; when one of our employees enters their Enquiry ID, it shows their status (cleared, not cleared) and, if not cleared, what the applicant needs to fix before they can proceed in their program.
I want to make sure that I am thinking about my application's different areas correctly. Here is what I have:
Model: The applicant class has a dynamic function, such as Application.find_by_Enquiry_Token__c_and_Account_dot_LastName_from_Opportunity, and when requested it returns the information from Salesforce
Controller: Parses the returned data from Salesforce and creates hashes with the information, such as #applicant[:general_information] = {:first_name = data[:Account].first[:FirstName], :last_name = data[:Account].first[:LastName]}.
View: Displays the information generated by the controller. However, it has it's own logic and checks, such as changing the color of a div depending on if they are clear (class="success"), if they are not clear (class="danger") or if they have some conditional information (class="warning").
I think I have this correct, except I'm a little worried about my view because I have a bit of Ruby code in there to perform checks based on the returned data, mainly to colorize but also to show certain errors. Is this okay/does this follow standards? Or should I try to refactor my application and push this up to the controller?
I would say having some ruby code like you do in the view is fine as long as you aren't performing long queries or setting instance variables in the view. Also another sign to start moving code from the view to the controller is if you feel the view is getting cluttered and hard to understand. From what you said, this seems like it is not a problem though.
One thing I would recommend changing is to make the method name on the model shorter. Shorter method names are much easier to understand and as you have it, the method name is very long and unwieldy. Other than that, I think you are doing everything well!
Displaying the correct classes in the view is fine and can't really be done anywhere else. If you feel like your views are getting messy, consider dividing them into partials or using Haml for views instead of ERB.
Model is where your application's business logic goes, including parsing data, and everything related to your domain.
Controllers handle interactions with the user. So, basically, in a webapp if a user goes to a URL what should your application do. This should not be doing anything other than handing off tasks to other classes and then rendering a view.
Views are just that. They should be super simple and straightforward as possible. You can extract logic from views into helpers or even presenters/decorators. Views handle what gets displayed to a user.
In your app I would have:
SalesforceApiGateway class which handles communications with Salesforce, I wouldn't be surprised if there was already a gem out there to handle this.
A model class for each Salesforce resource you are accessing. These would setup the proper call to the API gateway to pull the right data for the given resource.
This could get hairy quickly and may need to be extracted further: 1 class for interfacing with the gateway and a model class the resources as you would want to access them from your application.
Your controller should not be parsing any Salesforce data, but rather taking a user request and and wiring that up to the proper model.
The biggest thing to keep in mind is your classes should be doing one thing and one thing only. If you can't talk about your class without saying "and" then it is probably doing too much.
So you have a class that interfaces with the API. You have a class that parses the API. You have a class that brings an api's resource into your domain, etc.
A friend asks "Do you have examples or docs on how to inspect the Breeze change-set data on the server and perform server side validation and security checks before committing the data to the database?" My answer follows.
See the "Custom EFContextProvider" topic in the documentation which describes the Breeze.NET facilities for this purpose.
Although this topic targets the EFContextProvider<T> specifically, most of the points apply to the base class, ContextProvider<T>, which is helpful when saving to any kind of data store (see the "NoDb" sample for example).
The app produced by the BreezeMvcSpa template offers a taste of save validation (understood in the broadest sense to include security checks).
The BreezeMvcSpa template will be released Feb 2013 in conjunction with the "ASP.NET and Web Tools 2012.2")
Look at Models/TodoRepository.cs which inherits from EFContextProvider<T>. It overrides BeforeSaveEntity(entityInfo) to confirm that you are always updating/deleting a TodoList/TodoItem that belongs to the current user. It also assigns the current user to a new TodoList. In a real app, this would be a dispatcher to some helper classes dedicated to validating specific entity types, a point I slightly elaborate below.
There are two other important overrides:
BeforeSaveEntities(saveMap) gives you a chance to examine the entire change-set at once. This is a great way to make validate the entire change-set as a whole perhaps to ensure that this save request makes sense as a single transaction. It's also a good place to do some cross-entity checking. BeforeSaveEntities(saveMap) is called after calling BeforeSaveEntity(entityInfo) for each entity individually.
BeforeSaveEntities(saveMap) might be a good dispatch point for delegating validation to dedicated helper classes. I doubt that I would put all of my validation logic in one big ContextProvider class. I don’t mind that all save activity funnels through the ContextProvider.SaveChanges gate but I don’t want to do all the work in the ContextProvider itself.
SaveChangesCore is the other important override. That’s where you do any final pre-save preparation and hand the change-set to something that actually performs the database save (e.g., the DbContext.SaveChanges method). You could intercept the result of the save operation before returning control to the ContextProvider.
Note also that, when using the DbContext, EF applies the validations you prescribe in model attributes, both the standard set and your custom validation attributes.
I have more save advice but this is probably enough to digest right now.
I am using AjaxSubmit to post a form and there are server side validations done using XVal (RuleException way). I am not using the try/catch way to add error to Model and then send to view. Instead - I want to use the HandleError attibute and in the OnException I am adding the errors to Model. The major problem is how do I get those errors as a results in the Ajax Call?
There is not a great solution built in right now. Doing this correctly requires a client-side validation framework (because, to display the errors, you need to dynamically change the HTML page), and until recently, ASP.NET MVC has not had that. However, ASP.NET MVC 2 Preview 2 introduced client-side validation, so it's reasonable to presume that something might be built into the framework soon.
In the meantime, however, HandleErrorAttribute won't help you. HandleErrorAttribute only knows how to redirect to an error page, which is generally not what you want to do in response to a server-side validation error even with a "normal" POST, and certainly not with an AJAX post.
There really two different scenarios you need to handle:
Validation errors are not catastrophic failures; they are simply bad user data, which you should expect. You just need to get the information back to the page, so that the page can be marked up to tell the user how to fix their data.
You also need to handle catastrophic failures, like unanticipated exceptions. This is akin to what HandleErrorAttribute does, insofar as you can display a message to a user, but you cannot necessarily match that message up with specific fields on your page.
To handle the first scenario of error, you need to wrap the model state up into an object which will be parsable in JavaScript code; JSON is the obvious fit here. You then need to have JavaScript code on the client side which parses this object and marks up the form fields. This is easier if you tie into an existing client-side validation framework, which already contains code for marking up form fields.
To handle the second type of error, you can extend HandleErrorAttribute in order to provide JSON instead of HTML in the event of a catastrophic failure. Again, you will need to write JavaScript code that will be executed in the event of a failure -- jQuery's global ajaxError event is useful here -- that detects this structured error information you've created and display some sort of useful message to the user.
If all this sounds a bit involved, well, it is, which is why it may make more sense to wait and see what will be built-in when MVC 2 is finally released.