Constraint Validator Issue

Created on 25 September 2024, about 2 months ago

Problem/Motivation

When adding constraint validator to form, the messages are not shown on field level.

Steps to reproduce

1. Create custom form
2. Add Constraint and ConstraintValidator
3. Confirm if messages are not shown above the form field

🐛 Bug report
Status

Active

Version

1.0

Component

Code

Created by

🇵🇭Philippines erwindaez

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @erwindaez
  • 🇧🇪Belgium dieterholvoet Brussels

    Could you provide a minimal code example? As far as I know, Constraints and ConstraintValidators are usually added to fields in hook_entity_bundle_field_info_alter() implementations. I don't know how those would be used in context of a custom form.

  • 🇵🇭Philippines erwindaez

    Hi @dieterholvoet

    For this one I think the issue is on toastify\Element\ToastifyStatusMessages, renderMessages interrupts all messages event the messages that Contstraint validator shows

     public static function renderMessages($type = NULL): array {
        if (!\Drupal::currentUser()->hasPermission('show toastify messages')) {
          return parent::renderMessages($type);
        }
    
        $render = [];
        if (isset($type)) {
          $messages = [
            $type => \Drupal::messenger()->deleteByType($type),
          ];
        }
        else {
          $messages = \Drupal::messenger()->deleteAll();
        }
    
        if ($messages) {
          // Pass the messages to Toastify.
          $render['#attached']['drupalSettings']['toastify']['messages'] = $messages;
        }
    
        return $render;
      }
    

    A sample screenshot is the current behavior on what toastify does
    https://www.drupal.org/files/issues/2024-09-26/Screenshot%202024-09-26%2...

    VS on what we expect
    https://www.drupal.org/files/issues/2024-09-26/Screenshot%202024-09-26%2...

  • 🇧🇪Belgium dieterholvoet Brussels

    Okay, but you haven't given me more information on how to reproduce the issue. See my previous comment.

  • 🇵🇭Philippines erwindaez

    Hi @dieterholvoet

    Steps on how to reproduce the issue

    1. Add constraint on your custom form field, example

     $form['my_custom_field'] = [
       '#type' => 'managed_file',
              '#upload_validators' => [
                'CustomFormat' => ['format' => $format],
              ],
    ];
    

    2. Create CustomFormatConstraint and CustomFormatConstraintValidator classes
    3. Add validate to CustomFormatConstraintValidator
    4. Test if the message from your constraint will show up

    Currently what is happening if we have invalid value to the field
    https://www.drupal.org/files/issues/2024-09-26/Screenshot%202024-09-26%2...

Production build 0.71.5 2024