Skip to content
Snippets Groups Projects
Verified Commit 2be93630 authored by Dave Long's avatar Dave Long
Browse files

Issue #3508822 by penyaskito: Property constraints validation adding errors to...

Issue #3508822 by penyaskito: Property constraints validation adding errors to the field element instead of just the property
parent 45a1a667
No related branches found
No related tags found
1 merge request!11983Issue #3521857 by jwilson3: Update file type icons to use SVG
Pipeline #475106 passed with warnings
Pipeline: drupal

#475119

    Pipeline: drupal

    #475114

      Pipeline: drupal

      #475109

        ......@@ -12,6 +12,7 @@
        use Drupal\file\Entity\File;
        use Drupal\file\Plugin\Field\FieldWidget\FileWidget;
        use Drupal\image\Entity\ImageStyle;
        use Symfony\Component\Validator\ConstraintViolationInterface;
        /**
        * Plugin implementation of the 'image_image' widget.
        ......@@ -344,4 +345,14 @@ public function onDependencyRemoval(array $dependencies) {
        return $changed;
        }
        /**
        * {@inheritdoc}
        */
        public function errorElement(array $element, ConstraintViolationInterface $error, array $form, FormStateInterface $form_state) {
        $element = parent::errorElement($element, $error, $form, $form_state);
        $property_path_array = explode('.', $error->getPropertyPath());
        return ($element === FALSE) ? FALSE : $element[$property_path_array[1]];
        }
        }
        core/modules/image/tests/fixtures/example_1.jpeg

        8.67 KiB

        name: 'Image field property constraint validation'
        type: module
        description: 'Testing module with a constraint for image alt property'
        package: Testing
        version: VERSION
        <?php
        declare(strict_types=1);
        namespace Drupal\image_field_property_constraint_validation\Hook;
        use Drupal\Core\Entity\EntityTypeInterface;
        use Drupal\Core\Hook\Attribute\Hook;
        /**
        * Hook implementations for image_field_property_constraint_validation.
        */
        class ImagePropertyConstraintValidationHooks {
        /**
        * Implements hook_entity_bundle_field_info_alter().
        */
        #[Hook('entity_bundle_field_info_alter')]
        public function entityBundleFieldInfoAlter(&$fields, EntityTypeInterface $entity_type, $bundle): void {
        if ($entity_type->id() == 'node' && !empty($fields['field_image'])) {
        /** @var \Drupal\field\Entity\FieldConfig[] $fields */
        $fields['field_image']->addPropertyConstraints('alt', ['AltTextContainsLlamas' => []]);
        }
        }
        }
        <?php
        declare(strict_types=1);
        namespace Drupal\image_field_property_constraint_validation\Plugin\Validation\Constraint;
        use Drupal\Core\StringTranslation\TranslatableMarkup;
        use Drupal\Core\Validation\Attribute\Constraint;
        use Symfony\Component\Validator\Constraint as SymfonyConstraint;
        /**
        * Provides a Contains Llamas constraint.
        */
        #[Constraint(
        id: 'AltTextContainsLlamas',
        label: new TranslatableMarkup('Contains Llamas', options: ['context' => 'Validation'])
        )]
        final class AltTextContainsLlamasConstraint extends SymfonyConstraint {
        /**
        * The error message.
        *
        * @var string
        */
        public string $message = 'Alternative text must contain some llamas.';
        }
        <?php
        declare(strict_types=1);
        namespace Drupal\image_field_property_constraint_validation\Plugin\Validation\Constraint;
        use Symfony\Component\Validator\Constraint;
        use Symfony\Component\Validator\ConstraintValidator;
        /**
        * Validates the alt text contains llamas.
        */
        final class AltTextContainsLlamasConstraintValidator extends ConstraintValidator {
        /**
        * {@inheritdoc}
        */
        public function validate(mixed $value, Constraint $constraint): void {
        if (is_string($value) && !str_contains(strtolower($value), 'llamas')) {
        $this->context->buildViolation($constraint->message)
        ->setInvalidValue($value)
        ->addViolation();
        }
        }
        }
        <?php
        declare(strict_types=1);
        namespace Drupal\Tests\image\Functional;
        /**
        * Tests the image field widget validation.
        *
        * @group image
        */
        class ImageFieldWidgetValidationTest extends ImageFieldTestBase {
        /**
        * {@inheritdoc}
        */
        protected $defaultTheme = 'stark';
        /**
        * {@inheritdoc}
        */
        protected static $modules = [
        'image_field_property_constraint_validation',
        ];
        /**
        * Tests file widget element.
        */
        public function testWidgetElementValidation(): void {
        $page = $this->getSession()->getPage();
        // Check for image widget in add/node/article page
        $field_name = 'field_image';
        $field_settings = [
        'description' => 'Image test description',
        'alt_field' => 1,
        'alt_field_required' => 0,
        'title_field' => 1,
        'title_field_required' => 0,
        ];
        $this->createImageField($field_name, 'node', 'article', [], $field_settings, [], [], 'Image');
        $this->drupalGet('node/add/article');
        // Verify that the image field widget is found on add/node page.
        $this->assertSession()->elementExists('xpath', '//div[contains(@class, "field--widget-image-image")]');
        // Attach an image.
        $image_media_name = 'example_1.jpeg';
        $page->attachFileToField('files[field_image_0]', $this->root . '/core/modules/image/tests/fixtures/' . $image_media_name);
        $page->pressButton('Save');
        // Alt is marked as errored.
        $altElement = $this->assertSession()->elementExists('css', 'input[data-drupal-selector="edit-field-image-0-alt"]');
        $this->assertTrue(str_contains($altElement->getAttribute('class'), 'error'));
        // Title is not marked as errored
        $titleElement = $this->assertSession()->elementExists('css', 'input[data-drupal-selector="edit-field-image-0-title"]');
        $this->assertFalse(str_contains($titleElement->getAttribute('class'), 'error'));
        }
        }
        0% Loading or .
        You are about to add 0 people to the discussion. Proceed with caution.
        Please register or to comment