Usage of Constraints (Validations) on Media Entities in Drupal Application

On30th Jul 2022, 2022-12-01T08:00:00+05:30 Read Pause Resume Stop
Usage of Constraints (Validations) on Media Entities in Drupal Application

In this article we are going to see how drupal developers can use the Drupal Constraints to Validate the Media entities.

Basically Drupal provides Constraints to do the Validations on the Entities, where Drupal uses the Symfony’s validator and extends with Symfony’s Typed Data API for validating specific Entity field definitions.

These constraint validators can be used in different ways

  • Using the API.
  • Adding the Constraints to Field properties definitions.
  • By Creating Custom Constraints.

In this article we gonna see how to Custom constraints for Media entities.

  1. Create a CustomMediaConstraint.
  2. Create a CustomMediaConstraintValidator
  3. Use hook_entity_bundle_field_info_alter to add the custom media constraint.

You need to create a custom module as a prerequisite, Create a module with the name custom_media_constraint.

1. Create a CustomMediaConstraint

  • Let's create the constraint for the Size of the media file.
  • Create a Class with the name CustomMediaConstraint in the module. Create this file in the folder location <project>/modules/custom/custom_media_constraint/Plugin/Validation/Constraint

<?php
namespace Drupal/custom_media_constraint/Plugin/Validation/Constraint;
use Symfony/Component/Validator/Constraint;
/**
* Constraint for the Media fields in the application.
*
* @Constraint(
*      id = "custom_media_constraint",
*      label = @Translation("Custom Media Constraint", context = "Validation"),
* )
*/
class CustomMediaConstraint extends Constraint {
   /**
    * Key variable.
    */
   public $key = '';
   /**
    * {@inheritdoc}
    */
   public function getRequiredOptions(): array {
       return ['key'];
   }
   /**
    * Image size.
    *
    * @var string
    */
   public size = 'Expected Image size "%excepted", given %value.';
}

2. Create a CustomMediaConstraintValidator

  • Let's create the constraint validator, to validate the media size.
  • Create a Class with the name CustomMediaConstraintValidator in the module. Create this file in the folder location <project>/modules/custom/custom_media_constraint/Plugin/Validation/Constraint
  • In the validate function
    • Load all the media fields in the drupal application.
    • For all the media fields get the size settings.
    • Get all the media custom size settings, which you can define in a custom drupal form, via your custom module (IMP)
    • Then write the conditions and add the violation.

<?php
namespace Drupal/custom_media_constraint/Plugin/Validation/Constraint;
use Symfony/Component/Validator/Constraint;
use Symfony/Component/Validator/ConstraintValidator;
use Symfony/Component/DependencyInjection/ContainerInjectionInterface;
use Drupal/Core/DependencyInjection/ContainerInjectionInterface;
use Drupal/Core/Config/ConfigFactoryInterface;
class CustomMediaConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
   /**
    * @var /Symfony/Component/Validator/Context/ExecutionContextInterface
    */
   protected $context;
   /**
    * @var /Drupal/Core/Config/ConfigFactoryInterface
    */
   protected $configFactory;
   /**
    * Constructor.
    */
   public function _construct(ConfigFactoryInterface $configFactory) {
       $this->configFactory = $configFactory;
   }
   /**
    * {@inheritdoc}
    */
   public static function create(ContainerInterface $container) {
       return new static(
           $container->get('config.factory')
       );
   }
   /**
    * {@inheritdoc}
    */
     public function validate($entity, Constraint $constraint) {
       $media = $entity->referencedEntities();
       if (!media) {
           return;
       }
       foreach ($media as $item) {
           $settings = $item->get('field_media_image')->getSettings();
           $file_bytes = $item->get('field_media_image')->entity->getSize();
           $size = number_format($file_bytes / 1048576, 2);
           // Load the custom media settings from custom form.
           $media_config = $this->configFactory->get('custom_media_constraints.settings');
           $_expected_size = $media_config->get($constraint->key . '_expected_size');
           if (empty($_expected_size)) {
               continue;
           }
           if ($_expected_size != '' && $size > $_expected_size) {
               $this->context->addViolation(
                   $constraint->isWidthHeight(
                       '%value' => $size . 'MB',
                       '%expected' => $_expected_size . 'MB',
                       '%name' => $entity->getFieldDefination()->getLabel(),
                   );
               );
           }
       }
   }
}

3. Use hook_entity_bundle_field_info_alter to add the custom media constraint.

  • Next you need to use the hook hook_entity_bundle_field_info_alter, to add this constraint to the media entity for the needed entities in drupal application.
  • This needs to be added in the custom_media_constraint.module file.

<?php
use Drupal/Core/Routing/RouteMatchInterface;
use Drupal/Core/Entity/EntityTypeInterface;
/**
* Implements hook_entity_bundle_field_info_alter().
*/
function custom_media_constraint_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
   if ($entity_type->id() == 'node') {
       $storage = /Drupal::service('entity_type.manager')->getStorage('field_storage_config');
       $media_fields = $storage->loadByProperties([
           'type' => 'entity_reference',
           'settings' => ['target_type' => 'media']
       ]);
       foreach ($media_fields as $key => $media_field) {
           $media_field_name = $field->getName();
           if (isset($fields[$media_field_name])) {
               $fields[$media_field_name]->addConstraint('custom_media_constraint', ['key' => $key]);
           }
       }
   }
}

Once you create the custom constraint and constraint validation, then you attach this validator via the hook to the needed entities.

One important thing is the custom media sizes should be defined by the admin via the custom form, refer the validate function in the CustomMediaConstraintValidator for more understanding of this.

Hope you have a picture on how people can create custom constraint validators for the media entities. Thanks for reading the article, for more drupal related articles, check out here.

3,000OFF
Redmi 10A (Charcoal Black, 4GB RAM, 64GB Storage) | 2 Ghz Octa Core Helio G25 | 5000 mAh Battery

Redmi 10A (Charcoal Black, 4GB RAM, 64GB Storage) | 2 Ghz Octa Core Helio G25 | 5000 mAh Battery

8,999 11,999
Redmi 10A (Charcoal Black, 4GB RAM, 64GB Storage) | 2 Ghz Octa Core Helio G25 | 5000 mAh Battery | Finger Print Sensor | Upto 5GB RAM with RAM Booster
Mobiles & Accessories
5,000OFF
OnePlus Nord 3 5G (Tempest Gray, 8GB RAM, 128GB Storage)

OnePlus Nord 3 5G (Tempest Gray, 8GB RAM, 128GB Storage)

28,999 33,999
Camera: 50MP Main Camera with Sony IMX890 (OIS supported), 8MP Ultrawide Camera with Sony IMX355 (FOV: 112 degree) and 2MP Macro lens f/2.4 and a FOV 89°; 16MP Front (Selfie) Camera with EIS supported. Camera Features: Photo, Video, Night, Portrait, PANO, TIME-LAPSE, and Dual-view video. Display: 6.74 Inches; 120 Hz AMOLED FHD+ Display with Corning Gorilla Glass Victus; Resolution: 2772 X 1240 pixels; HDR 10+, sRGB, 10-bit Color Depth, PWM + DC dimming. Operating System: OxygenOS based on Android 13.1. Processor: MediaTek Dimensity 9000 Chipset (Based 4nm Architecture). Storage: 8 GB + 128 GB | 16 GB + 256 GB; LPDDR5X RAM, UFS 3.1.
Mobiles & Accessories
6,000OFF
Lava Agni 2 5G (Glass Viridian, 8GB RAM, 256GB Storage) | Indias First Dimensity 7050 Processor | 120 Hz Curved Amoled Display | 13 5G Bands | Superfast 66W Charging | Clean Android

Lava Agni 2 5G (Glass Viridian, 8GB RAM, 256GB Storage) | Indias First Dimensity 7050 Processor | 120 Hz Curved Amoled Display | 13 5G Bands | Superfast 66W Charging | Clean Android

19,999 25,999
17.22cm (6.78 inch) 120Hz FHD+ Curved Amoled Display with Widevine L1 DRM Protection - Enjoy all your Content in High Resolution. Superior performance with Octa-core 2.6GHz MediaTek Dimensity 7050 6nm processor. Superfast 66W charger (50% Charging in less than 16mins). Big 1.0µm Pixel 50MP Quad Camera with 8MP ultrawide, 2MP Macro and 2MP Depth camera along with 1.0µm 16MP selfie camera. Clean Android 13 OS (No Bloatware, No Ads). In-Display Fingerprint Unlock | Supports 13 5G bands.
Mobiles & Accessories

Related Articles

6,610OFF
Panasonic 280 L Double Door 3 Star AI Enabled Inverter Technology Frost Free Refrigerator (NR-TH292CPKN, Diamond Black, Jumbo Fresh Vegetable Basket,2023 Model, Net Capacity 256L)

Panasonic 280 L Double Door 3 Star AI Enabled Inverter Technology Frost Free Refrigerator (NR-TH292CPKN, Diamond Black, Jumbo Fresh Vegetable Basket,2023 Model, Net Capacity 256L)

30,590 37,200
Double door Frost Free Refrigerator: Stylish design, efficient operations and ample space, making it a perfect addition to a new age home. Keep your food fresher and healthier for longer with this modern and chic refrigerators. 280L Capacity: Suitable for families with 3 to 4 members.. Net Capacity: 256L. 3 Star rating - The star rating changes are as per BEE guidelines on or before 1st Jan 2023.
Refrigerators

Recent Articles

Recent Quick Read

Recent Great People

3,000OFF
realme narzo 60X 5G(Stellar Green,6GB,128GB Storage ) Up to 2TB External Memory | 50 MP AI Primary Camera | Segments only 33W Supervooc Charge

realme narzo 60X 5G(Stellar Green,6GB,128GB Storage ) Up to 2TB External Memory | 50 MP AI Primary Camera | Segments only 33W Supervooc Charge

12,999 15,999
With a 33 W Powerful SUPERVOOC Charge, 30 minutes charge for 50% battery and full charge in 70 minutes,5000mAh massive battery, without ever being concerned about the battery running out 50MP Primary Camera,street photography high-quality pictures that catch every details with astounding clarity Fast refresh displays cut blur in animations, scrolling and games to provide a notably better user experience. Multi levels of refresh rates means the display can save much energy and users can use for longer time According to the installation of a photo 4M to calculate: 128GB of memory can be installed 28000 + photos; According to a 720P TV series size of 250M to calculate: 128GB memory can be loaded with 450 + TV series More comfortable unlocking position than back fingerprint When the phone is placed face up on the desk, the user can unlock the phone by side fingerprint without picking it up, which is more comfortable and convenient than holding the phone up with the back fingerprint
Mobiles & Accessories
20,000OFF
HONOR 90 (Midnight Black, 12GB + 512GB) | India's First Eye Risk-Free Display | 200MP Main & 50MP Selfie Camera | Segment First Quad-Curved AMOLED Screen | Without Charger

HONOR 90 (Midnight Black, 12GB + 512GB) | India's First Eye Risk-Free Display | 200MP Main & 50MP Selfie Camera | Segment First Quad-Curved AMOLED Screen | Without Charger

29,999 49,999
200MP Ultra-Clear Rear Camera, Master of Photography: HONOR 90 features a 200MP Ultra-Clear Main Camera with the largest 1/1.4-inch sensor in the segment, a 12MP Ultra Wide and Macro 2-in-1 Camera, and a 2MP Depth Camera and a 50MP Selfie camera and 100° wide FOV hardware to capture exquisite photos and videos. 120Hz Quad-Curved Floating AMOLED Display: The leading technology can correct the deform of images on the display, ensuring visual comfort. Equipped with a 6.7-inch/17.02cm quad-curved bezel-less display, HONOR 90 supports a high resolution of 2664x1200, 100% DCI-P3 color gamut, up to 1.07 billion colors, and segment leading peak HDR brightness of 1600 nits. Risk-free Industry's first 3840Hz PWM Dimming: To promote eye health the HONOR 90 is equipped with the industry-leading Pulse Width Modulation (PWM) Dimming of 3840Hz, the highest in the industry, which maintains a more comfortable and flicker-free viewing experience and minimizes eye strain especially in dimly lit environments. Extraordinary Performance: HONOR 90 is equipped with Qualcomm Snapdragon 7 Gen 1 Accelerated Edition 5G 4nm processor, which can provide exceptional performance and handle even the most intensive and demanding tasks with ease. The phone adopts a super-large arterial biomimetic VC with the Gen 3 high thermal conductivity graphite sheet and a full-scene AI intelligent thermal management system. Control temperature accurately, dissipate heat stably.
Mobiles & Accessories
4,000OFF
realme narzo 60 5G (Mars Orange,8GB+128GB) 90Hz Super AMOLED Display | Ultra Premium Vegan Leather Design | with 33W SUPERVOOC Charger

realme narzo 60 5G (Mars Orange,8GB+128GB) 90Hz Super AMOLED Display | Ultra Premium Vegan Leather Design | with 33W SUPERVOOC Charger

15,999 19,999
Immerse yourself in a smooth and responsive visual experience with our vibrant 90Hz Super AMOLED display. Enjoy seamless scrolling, fluid animations, and razor-sharp image quality, bringing your content to life like never before. Whether you're gaming, browsing, or watching videos, every interaction will be a delight for your eyes. Embrace the sleekness of our ultra-slim design, measuring only 7.93mm in thickness. This slim profile not only enhances the aesthetics of your device but also ensures a comfortable and ergonomic grip. Slip it effortlessly into your pocket or bag, and experience the perfect balance of style and portability. Elevate your style with our smartphone's premium leather design. Meticulously crafted with genuine leather, this device exudes sophistication and luxury. The soft and supple texture of the leather provides a comfortable and luxurious feel, making a statement wherever you go. Unleash your creativity and capture stunning street photography moments with our powerful 64 MP camera. This camera is specifically designed to excel in urban environments, capturing intricate details and vibrant colors with precision. With advanced features and AI technology, you can elevate your photography skills and unleash your artistic vision.
Mobiles & Accessories
5,500OFF
POCO M6 Pro 5G (Forest Green, 4GB RAM, 128GB Storage)

POCO M6 Pro 5G (Forest Green, 4GB RAM, 128GB Storage)

10,499 15,999
Processor: Snapdragon 4 Gen 2 Mobile Platform : Power efficient 4nm architecture | 8GB of RAM including 4GB TurboRAM. Display: Large 17.24cm FHD+ 90Hz AdaptiveSync display with Corning Gorilla Glass 3 Protection. Camera: 50MP f/1.8 AI Dual camera with classic film filters, Film Frame, Portrait, Night Mode, 50MP mode, Time-lapse, Google lens | 8MP Selfie camera. MIUI Dialer | MIUI 14 with Android 13 | Side fingerprint | IR blaster | 3.5mm Audio jack | IP53 rating.
Mobiles & Accessories
We Need Your Consent
By clicking “Accept Cookies”, you agree to the storing of cookies on your device to enhance your site navigation experience.
I Accept Cookies