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

ByKarthik Kumar D Kon30th 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.

1,600OFF
Xtore Beautiful Finish Uniquely Hand Crafted Home Dcor African Tribal Women Art Piece - (Set of 3, Multicolour), Resin

Xtore Beautiful Finish Uniquely Hand Crafted Home Dcor African Tribal Women Art Piece - (Set of 3, Multicolour), Resin

899 2,499
These uniquely hand crafted and painted resin black African tribal lady figure make an excellent compliment to any home/office decor. It makes a great display for culture/tradition appreciation events and a perfect gift for your loved ones. Unique and Rare - Hand Painted and Hand Crafted.
Home & Decor
13,000OFF
OnePlus 108 cm (43 inches) Y Series 4K Ultra HD Smart Android LED TV 43Y1S Pro (Black)

OnePlus 108 cm (43 inches) Y Series 4K Ultra HD Smart Android LED TV 43Y1S Pro (Black)

26,999 39,999
Resolution : 4K Ultra HD (3840x2160) | Refresh Rate : 60 Hertz. Connectivity: 3 HDMI ports to connect set top box, Blu Ray players, gaming console | 2 USB ports to connect hard drives and other USB devices | Dual-band Wi-Fi Sound : 24 Watts Output | Dolby Audio | Dolby Atmos Decoding. Smart TV features: Android TV | OnePlus Connect Ecosystem| Google Assistant | Chromecast, Miracast, DLNA | Auto Low Latency Mode | Supported Apps : Netflix, Youtube, Prime Video, Hotstar, SonyLiv, Hungama, JioCinema, Zee5, Eros Now, Oxygen Play.
Televisions
7,000OFF
OnePlus 80 cm (32 inches) Y Series HD Ready LED Smart Android TV 32Y1 (Black)

OnePlus 80 cm (32 inches) Y Series HD Ready LED Smart Android TV 32Y1 (Black)

12,999 19,999
Resolution: HD Ready (1366x768) | Refresh Rate: 60 hertz. Connectivity: 2 HDMI ports to connect set top box, Blu Ray players, gaming console | 2 USB ports to connect hard drives and other USB devices, Dimensions(TV With Stand) - 71.3cm x 20cm x 46.9cm | VESA Hole Pitch - 20cm x 20cm. Sound : 20 Watts Output | Dolby Audio. Smart TV Features: Android TV 9.0 | OnePlus Connect | Google Assistant | Play Store | Chromecast | Shared Album | Supported Apps : Netflix, YouTube, Prime video | Content Calendar | OxygenPlay. Display : LED Panel | Noise Reduction | Colour Space Mapping |Dynamic Contrast | Anti-Aliasing | DCI-P3 93% colour gamut | Gamma Engine | Design: Bezel-less | Screen/Body Ratio = 91.4%. Warranty Information: 1 year comprehensive warranty and additional 1 year on panel provided by the manufacturer from date of purchase.
Televisions

Related Articles

1,031OFF
eCraftIndia Ganesh Deepak with Bell Brass Wall Hanging (11 cm x 8 cm x 24 cm, Brown)

eCraftIndia Ganesh Deepak with Bell Brass Wall Hanging (11 cm x 8 cm x 24 cm, Brown)

968 1,999
1 Brass Ganeshs wall hanging Deepak with bell and Dancing Ganesha. Don't wash, use dry/wet cotton cloth to remove dirt.
Home & Decor

Recent Articles

Recent Quick Read

Recent Great People

32,991OFF
Hisense 139 cm (55 inches) Tornado 2.0 Series 4K Ultra HD Smart LED Google TV 55A7H (Silver)

Hisense 139 cm (55 inches) Tornado 2.0 Series 4K Ultra HD Smart LED Google TV 55A7H (Silver)

36,999 69,990
Resolution : 4K Ultra HD (3840x2160) | Refresh Rate : 60 Hertz | 178 Degree wide viewing angle. Connectivity: 3 HDMI ports to connect set top box, Blu Ray players, gaming console (HDMI 1 eARC supported) | 2 USB ports to connect hard drives and other USB devices | Dual-band Wi-Fi | Bluetooth 5.1. Sound : 102 Watts Output | JBL 6 Speakers System | Dolby Atmos for remarkable sound quality. Smart TV features: Google TV with Watchlist | Google Play Store | Google Assistant | Chromecast, Miracast, DLNA, Airplay | Auto Low Latency Mode for VRR | Supported Apps : Netflix, Youtube, Prime Video, Hotstar, SonyLiv, Hungama, JioCinema, Zee5, Eros Now. Display :10 bit Panel | Bezel-less Floating Display Design | ALLM | Decoding of Dolby Vision, HDR10, HLG | 1 Billion Colours | MEMC. Warranty Information: 2 Year Comprehensive Warranty on product provided by Hisense from date of purchase.. Installation: For requesting installation/wall mounting/demo of this product once delivered, please directly call Hisense Support for assistance (Please visit Hisense Website for Toll Free Numbers) and provide product's model name and seller's details mentioned on your invoice. The service center will allot you a convenient slot for the service. Easy Returns: This product is eligible for replacement within 10 days of delivery in case of any product defects, damage or features not matching the description.
Televisions
26,991OFF
Hisense 139 cm (55 inches) Bezelless Series 4K Ultra HD Smart LED Google TV 55A6H (Black)

Hisense 139 cm (55 inches) Bezelless Series 4K Ultra HD Smart LED Google TV 55A6H (Black)

32,999 59,990
Resolution : 4K Ultra HD (3840x2160) | Refresh Rate : 60 Hertz | 178 Degree wide viewing angle. Connectivity: 3 HDMI ports to connect set top box, Blu Ray players, gaming console | 2 USB ports to connect hard drives and other USB devices | Dual-band Wi-Fi | Bluetooth 5.1. Sound : 24 Watts Output | Dolby Atmos | Dolby Digital. Smart TV features: Google TV | Watchlist | Google Assistant | Far Field Vioce Control | Chromecast, Miracast, DLNA | Auto Low Latency Mode for VRR | Supported Apps : Netflix, Youtube, Prime Video, Hotstar, SonyLiv, Hungama, JioCinema, Zee5, Eros Now. Display :10 bit Panel | Bezel-less Floating Display Design | ALLM | Decoding of Dolby Vision, HDR10, HLG | 1 Billion Colours | MEMC.
Televisions
350OFF
Amazon Brand - Solimo Slim Stainless Steel Water Bottle, Set of 3, 1 L Each

Amazon Brand - Solimo Slim Stainless Steel Water Bottle, Set of 3, 1 L Each

649 999
Stainless Steel water bottle set for home and office use. Made using high quality stainless steel for added durability and long life. Made from 100% food grade materials to be safe for everyday usage. Features a spill-proof design; has a snug fitting lid for easy usage and prevention of leaks. Ergonomic design for comfortable grip and rust free body. Ideal for storing water, iced tea, juices, shakes and more. Dimensions: L x W x H: 7.3 x 7.3 x 26 cm. Package Contents:- Solimo Stainless Steel Water Bottle Set of 3, Weight: 200 gm each, Colour: Silver, Capacity: 1 litre each.
Kitchen & Dining
1,272OFF
Bajaj Rex 500W Mixer Grinder, Purple

Bajaj Rex 500W Mixer Grinder, Purple

2,278 3,550
Wattage : 500 W, Voltage: 230V~50 Hz: Revolution: 20,000 RPM. Powerful 500W Titan Motor with Radio Knob: Easy selection of Speed. 2-in-1 Blade: The dry grinding jar can be used for dry and chutney grinding both. Product warranty by Bajaj - 2 Years. T&C Applied. Pulse Mode: Used for mixing and grinding without stopping your mixie. Perfect to mince chicken , get bread crumps, small puree and making lump free gravies.
Kitchen Appliances
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