I have custom entity (component) with two fields field_area_type and field_dd_test_data. I want to add custom validation to make sure that user must enter either of two fields. I have used ConstraintValidator as suggested in different blogs. https://www.drupalwatchdog.com/volume-5/issue-2/introducing-drupal-8s-en...

I am able to validate for one field, means in validate function I get only value of one field. How can I get values of both field in validate function of ConstraintValidator? Please help me

  • You need to add a validation to the custom entity, see drupal.stackexchange.com/questions/215508/… – 4k4 May 8 '17 at 16:22
  • I have used as mentioned in drupal.stackexchange.com/questions/215508/…. But on validation, error border line added to all fields in that component entity. I just want to compare two fields in that entity and show error message to any of these two fields. thanks in advance – DDD May 9 '17 at 6:57
  • If you want to generate more user friendly error messages the Form API might be a better place, add a custom validation function to the entity form. Keep the validation on the entity level, because there might be incorrect data coming from other code than a form that you want to catch. – 4k4 May 9 '17 at 7:31
  • Finally I am able to make it work using validation constraint in one case. While validating two fields $field1 = $entity->field_optional_image_headline->value; $field2 = $entity->field_optional_image_caption->value; Case 1 : Working if($field1 != $field2) { $this->context->buildViolation($constraint->messageRequired) ->atPath('field_optional_image_headline') ->addViolation(); } Case 2 : Modified condition :- not working if($field1 == '' && $field2 != '') { //added same viloation } – DDD May 9 '17 at 11:52
  • thanks for help. it worked for me. added conditon if(isset($entity->field_optional_image_headline)) – DDD May 9 '17 at 16:21

Browse other questions tagged or ask your own question.