Using a Form Widget Validator on multiple fields - plone

I've written a custom validator for my schema field as shown in the documentation here:
http://docs.plone.org/develop/plone/forms/z3c.form.html#form-widget-validators
My question is that if i want to use the same validator for a few different fields, is that possible? It doesnt seem to work. eg I would like to write:
# Set conditions for which fields the validator class applies
validator.WidgetValidatorDiscriminators(PhoneNumberValidator, field=IZohoContactForm['phone_number'])
validator.WidgetValidatorDiscriminators(PhoneNumberValidator, field=IZohoContactForm['another_phone_field'])

As a workaround I have written two identical validators with different names which violates the DRY principle but not much i can for this one it seems...

It is possible to pass a field type as well for the field argument
(see: https://docs.plone.org/develop/addons/schema-driven-forms/customising-form-behaviour/validation.html#field-widget-validators): validator.WidgetValidatorDiscriminators(MyListValidator, field=schema.List)
In the above example the validator is applied to all fields of type schema.List

It's an old question but I just recently faced this problem and this is my approach:
Set a schema interface for the field to be validated.
class ICaptchaSchema(model.Schema):
captcha = schema.TextLine(
title=_('security_check', default="Security check"),
)
Use the field in form schema interface:
class IFormSchema(model.Schema):
captcha1 = ICaptchaSchema['captcha']
captcha2 = ICaptchaSchema['captcha']
Register form widget validator for the first schema iterface:
validator.WidgetValidatorDiscriminators(YourCustomValidator,
field=ICaptchaSchema['captcha'])
All fields "captcha" will be adapted.
Regards.

Related

Can a plone.behavior be enabled for just some objects of a type?

I would like to set a marker interface to some objects that should have additional fields. If I remove this marker interface again the fields should be removed too.
Now I'm trying to understand plone.behavior. But I'm not sure if a behavior must be enabled for all objects of a type or is it possible to enable it for only a subset of objects of that type?
Take a look at collective.instancebehavior, an add-on aimed to do exactly what you want: to enable behaviors per content type instance.
Unfortunately I don't think there is a solution out of the box.
The simplest thing you can do is working on the form fields by overriding the updateFields method in the form.
This is untested demo code:
def updateFields(self):
if not IMyInterface.providedBy(self.context):
self.fields = (
self.fields.omit('IMyBehaviour.my_field')
)
As a reference have a look to:
https://github.com/plone/plone.app.users/search?utf8=%E2%9C%93&q=def+updateFields

Use custom value on symfony2 choice form type using choice_list

I'm trying to use custom values in a choice form type which gets its data from a database query that needs post-processing. For this reason I opted to use the choice_list option and extending Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList\ChoiceList. The problem is that I need custom index/value for the resulting dropdown instead of the default 0-indexed style. 0-index doesn't work form me as I will access the values using Javascript and need the data I retrieved from the database.
I already tried replacing the createIndex() method in the ChoiceList class but to no avail :-(
Any tips?
I can't believe it...I have tried the whole day and couldn't find the answer. 5 Minutes after having published the question, I solved it.
For future research:
You need to overwrite the createValue() method in the Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList class.

Formatted text in QTreeWidgetItem

I need to create QTreeWidgetItems which have support for formatted texts, such as:
MyCreatedType - INTEGER(1)
(ie: the line above should have a "normal" part : MyCreatedType and a "formatted" part (INTEGER(1) in our case).
Any idea how to accomplish this?
Thanks.
What you need is a delegate. Delegates are explained here:
Star Delegate Example http://qt-project.org/doc/qt-4.8/itemviews-stardelegate.html
QItemDelegate Reference http://qt-project.org/doc/qt-4.8/qitemdelegate.html
The general procedure I follow when creating and using custom delegates:
Create a custom type with the information you want to encapsulate.
For your case, perhaps fields for the variable type name and type value.
Store these custom types in your model, wrapping them in QVariants to satisfy the return types required by QAbstractItemModel
Create a control that matches the UI you want.
In this case it might mean a QText label for "MyCreatedType" followed by a second label in bold for "Integer(1)".
Perhaps the control has methods like "setTypeName" and "setTypeValue"
Create a delegate that paints your specific control when your custom type is found.
You will have to map fields in the custom type to fields in the custom UI control as needed.
Associate your model and delegate with the Tree View you are using.
I hope this general procedure makes sense. I would recommend completing the Star Delegate Example and then reading my procedure, as it will make more sense with some background.

Do standard ASP.NET controls connected to an entity datasource provide built in validation?

The entity framework connects to my database to retrieve columns, datatypes, relations, etc. It also knows which columns can be null and not null.
If I connect a regular asp.net grid to an entity datasource, it can generate the grid automatically based on the entity. It knows which fields should be a checkbox based on the datatype, etc.
Since data types are built into the entity class, can a regular asp.net control (like a grid or formview) also perform validation automatically? (or generate the necessary validation controls at least?)
Thanks,
Kevin
Yes, you can display validation errors including validation types using asp:ValidationSummary control. Here one project with this approach used on gridview: http://code.msdn.microsoft.com/ASPNET-Web-Forms-97f8ee9a , check out editing students.
The way to add more validation rules to entities is by attaching meta data.
If you are using EF Code First you can apply rules directly else by adding meta data class, here example:
[MetadataType(typeof(EntityNameMetaData))]
public partial class EntityName {} // name of entity which want to add validation
public class EntityNameMetaData // this is a place, where put validation rules
{
[StringLength(25, ErrorMessage = "First name must be 25 characters or less in length.")]
[Required(ErrorMessage = "First name is required.")]]
//custom or other validation rules
public String EntityProperty
}
this is not possible automatically in asp.net, you would have to define the columns and create item templates to implement this.

How to check constraints on dexterity content types fields

I want to check during edit form saving process the value of a field verify some constraints
(understand calling a method where I can invalidate the form action)
The field must be defined via schema (not supermodel), otherwise the field isn't visible in the schema. Once the field is defined in the schema, you may use a decorated function like the following to set a field validator:
#form.validator(field=IMySchema['title'])
def validateTitle(value):
if value == value.upper():
raise schema.ValidationError(u"Please don't shout")
I'm pretty sure you can do this with a filesystem code dexterity type using zope.interface invariants.
Take a look at the Dexterity Developer Manual, on the chapter dedicated to validators.

Resources