Dexterity: Unique field validation

Hi everyone,

I'm trying to implement a unique field code for a dexterity content type and added already a validator:

class IPatient(model.Schema):
    code = schema.TextLine(
        title=_(u"label_patient_code", default=u"Tax/Fiscal Code"),
        description=_(u"Patient unique Tax/Fiscal Code"),
        required=True)

    @invariant
    def validate_code(data):
        """Checks if the patient code is unique
        """
        ... (catalog search) ...

However, since this validator lives in the interface, I can not check if the current value of the field was changed after edit or not. Therefore, my validator fails obviously for each edit.

What would be the best approach to check if the value was changed or not?

I have already seen the data converters in z3c.form.converter. Would this be the right way to handle that or in a custom edit view in handleApply or extractData?

Thanks in advance

Something from an old ZTK application, which might help you:

    @invariant
    def validate_email_and_user(self):
        """Check for user."""
        context = getattr(self, '__context__', None)
        if context is None:
            # We are in an AddForm
            return checkForUserlogin(self.email)
        # We are in an EditForm
        if context.email == self.email:
            # nothing has changed
            return True
        # Changes in editForm. Test if new userlogin is not assigned
        return checkForUserlogin(self.email)
2 Likes

Hi Thomas,

thanks for your swift reply and the code snippet!

Looks a bit like a hack, but too simple to reject it! And of course it works just perfectly!

However, I thought there's a fancy adapter or something, simply to write more code and achieve the same result... What to do now with the sparse time...? :smile:

Best regards and thanks again
Ramon

1 Like

Well, you could write one :wink:

Glad it worked out for you!

Plone Foundation Code of Conduct