Let's say we have a dexterity content type with two fields: field_a
and field_b
.
In edit mode:
field_a
has the category_1
value selected then field_b
is not requiredfield_b
has other value selected then field_b
is requiredIt seems a simple validation is not possible here. I tried:
from zope.interface import Invalid
def validate_field_b(value):
# value is a string here. I can't create a condition based on field_a.
raise Invalid(_(u"Value in field b is required."))
used here:
field_b = schema.TextLine(
title=_(u"Some field B"),
required=False,
constraint=validate_field_b
)
The result is field_b
required all the time. :)
Any solution here? How the get the form / context / request / other fields value in my validator?
The solution is to use an invariant
instead of constraint
:
https://docs.plone.org/external/plone.app.dexterity/docs/advanced/validators.html#invariants
@invariant
def validate_field_b(data):
if data.field_a != 'category_1' and data.field_b is None:
raise Invalid(_("Missing input for field_b."))