i'd like to know whether I could ignore play standard validation when I want to. For instance, let's imagine I have a Entity called Car just like
#Entity
public class Car{
#Id
private Long id;
#Required
private String model;
#Required
private String hiddenField; //important but doesn't appear in some cases (some usecases)
}
In order to make it clearer, then
Case 1
#(carForm : Form[Car])
#import helper._
#form(routes.controller.foo.bar) {
#inputText(carForm("model"))
<input type="submit">
}
Case 2
#(carForm : Form[Car])
#import helper._
#form(routes.controller.foo.bar) {
#inputText(carForm("model"))
#inputText(carForm("hiddenField"))
<input type="submit">
}
Then I have a Play.data.Form object, and it has errors cause i haven't filled model or the hiddenField that was given as exmple. But, actually, i have some situations that this hidden doesn't even appear (case 1), i mean, there's no input called that, as the user is not allowed to edit it that time. So, if I have two usecases, where at the first, all inputs are there and they are supposed to be filled, but the other one has no 'hiddenField' input, but, altought, it's still required by my model, and, of course, a form submitted without it has error as well, what should I do?. How was I supposed to deal with it? I have one model, but validation may be different in one case to another, and i wanna it to be server side, not jquery nor pure javascript.
I tried to discardErrors through
(Imagine it was submitted from case 1)
MyForm<Car> myCarForm = Form.form(Car.class).bindFromRequest();
//it has errors, sure it does, hiddenField was required and that field didn't even exist at screen.
myCarForm.discardErrors(); //ok, error hashmap is empty right now
myCarForm.get(); // anyway, no value here.
//myCarForm.data(); //for sure i could retrieve field by field and remount object that way, but that looks hacky and hardworking
Then, any solution? Thank u all
I got it reading Play for Java book.
6.4.2 Partial Validation
A common use case is having multiple validation constraints for the same object
model. Because we’re defining our constraint on the object model, it’s normal to have
multiple forms that refer to the same object model. But these forms might have different
validation constraints. To illustrate this use case, we can imagine a simple wizard in
which the user inputs a new product in two steps:
1 The user enters the product name and submits the form.
2 The user enters the product EAN number and the description.
We could validate the product’s name during step 2, but displaying an error message
for the product name at that point would be weird. Fortunately, Play allows you to perform
partial validation. For each annotated value, we need to indicate at which step it
applies. We can do that with the help of the groups attribute from our annotations.
Let’s change our Product model class to do that:
public Product extends Model {
public interface Step1{}
public interface Step2{}
#Required(groups = Step1.class)
public String name;
#Required(groups = Step2.class)
public String ean;
}
Then, at Controller
// We re//strict the validation to the Step1 "group"
Form<Product> productForm =
form(Product.class, Product.Step1.class).bindFromRequest();
Thanks!
Yes you can achieve the solution to this problem. what's happening in this case is every time you map your request to model car it will always look for JPA validations for every property then it looks for validate() method present inside that model, if that method returns null then it doesn't pass any error and perform the normal execution, but if it returns any thing then it maps it to form errors.
You can return error mapping to specific field or you can just return a string that will be considered as a global error.
In your case solution is :
#Entity
public class Car{
#Id
private Long id;
private String model;
private String hiddenField; //important but doesn't appear in some cases (some usecases)
public List<ValidationError> validate() {
List<ValidationError> errors = new ArrayList<ValidationError>();
.
.
.
#Some logic to validate fields#
#if field invalid#
errors.add(new ValidationError("model", "errorMessage"));
.
.
.
return errors.isEmpty() ? null : errors;
}
Note: Just remove the JPA validation and use your logic in validate function to check according to the situation.
Ignores validations, like this:
myCarForm.discardErrors().get();
and does the validation otherwise, Jquery for example.
Related
i am trying to implement repository pattern in mvc. but I am stuck. I want to return related data. I have two classes , tbl_Account (contains users )and tbl_Country (contains countries).
public class AccountRepository : IAccount
{
public IEnumerable<Account> GetCountry()
{
var Account = this.storeDB.tbl_UserAccount.Include(s => s.tbl_Country).ToList();
return Account; // it gives error here, saying explicit cast required
}
}
Account is a model class i have created on top of tbl_Account for field validations.
how to cast this or i am missing something else... please please help
1.) Variable name must start lower case.
2.) Method name 'GetCountry' but you return Account.
3.) After include you need to Select countries in account and then return countries.
4.) Please share your entities (model classes) in your question if you wanna get cool answers
I have one main document:
#Document
public class MainDocument {
private String name;
private String desc;
private List<Nested> nestedList;
-- More fields/methods --
}
and a document getting embedded:
#Document
public class Nested {
private String nestedUser;
private String nestedTitle;
-- More fields/methods --
}
When attempting to store a new instance of the Nested class in List<Nested>, the fields of the Nested class are getting renamed. For example, nestedTitle becomes title. This wouldn't be a huge deal except for the fact that it is not allowing me to set the value of some of the renamed fields.
I have tried using the #Field("field_name") annotation but the fields will still get renamed and ignore attempts to set their value.
What would be causing some of the fields to get renamed? Am I missing something? About half of the fields get renamed and the rest stay the correct name...
I am testing by using POSTMAN to send JSON requests to the controller for the main document. Even if I use the new field name in the JSON request the value will still not be set.
Figured it out...
Getter method for nestedTitle was named getTitle() so it was renaming it based on the getter methods name. Changed to getNestedTitle() and it stopped getting renamed. Changed the other getter methods for the fields in question and now everything works as expected.
Not sure why it would rename the field's based on the method name but who am I to judge Spring... Posting this answer to save someone else a couple hours of their time.
I'm new at Apache Isis and I'm stuck.
I want to create my own submit form with editable parameters for search some entities and a grid with search results below.
Firstly, I created #DomainObject(nature=Nature.VIEW_MODEL) with search results collection, parameters for search and #Action for search.
After deeper research, I found out strict implementations for actions (For exapmle ActionParametersFormPanel). Can I use #Action and edit #DomainObject properties(my search parameters for action) without prompts?
Can I implement it by layout.xml?
Then I tried to change a component as described here: 6.2 Replacing page elements, but I was confused which ComponentType and IModel should I use, maybe ComponentType.PARAMETERS and ActionModel or implement my own IModel for my case.
Should I implement my own Wicket page for search and register it by PageClassList interface, as described here: 6.3 Custom pages
As I understood I need to replace page class for one of PageType, but which one should I change?
So, the question is how to implement such issues properly? Which way should I choose?
Thank you!
===================== UPDATE ===================
I've implemented HomePageViewModel in this way:
#DomainObject(
nature = Nature.VIEW_MODEL,
objectType = "homepage.HomePageViewModel"
)
#Setter #Getter
public class HomePageViewModel {
private String id;
private String type;
public TranslatableString title() {
return TranslatableString.tr("My custom search");
}
public List<SimpleObject> getObjects() {
return simpleObjectRepository.listAll();
}
#Action
public HomePageViewModel search(
#ParameterLayout(named = "Id")
String id,
#ParameterLayout(named = "Type")
String type
){
setId(id);
setType(type);
// finding objects by entered parameters is not implemented yet
return this;
}
#javax.inject.Inject
SimpleObjectRepository simpleObjectRepository;
}
And it works in this way:
I want to implement a built-in-ViewModel action with parameters without any dialog windows, smth like this:
1) Is it possible to create smth like ActionParametersFormPanel based on ComponentType.PARAMETERS and ActionModel and use this component as #Action in my ViewModel?
2) Or I should use, as you said, ComponentType.COLLECTION_CONTENTS? As I inderstand my search result grid and my search input panel will be like ONE my stub component?
Thank you.
We have a JIRA ticket in our JIRA to implement a filterable/searchable component, but it hasn't yet made it to the top of the list for implementation.
As an alternative, you could have a view model that provides the parameters you want to filter on as properties, with a table underneath. (I see you asked another question here on SO re properties on view models, so perhaps you are moving in that direction also... I've answered that question).
If you do want to have a stab at implementing that ticket, then the ComponentTYpe to use is COLLECTION_CONTENTS. If you take a look at the isisaddons, eg for excel or gmap3 then it might help get you started.
======= UPDATE TO ANSWER (based on update made to query) ==========
I have some good news for you. v1.15.0-SNAPSHOT, which should be released in the couple of weeks, has support for "inline prompts". You should find these give a user experience very similar to what you are after, with no further work needed on your part.
To try it out, check out the current trunk, and then load the simpleapp (in examples/application/simpleapp). You should see that editing properties and invoking actions uses the new inline prompt style.
HTH
Dan
I'm looking for someone to point me in the right direction (link) or provide a code example for implementing a drop down list for a many-to-one relationship using RequestFactory and the Editor framework in GWT. One of the models for my project has a many to one relationship:
#Entity
public class Book {
#ManyToOne
private Author author;
}
When I build the view to add/edit a book, I want to show a drop down list that can be used to choose which author wrote the book. How can this be done with the Editor framework?
For the drop-down list, you need a ValueListBox<AuthorProxy>, and it happens to be an editor of AuthorProxy, so all is well. But you then need to populate the list (setAcceptableValues), so you'll likely have to make a request to your server to load the list of authors.
Beware the setAcceptableValues automatically adds the current value (returned by getValue, and defaults to null) to the list (and setValue automatically adds the value to the list of acceptable values too if needed), so make sure you pass null as an acceptable value, or you call setValue with a value from the list before calling setAcceptableValues.
I know it's an old question but here's my two cents anyway.
I had some trouble with a similar scenario. The problem is that the acceptable values (AuthorProxy instances) were retrieved in a RequestContext different than the one the BookEditor used to edit a BookProxy.
The result is that the current AuthorProxy was always repeated in the ValueListBoxwhen I tried to edit a BookProxy object. After some research I found this post in the GWT Google group, where Thomas explained that
"EntityProxy#equals() actually compares their request-context and stableId()."
So, as I could not change my editing workflow, I chose to change the way the ValueListBox handled its values by setting a custom ProvidesKey that used a different object field in its comparison process.
My final solution is similar to this:
#UiFactory
#Ignore
ValueListBox<AuthorProxy> createValueListBox ()
{
return new ValueListBox<AuthorProxy>(new Renderer<AuthorProxy>()
{
...
}, new ProvidesKey<AuthorProxy>()
{
#Override
public Object getKey (AuthorProxy author)
{
return (author != null && author.getId() != null) ? author.getId() : Long.MIN_VALUE;
}
});
}
This solution seems ok to me. I hope it helps someone else.
I'm using Entity Framework 4 and a Dynamic Data site to expose a bare-bones admin interface to a few users. Working pretty well in general, but I have run into this one problem on a couple of fields on my model.
Several tables have some audit-related fields - CreatedBy, CreatedDate, ModifiedBy, and ModifiedDate. These fields are required in the database and the associated models are marking the properties as non-nullable (all as it should be). However I am handing setting the values for these fields in code - the field templates for the field types mark these specific fields as disabled on the page, and in the SavingChanges event I set these fields to the appropriate values. All works great when I'm updating an existing item.
The problem comes in when I try to create a new item. I want these fields to remain empty on the page and be auto-populated by my code when submitted, but the Field Templates set up RequiredFieldValidators for these fields and won't let me submit them without a value. Normally this would be great, except that I want to prevent EF from validating these fields at the point of page submission.
I realize that I could mark the fields as nullable in the database and that would resolve the issue - it would probably even be just fine from the data standpoint, but I'm not comfortable with doing so - for one thing it's not unlikely that some of the models these fields appear on will be bulk loaded, possibly by someone else, at a later date. I would rather still have the database enforce the non-nullability of these fields. In the field templates I've tried moving the built-in SetUpValidator() call for the RequiredFieldValidator not to run when these specific fields are being loaded, and I've also tried disabling the RequiredFieldValidators and forcing their IsValid property to true. None of these actions allows me to submit the page.
Is there a way to tell EF/Dynamic Data to skip the validation for some fields?
EDIT
As noted below, I also tried marking them nullable in the model and not in the database, which caused an error: Problem in mapping fragments...Non-nullable column...in table...is mapped to a nullable entity property.
EDIT #2
I have found a solution that works, but requires modifying the auto-generated designer file for the entity set, which is fragile at best. I would love to know a "righter" way to do it, but if nothing becomes apparent in the next couple of days I'll post my own answer.
So here are the edits I found I had to make. When allowing the tool to create the entities in the edmx Designer.cs file I get properties like these:
for a datetime on the server side
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.DateTime CreatedDate
{
get
{
return _CreatedDate;
}
set
{
OnCreatedDateChanging(value);
ReportPropertyChanging("CreatedDate");
_CreatedDate = StructuralObject.SetValidValue(value);
ReportPropertyChanged("CreatedDate");
OnCreatedDateChanged();
}
}
for a varchar
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String CreatedBy
{
get
{
return _CreatedBy;
}
set
{
OnCreatedByChanging(value);
ReportPropertyChanging("CreatedBy");
_CreatedBy = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("CreatedBy");
OnCreatedByChanged();
}
}
To make it work without validation for a DateTime property setting the IsNullable parameter of the EdmScalarPropertyAttribute to true is sufficient to avoid the issue. For the String property you also have to change the 2nd parameter of the SetValidValue method call to "true."
All of this said, the only reason that I'm leaving this as it is is because I don't expect to have to regenerated the entities more than once or twice before we move to a different platform for this site. And in this case, merging the version in I have checked in to git with the version generated by the tool allows me to avoid most of the headaches,
Here is my meta information for a read-only auto generated date field. I don't get validation controls validating these fields. Hope this helps.
[ReadOnly(true)]
[DataType(DataType.Date)]
[Column(IsDbGenerated = true, UpdateCheck = UpdateCheck.Never, AutoSync = AutoSync.Never)]
[UIHint("DateTime")]
[Display(Name = "Modified", Order = 1000)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public object DateModified { get; private set; }