How can I dynamically remove an entity constraint? I'm working on a single-sign-on module for D8 and would like to disable the password fields on the user edit form, since passwords should be managed by the outside identity provider and not through Drupal.

Drupal adds a "current password" field to the edit page which is required if the user wants to change their email address. I can remove the field easily in a hook_form_alter, but there's a form constraint, ProtectedUserFieldConstraintValidator, that runs and fails validation if the password field is not filled out.

How can I remove this form constraint dynamically?

Things I've looked at so far:


In my hook_form_alter setting $form_state-&gt;getFormObject()-&gt;getEntity()-&gt;_skipProtectedUserFieldConstraint = TRUE. This is a property that this constraint checks and when TRUE will skip it, but changes to the entity here are tossed since ContentEntityForm::validateForm rebuilds the entity just before validation.
Looking at the BaseFieldDefinition class to see if there's a way to remove an existing constraint, but there are no API methods available to do so.


EDIT: It seems once possible approach is to extend ProfileForm, overwrite the buildEntity method to set _skipProtectedUserFieldConstraint = TRUE, and then tell core to use my forms instead. Thought a downside here is that I'm just disabling the constraint in the context of a form, but not in other contexts where the entity may be updated, like in a REST API.
Validation constraints are plugins with an alter hook: hook_validation_constraint_alter() (the hook name can be seen in \Drupal\Core\Validation\ConstraintManager::__construct()).

That means you can alter that plugin and replace it with your own class that doesn't do anything, or only under some conditions.

Note that constraint plugins are special, unlike everything else, they consist of two classes, the plugin class is just the definition and strings, and then here is a $classname . 'Validator' class that contains the actual logic. So you need two classes, first the constraint class, Drupal\yourmodule\Something and then an overriden version of the Validator as Drupal\yourmodule\SomethingValidator.