4

I have a field in a content entity that is required if another field in it is checked, otherwise it can be blank.

My guess is that I'd need to make some kind of Validation Constraint Plugin for this - is there an easier way to do this, or a module where something like this already exists?

2

That sounds like a job for Drupal's Form API states.

Just add a hook_form_alter similar to this, in a custom module:

function MYMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'FORM_ID_TO_ALTER') {
    $form['OPTIONALLY_REQUIRED_FIELD']['#states'] = array(
      'visible' => array(
        ':input[name="CHECKBOX_NAME"]' => array('checked' => 'checked'),
      ),
      'required' => array(
        ':input[name="CHECKBOX_NAME"]' => array('checked' => 'checked'),
      ),
    );
  }
}
2

The form_alter() solution will only work when you're using a form to save the entity, so I believe that the answer is not the correct one. Here's how you do it with Drupal's Entity Validation API:

Create a constraint and add it to the entity type instead of adding it to a field. Ex:

## See hook_entity_type_alter().
function custom_validation_entity_type_alter(array &$entity_types) {
  if (isset($entity_types['node'])) {
    $entity_types['node']->addConstraint('ConstraintName');
  }
}

Next, in your ConstraintValidator::validate() method, you will get receive the entity as the first argument and you can perform the validation. Here's a code sample from the same article.

0

Managed to get this working a different way, though Change G's way looks a lot simpler. If you want to go pure entity this way worked for me.

I created an entity validation plugin, based on this blog article (https://www.drupalwatchdog.com/volume-5/issue-2/introducing-drupal-8s-entity-validation-api). The comment module in core modules has a working example of this.

One issue I ran into is that the comment CommentNameContraintValidator class declares a $context class property; I can't figure out how this works for that class, but when creating my own it overrode the $context class property in the ConstraintValidator abstract class you need to extend from. When I removed the $context class property, it correctly used the parent $context class property and worked.

My guess is that it has to do with the ContainerInjectionInterface, which the CommentNameConstraintValidator implements and I didn't. I've stopped digging for now though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.