I'm submitting an entity programmatically through a custom, non-entity form. How can I validate the entity before submission, and report the validation errors to the user if they exist?


This code worked for me, not sure if best approach:

    $errors = $my_entity->validate();
    //see if there were any errors
    if ($errors->count() == 0) {
      //there are no validation errors, move to next step
    else {
      //there were validation errors, report them
      for($j = 0; $j < $errors->count(); $j++) {
        $error = $errors->get($j);
        //the entity field that failed validation
        $property = $error->getPropertyPath().'_my_weird_field_suffix';
        //the error message about how validation failed.
        $message = $error->getMessage();
        $form_state->setErrorByName($property, $message);

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.