I made a custom hook_alter_form to invalidate and delete a image if invalid.

php code in the .module file


 * Implements hook_form_alter() to add custom validation for image ratio.
function scouts_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // Specify the form IDs where you want to replace the validation.
  $target_form_ids = [
    // Add more form IDs as needed.

  // dpm($form_id); // print the form id at the top of the page to find the correct form id.

  // Check if the current form ID is one of the target form IDs.
  if (in_array($form_id, $target_form_ids)) {
    // Replace the file_validate_image_resolution validation function.
    $form['#validate'][] = 'force_aspect_ratio';

 * Custom validation handler to enforce image ratio.
function force_aspect_ratio($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $image_field = $form_state->getValue('field_afbeelding');

  if (!empty($image_field)) {
    // Load the file entity.
    $file = \Drupal\file\Entity\File::load($image_field[0]['fids'][0]);
    if ($file) {
      // Get the image properties.
      $image_info = getimagesize($file->getFileUri());
      $width = $image_info[0];
      $height = $image_info[1];
      $aspect_ratio = $width / $height;

      if ($aspect_ratio < 1) {
        $form_state->setErrorByName('field_afbeelding', t('Verticale foto\'s zijn lelijk, upload een horizontale.'));
        $form_state->setValue('field_afbeelding', []);

The invalidation works but not the deletion: situation_now

I want it to go back to: correct image


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.