Drupal - Require field on publish only

Simply add a validation on the entity level, then you have easy access to the whole entity.

You can see an example in content_translation_entity_type_alter():

$entity_type->addConstraint('ContentTranslationSynchronizedFields');

You register a constraint like any plugin, the only special thing is that there are two classes, the plugin class itself doesn't really have anything except the messages usually while the validator has the logic, in the validate method::

ContentTranslationSynchronizedFieldsConstraint ContentTranslationSynchronizedFieldsConstraintValidator::validate

Once you have that, writing the actual logic is often much easier, because you have a fully built entity object to work with and don't have to wory about getting the raw values from the form values. And as a bonus, it will also automatically work for REST/json_api and any other module that uses the validate() method to ensure that created entities are valid before saving them.

For example, verifying that an image field is not empty when the entity is published:

if ($entity->isPublished() && $entity->hasField('field_image') && $entity->get('field_image')->isEmpty()) {
  // add a violation...
}

Tags:

Forms

Entities

8