3 namespace Drupal\image_widget_crop\Plugin\Field\FieldWidget;
5 use Drupal\Core\Ajax\AjaxResponse;
6 use Drupal\Core\Ajax\ReplaceCommand;
7 use Drupal\Core\Config\ConfigFactoryInterface;
8 use Drupal\Core\Config\Entity\ConfigEntityStorageInterface;
9 use Drupal\Core\Entity\EntityStorageInterface;
10 use Drupal\Core\Field\FieldDefinitionInterface;
11 use Drupal\Core\Field\FieldItemListInterface;
12 use Drupal\Core\Form\FormStateInterface;
14 use Drupal\Core\Render\ElementInfoManagerInterface;
15 use Drupal\image\Plugin\Field\FieldWidget\ImageWidget;
16 use Drupal\image_widget_crop\ImageWidgetCropInterface;
17 use Symfony\Component\DependencyInjection\ContainerInterface;
18 use Drupal\crop\Entity\CropType;
19 use Drupal\Core\Render\Element\Select;
22 * Plugin implementation of the 'image_widget_crop' widget.
25 * id = "image_widget_crop",
26 * label = @Translation("ImageWidget crop"),
32 class ImageCropWidget extends ImageWidget {
35 * Instance of ImageWidgetCropManager object.
37 * @var \Drupal\image_widget_crop\ImageWidgetCropInterface
39 protected $imageWidgetCropManager;
42 * The image style storage.
44 * @var \Drupal\image\ImageStyleStorageInterface
46 protected $imageStyleStorage;
49 * The crop type storage.
51 * @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface
53 protected $cropTypeStorage;
58 * Subclasses should use the self::config() method, which may be overridden to
59 * address specific needs when loading config, rather than this property
60 * directly. See \Drupal\Core\Form\ConfigFormBase::config() for an example of
63 * @var \Drupal\Core\Config\ConfigFactoryInterface
65 protected $configFactory;
70 public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, ElementInfoManagerInterface $element_info, ImageWidgetCropInterface $iwc_manager, EntityStorageInterface $image_style_storage, ConfigEntityStorageInterface $crop_type_storage, ConfigFactoryInterface $config_factory) {
71 parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings, $element_info);
72 $this->imageWidgetCropManager = $iwc_manager;
73 $this->imageStyleStorage = $image_style_storage;
74 $this->cropTypeStorage = $crop_type_storage;
75 $this->configFactory = $config_factory;
81 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
85 $configuration['field_definition'],
86 $configuration['settings'],
87 $configuration['third_party_settings'],
88 $container->get('element_info'),
89 $container->get('image_widget_crop.manager'),
90 $container->get('entity_type.manager')->getStorage('image_style'),
91 $container->get('entity_type.manager')->getStorage('crop_type'),
92 $container->get('config.factory')
99 public static function defaultSettings() {
101 'crop_preview_image_style' => 'crop_thumbnail',
103 'crop_types_required' => [],
104 'show_crop_area' => FALSE,
105 'show_default_crop' => TRUE,
106 'warn_multiple_usages' => TRUE,
107 ] + parent::defaultSettings();
111 * Form API callback: Processes a crop_image field element.
113 * Expands the image_image type to include the alt and title fields.
115 * This method is assigned as a #process callback in formElement() method.
118 * The elements with parents fields.
120 public static function process($element, FormStateInterface $form_state, $form) {
121 if ($element['#files']) {
122 foreach ($element['#files'] as $file) {
123 $element['image_crop'] = [
124 '#type' => 'image_crop',
126 '#crop_type_list' => $element['#crop_list'],
127 '#crop_preview_image_style' => $element['#crop_preview_image_style'],
128 '#show_default_crop' => $element['#show_default_crop'],
129 '#show_crop_area' => $element['#show_crop_area'],
130 '#warn_multiple_usages' => $element['#warn_multiple_usages'],
131 '#crop_types_required' => $element['#crop_types_required'],
136 return parent::process($element, $form_state, $form);
140 * Verify if the element have an image file.
142 * @param array $element
143 * A form element array containing basic properties for the widget.
144 * @param array $variables
145 * An array with all existent variables for render.
148 * The variables with width & height image informations.
150 public static function getFileImageVariables(array $element, array &$variables) {
151 // Determine image dimensions.
152 if (isset($element['#value']['width']) && isset($element['#value']['height'])) {
153 $variables['width'] = $element['#value']['width'];
154 $variables['height'] = $element['#value']['height'];
157 /** @var \Drupal\Core\Image\Image $image */
158 $image = \Drupal::service('image.factory')->get($variables['uri']);
159 if ($image->isValid()) {
160 $variables['width'] = $image->getWidth();
161 $variables['height'] = $image->getHeight();
164 $variables['width'] = $variables['height'] = NULL;
174 public function settingsForm(array $form, FormStateInterface $form_state) {
175 if (!$crop_types_options = $this->imageWidgetCropManager->getAvailableCropType(CropType::getCropTypeNames())) {
176 $element['message'] = [
177 '#type' => 'container',
178 '#markup' => $this->t('No image style using the "manual crop" effect found. Please first go @link and attach the "manual crop" effect and then return to configure the field widget settings.', ['@link' => Link::createFromRoute('configure one here', 'entity.image_style.collection')->toString()]),
180 'class' => ['messages messages--error'],
184 // Stop process and display error message,
185 // if any available Image Style is set.
189 $element = parent::settingsForm($form, $form_state);
190 $element['crop_preview_image_style'] = [
191 '#title' => $this->t('Crop preview image style'),
193 '#options' => image_style_options(FALSE),
194 '#default_value' => $this->getSetting('crop_preview_image_style'),
195 '#description' => $this->t('The preview image will be shown while editing the content.'),
199 $element['crop_list'] = [
200 '#title' => $this->t('Crop Type'),
202 '#options' => $crop_types_options,
203 '#default_value' => $this->getSetting('crop_list'),
206 '#description' => $this->t('The type of crop to apply to your image. If your Crop Type not appear here, set an image style use your Crop Type'),
209 'callback' => [static::class, 'updateCropTypeRequiredOptions'],
214 $element['crop_types_required'] = [
215 '#title' => $this->t('Required crop types'),
217 '#options' => $crop_types_options,
218 '#default_value' => $this->getSetting('crop_types_required'),
220 '#description' => $this->t('Crop types that should be required.'),
224 $element['show_crop_area'] = [
225 '#title' => $this->t('Always expand crop area'),
226 '#type' => 'checkbox',
227 '#default_value' => $this->getSetting('show_crop_area'),
230 $element['show_default_crop'] = [
231 '#title' => $this->t('Show default crop area'),
232 '#type' => 'checkbox',
233 '#default_value' => $this->getSetting('show_default_crop'),
236 $element['warn_multiple_usages'] = [
237 '#title' => $this->t('Warn the user if the crop is used more than once.'),
238 '#type' => 'checkbox',
239 '#default_value' => $this->getSetting('warn_multiple_usages'),
242 $element['crop_types_required']['#process'] = [
243 // We mandatory to re-attach 'processSelect'.
244 [Select::class, 'processSelect'],
245 [static::class, 'processCropTypesRequired'],
252 * Render API callback: retrieve options for current form element.
254 * @param array $element
255 * An associative array containing the properties and children of the
256 * form actions container.
257 * @param \Drupal\Core\Form\FormStateInterface $form_state
258 * The current state of the form.
259 * @param array $complete_form
260 * The complete form structure.
263 * The processed element.
265 public static function processCropTypesRequired(array &$element, FormStateInterface $form_state, array &$complete_form) {
266 if (!$form_state->getTriggeringElement()) {
270 // Only display options chosen on 'crop_list',
271 // element in current form element.
272 $crop_list_form_element = self::getImageCropWidgetElement($form_state, 'crop_list');
273 if (empty($crop_list_form_element)) {
277 $crop_list_options = $crop_list_form_element['#options'];
278 $crop_list_default_value = array_flip($crop_list_form_element['#default_value']);
280 // Populate element options with crop_list selected options.
281 $element['#options'] = array_intersect_key($crop_list_options, $crop_list_default_value);
287 * Ajax callback for 'crop_list' select element.
289 * This ajax callback takes care of the following things:
290 * - Fetching selected options on the 'crop_list' element.
293 * An associative array containing the structure of the form.
294 * @param \Drupal\Core\Form\FormStateInterface $form_state
295 * The current state of the form.
297 * @return \Drupal\Core\Ajax\AjaxResponse
300 public static function updateCropTypeRequiredOptions(array $form, FormStateInterface $form_state) {
301 $response = new AjaxResponse();
302 $triggering_element = $form_state->getTriggeringElement();
303 if (isset($triggering_element['#value'])) {
304 $crop_type_required_form = self::getImageCropWidgetElement($form_state, 'crop_types_required');
305 $crop_type_required_form['#options'] = array_intersect_key($triggering_element['#options'], $triggering_element['#value']);
307 /** @var \Drupal\Core\Render\RendererInterface $renderer */
308 $renderer = \Drupal::service('renderer');
309 $output = $renderer->renderRoot($crop_type_required_form);
311 // Transform field name onto field name class.
312 $field_name_class = str_replace('_', '-', $triggering_element['#parents'][1]);
314 // Re-construct triggered crop required form element class.
315 $element_fragments = [
319 '-settings-edit-form-settings-',
320 'crop-types-required',
323 // Replace existing element with selected `crop_list` options.
324 $response->addCommand(new ReplaceCommand('.' . implode($element_fragments), $output));
331 * Return a specific of ImageCropWidget form element.
333 * @param \Drupal\Core\Form\FormStateInterface $form_state
334 * The current state of the form.
336 * Name of element needed.
339 * The form element needed by $key parameter.
341 public static function getImageCropWidgetElement(FormStateInterface $form_state, $key) {
342 $triggering_element = $form_state->getTriggeringElement();
343 $children = $triggering_element['#parents'][0];
344 $field_name = $triggering_element['#parents'][1];
345 $field_element_form = $form_state->getCompleteForm()[$children][$field_name];
347 return $field_element_form['plugin']['settings_edit_form']['settings'][$key] ?: [];
353 * @return \Drupal\Core\StringTranslation\TranslatableMarkup[]
354 * A short summary of the widget settings.
356 public function settingsSummary() {
359 $image_styles = image_style_options(FALSE);
360 // Unset possible 'No defined styles' option.
361 unset($image_styles['']);
363 $crop_list = $this->getSetting('crop_list');
364 if (empty($crop_list)) {
365 return [$this->t('No crop types selected.')];
368 $image_style_setting = $this->getSetting('preview_image_style');
369 $crop_preview = $image_styles[$this->getSetting('crop_preview_image_style')];
370 $crop_show_button = $this->getSetting('show_crop_area');
371 $show_default_crop = $this->getSetting('show_default_crop');
372 $warn_multiple_usages = $this->getSetting('warn_multiple_usages');
373 $crop_required = $this->getSetting('crop_types_required');
375 $preview[] = $this->t('Always expand crop area: @bool', ['@bool' => ($crop_show_button) ? 'Yes' : 'No']);
376 $preview[] = $this->t('Show default crop area: @bool', ['@bool' => ($show_default_crop) ? 'Yes' : 'No']);
377 $preview[] = $this->t('Warn the user if the crop is used more than once: @bool', ['@bool' => ($warn_multiple_usages) ? 'Yes' : 'No']);
379 if (isset($image_styles[$image_style_setting])) {
380 $preview[] = $this->t('Preview image style: @style', ['@style' => $image_style_setting]);
383 $preview[] = $this->t('No preview image style');
386 if (isset($crop_preview)) {
387 $preview[] = $this->t('Preview crop zone image style: @style', ['@style' => $crop_preview]);
390 if (!empty($crop_list)) {
391 $preview[] = $this->t('Crop Type used: @list', ['@list' => implode(", ", $crop_list)]);
394 if (!empty($crop_required)) {
395 $preview[] = $this->t('Required crop types : @list', ['@list' => implode(", ", $crop_required)]);
405 * The form elements for a single widget for this field.
407 public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
408 // Add properties needed by process() method.
409 $element['#crop_list'] = $this->getSetting('crop_list');
410 $element['#crop_preview_image_style'] = $this->getSetting('crop_preview_image_style');
411 $element['#show_crop_area'] = $this->getSetting('show_crop_area');
412 $element['#show_default_crop'] = $this->getSetting('show_default_crop');
413 $element['#warn_multiple_usages'] = $this->getSetting('warn_multiple_usages');
414 $element['#crop_types_required'] = $this->getSetting('crop_types_required');
416 return parent::formElement($items, $delta, $element, $form, $form_state);