How can I validate a field in a vaadin table? For example the year field with a regex:
val persons: BeanContainer[Int, Person] =
new BeanContainer[Int, Person] classOf[Person])
persons.setBeanIdProperty("id")
persons.addBean(new Person("Thomas", "Mann", 1929, 123123))
persons.addBean(new Person("W. B.", "Yeats", 1923, 643454))
persons.addBean(new Person("Günter", "Grass", 1999, 743523))
// create table
val table: Table = new Table("Nobel Prize for Literature", persons)
table.setVisibleColumns(Array("id", "firstName", "lastName", "year"))
table.setColumnHeader("lastName", "last name")
table.setColumnHeader("firstName", "first name")
table.setColumnHeader("year", "year")
// create a validator
val yearValidator = new RegexpValidator("[1-2][0-9]{3}",
"year must be a number 1000-2999.");
// TODO check the year field!
table.addValidator(yearValidator)
I create a Regex Validator, but how can I set the validator to the right field?
You have to intercept the creation of the fields with a field factory and add the validators there:
table.setTableFieldFactory(new DefaultFieldFactory() {
#Override
public Field createField(Item item, Object propertyId, Component uiContext) {
Field field = super.createField(item, propertyId, uiContext);
if ("year".equals(propertyId)) {
field.addValidator(new RegexpValidator("[1-2][0-9]{3}",
"year must be a number 1000-2999.");
}
return field;
}
});
(Java, not Scala, but it should be straightforward to translate this to scala).
Related
I have two mongoose models with a relationship like this:
const ProductSchema: Schema = new Schema(
{
name: String,
category: {
type: Schema.Types.ObjectId,
ref: 'Category'
},
description: String
}
with a text index on name and description fields.
The category schema looks like this
const CategorySchema: Schema = new Schema(
{
title: String
}
with text index on title field.
Is it possible to have a fulltext search for products such that the keywords can include the category title or even just a text search with the category title alone?
You could find all Products, populate them, and then filter using .filter().
The code would look like this (I guess you know how to gather user input, so I skipped that part):
// If you have saved the user input in a variable
const searchFieldInput = "foo";
const products = await Product
.find({}) // Finds all Products in the DB
.populate("category"); // Populates the Category field
// Filter the products array based on the user input
const filteredProducts = products.filter((product) =>
product.category.includes(searchFieldInput)
)
I want to update only those fields in mongo document that have values in the POJO. How do I do this?
I have a User collection with the following document:
{
_id: ObjectId("someId"),
name: "Foo",
age: 20,
gender: "male"
}
Now I want to update only the age to 22 so, I have a User pojo with age = 22 and _id = ObjectId("someId").
I don't want to use Updates.set("age",22) because then I'll have to handle every field. The field to be populated may be something other than age.
So, I used reflection to make a generic method to get the list of Update.sets for the pojo
classMembers = User::class.memberProperties
// get hashmap from pojo
val fieldsMap: HashMap<String, Any> =
mapper.convertValue(pojo, object : TypeReference<HashMap<String, Any>>() {}) ?:
throw CustomException( HttpStatus.BAD_REQUEST, "Could not parse request" )
// get hashmap from default/empty pojo
val defaultMap: HashMap<String, Any> =
mapper.convertValue(emptyPojo, object : TypeReference<HashMap<String, Any>>() {}) ?:
throw CustomException( HttpStatus.BAD_REQUEST, "Could not parse request" )
for (member in classMembers) {
val name = member.name
val value = fieldsMap[name]
//add to list only if the current value is not null or default and current value is different
if (value != null && defaultMap[member.name] != value && member.getter.annotations.isNotEmpty()) {
val field = (member.getter.annotations[0] as BsonProperty).value
setList.add(Updates.set(field, value))
}
}
This works. But I wanted to know if theres a better way to do it? A default way to do this via mongoClient or mongoTemplate or mongoRepository?
I am trying to filter a null field and validate it in forms.py But i get below error :
Cannot assign None: "TeacherAttendance.teacher" does not allow null values.
But i am doing validation in the form as below for teacher field. It should generate "Please choose teacher" validation warning. But it is not doing.
It should validate the null value for teacher and go back to form with a validation warning if i dont choose a teacher from teacher field.
class TeacherAttendanceForm(forms.ModelForm):
class Meta:
model = TeacherAttendance
fields = ('time', 'attendance', 'teacher','dailynote','writer',)
exclude = ['uuid', 'notedate',]
widgets = {
'attendance': forms.RadioSelect(renderer=HorizontalRadioRenderer),
'dailynote': forms.Textarea(attrs={'rows': 10}),
'writer': forms.Textarea(attrs={'rows': 1}),
'uuid': forms.HiddenInput(),
'semester': forms.HiddenInput(),
}
def clean(self):
if str(self.cleaned_data['time']) == "-----------":
raise forms.ValidationError('Please choose time.')
if self.cleaned_data['dailynote'] == "":
raise forms.ValidationError('Please enter note.')
if not self.cleaned_data['teacher']:
raise forms.ValidationError('Please choose teacher .')
My model is below and teacher field is a dropdown filed that shows all teacher.
class TeacherAttendance(BaseModel):
teacher = models.ForeignKey(Staff, blank=True, verbose_name=_("Choose Teacher"))
attendance = models.CharField(choices=TEACHER_ATTENDANCE, default="YOK", max_length=20, verbose_name=_("Attendance"))
time = models.CharField(choices=TIME, default="-------------", max_length=20, verbose_name=_("Time"))
dailynote = models.TextField(null=True, blank=True, verbose_name=_("Add Note"))
notedate = models.DateField(auto_now_add=True, db_index=True, verbose_name=_("Date"))
writer = models.TextField(null=True, blank=True, verbose_name=_("Writer"))
class Meta:
unique_together = ("teacher", "attendance", "notedate")
index_together = [["teacher", "notedate", ], ]
def __unicode__(self):
return "%s / %s / %d " % (self.teacher, self.notedate, self.attendance)
I solved the question by changing below field in model :
teacher = models.ForeignKey(Staff, blank=True, verbose_name=_("Choose Teacher"))
to :
teacher = models.ForeignKey(Staff, blank=True, null=True, verbose_name=_("Choose Teacher"))
by adding "null=True" to the field. Probably it was first looking at the model field before doing form validation.
I am trying to figure out how to seed a complex entity framework code first object. Currently the code I have allows me to insert simple objects but there has to be a way do more complex items, i.e. Address with an AdressType field.
context.AddressTypes.AddOrUpdate(
p => p.Name,
new AddressType { Name = "Original" },
new AddressType { Name = "Shipping" },
new AddressType { Name = "Billing" }
);
context.Addresses.AddOrUpdate(
a => a.Address1,
new Address
{
Address1 = "1234 West Main",
City = "Hannibal",
Region = "MO",
PostalCode = "12345",
Country = "USA",
Type = context.AddressTypes.Where(a=>a.Name=="Original")
});
But while I can "Find" an addresstype by id I can't do a "Where" name equals. Find would work except that I can not guarantee what the id will be with each seed and want to base it on name instead.
Any suggestions on how to do this?
TIA
Solution:
Added a reference System.Linq to the seed class. Then was able to the where clause.
I am new using entity framework
i have a list of form numbers and i want to search from a table for that list of form numbers and then return form numbers from the list that not contains in the table
i tried this query it gave me half of the work:
here is my list:
var strPurchaseFormNoList= new List<string> { "1", "2", "3" }
and this is my query:
var checkPurchaseAccount = vcEntities.VcUserAccountTbls.Where(x =>
!strPurchaseFormNoList.Contains(x.FormNo))
how to select form numbers in the list that not include from the table ?
you're looking for the "Except" extension.
var reject_list= vcEntities.VcUserAccountTbls.Where(p =>strPurchaseFormNoList.Contains(p.FormNo))
var checkPurchaseAccount = vcEntities.VcUserAccountTbls.Except(reject_list);