You are here

public static function ImageCrop::cropRequired in Image Widget Crop 8.2

Form element validation handler for crop widget elements.

Parameters

array $element: All form elements without crop properties.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

See also

ImageCrop::getCropFormElement()

File

src/Element/ImageCrop.php, line 455

Class

ImageCrop
Provides a form element for crop.

Namespace

Drupal\image_widget_crop\Element

Code

public static function cropRequired(array $element, FormStateInterface $form_state) {
  if (!static::hasCropRequired($element)) {
    return;
  }
  $required_crops = [];
  foreach ($element['#crop_types_required'] as $crop_type_id) {
    $crop_applied = $form_state
      ->getValue($element['#parents'])['crop_wrapper'][$crop_type_id]['crop_container']['values']['crop_applied'];
    $action_button = $form_state
      ->getTriggeringElement()['#value'];
    $operation = $action_button instanceof TranslatableMarkup ? $action_button
      ->getUntranslatedString() : $action_button;
    if (self::fileTriggered($form_state) && self::requiredApplicable($crop_applied, $operation)) {

      /** @var \Drupal\crop\Entity\CropType $crop_type */
      $crop_type = \Drupal::entityTypeManager()
        ->getStorage('crop_type')
        ->load($crop_type_id);
      $required_crops[] = $crop_type
        ->label();
    }
  }
  if (!empty($required_crops)) {
    $form_state
      ->setError($element, \Drupal::translation()
      ->formatPlural(count($required_crops), '@crop_required is required.', '@crops_required are required.', [
      "@crop_required" => current($required_crops),
      "@crops_required" => implode(', ', $required_crops),
    ]));
  }
}