Further changes for the Use cases on the live site.
[yaffs-website] / web / core / modules / responsive_image / src / ResponsiveImageStyleForm.php
1 <?php
2
3 namespace Drupal\responsive_image;
4
5 use Drupal\breakpoint\BreakpointManagerInterface;
6 use Drupal\Core\Entity\EntityForm;
7 use Drupal\Core\Form\FormStateInterface;
8 use Symfony\Component\DependencyInjection\ContainerInterface;
9
10 /**
11  * Form controller for the responsive image edit/add forms.
12  */
13 class ResponsiveImageStyleForm extends EntityForm {
14
15   /**
16    * The breakpoint manager.
17    *
18    * @var \Drupal\breakpoint\BreakpointManagerInterface
19    */
20   protected $breakpointManager;
21
22   /**
23    * {@inheritdoc}
24    */
25   public static function create(ContainerInterface $container) {
26     return new static(
27       $container->get('breakpoint.manager')
28     );
29   }
30
31   /**
32    * Constructs the responsive image style form.
33    *
34    * @param \Drupal\breakpoint\BreakpointManagerInterface $breakpoint_manager
35    *   The breakpoint manager.
36    */
37   public function __construct(BreakpointManagerInterface $breakpoint_manager) {
38     $this->breakpointManager = $breakpoint_manager;
39   }
40
41   /**
42    * Overrides Drupal\Core\Entity\EntityForm::form().
43    *
44    * @param array $form
45    *   A nested array form elements comprising the form.
46    * @param \Drupal\Core\Form\FormStateInterface $form_state
47    *   The current state of the form.
48    *
49    * @return array
50    *   The array containing the complete form.
51    */
52   public function form(array $form, FormStateInterface $form_state) {
53     if ($this->operation == 'duplicate') {
54       $form['#title'] = $this->t('<em>Duplicate responsive image style</em> @label', ['@label' => $this->entity->label()]);
55       $this->entity = $this->entity->createDuplicate();
56     }
57     if ($this->operation == 'edit') {
58       $form['#title'] = $this->t('<em>Edit responsive image style</em> @label', ['@label' => $this->entity->label()]);
59     }
60
61     /** @var \Drupal\responsive_image\ResponsiveImageStyleInterface $responsive_image_style */
62     $responsive_image_style = $this->entity;
63     $form['label'] = [
64       '#type' => 'textfield',
65       '#title' => $this->t('Label'),
66       '#maxlength' => 255,
67       '#default_value' => $responsive_image_style->label(),
68       '#description' => $this->t("Example: 'Hero image' or 'Author image'."),
69       '#required' => TRUE,
70     ];
71     $form['id'] = [
72       '#type' => 'machine_name',
73       '#default_value' => $responsive_image_style->id(),
74       '#machine_name' => [
75         'exists' => '\Drupal\responsive_image\Entity\ResponsiveImageStyle::load',
76         'source' => ['label'],
77       ],
78       '#disabled' => (bool) $responsive_image_style->id() && $this->operation != 'duplicate',
79     ];
80
81     $image_styles = image_style_options(TRUE);
82     $image_styles[RESPONSIVE_IMAGE_ORIGINAL_IMAGE] = $this->t('- None (original image) -');
83     $image_styles[RESPONSIVE_IMAGE_EMPTY_IMAGE] = $this->t('- empty image -');
84
85     if ((bool) $responsive_image_style->id() && $this->operation != 'duplicate') {
86       $description = $this->t('Select a breakpoint group from the installed themes and modules. Below you can select which breakpoints to use from this group. You can also select which image style or styles to use for each breakpoint you use.') . ' ' . $this->t("Warning: if you change the breakpoint group you lose all your image style selections for each breakpoint.");
87     }
88     else {
89       $description = $this->t('Select a breakpoint group from the installed themes and modules.');
90     }
91
92     $form['breakpoint_group'] = [
93       '#type' => 'select',
94       '#title' => $this->t('Breakpoint group'),
95       '#default_value' => $responsive_image_style->getBreakpointGroup() ?: 'responsive_image',
96       '#options' => $this->breakpointManager->getGroups(),
97       '#required' => TRUE,
98       '#description' => $description,
99       '#ajax' => [
100         'callback' => '::breakpointMappingFormAjax',
101         'wrapper' => 'responsive-image-style-breakpoints-wrapper',
102       ],
103     ];
104
105     $form['keyed_styles'] = [
106       '#type' => 'container',
107       '#attributes' => [
108         'id' => 'responsive-image-style-breakpoints-wrapper',
109       ],
110     ];
111
112     // By default, breakpoints are ordered from smallest weight to largest:
113     // the smallest weight is expected to have the smallest breakpoint width,
114     // while the largest weight is expected to have the largest breakpoint
115     // width. For responsive images, we need largest breakpoint widths first, so
116     // we need to reverse the order of these breakpoints.
117     $breakpoints = array_reverse($this->breakpointManager->getBreakpointsByGroup($responsive_image_style->getBreakpointGroup()));
118
119     foreach ($breakpoints as $breakpoint_id => $breakpoint) {
120       foreach ($breakpoint->getMultipliers() as $multiplier) {
121         $label = $multiplier . ' ' . $breakpoint->getLabel() . ' [' . $breakpoint->getMediaQuery() . ']';
122         $form['keyed_styles'][$breakpoint_id][$multiplier] = [
123           '#type' => 'details',
124           '#title' => $label,
125         ];
126         $image_style_mapping = $responsive_image_style->getImageStyleMapping($breakpoint_id, $multiplier);
127         if (\Drupal::moduleHandler()->moduleExists('help')) {
128           $description = $this->t('See the <a href=":responsive_image_help">Responsive Image help page</a> for information on the sizes attribute.', [':responsive_image_help' => \Drupal::url('help.page', ['name' => 'responsive_image'])]);
129         }
130         else {
131           $description = $this->t('Enable the Help module for more information on the sizes attribute.');
132         }
133         $form['keyed_styles'][$breakpoint_id][$multiplier]['image_mapping_type'] = [
134           '#title' => $this->t('Type'),
135           '#type' => 'radios',
136           '#options' => [
137             'sizes' => $this->t('Select multiple image styles and use the sizes attribute.'),
138             'image_style' => $this->t('Select a single image style.'),
139             '_none' => $this->t('Do not use this breakpoint.'),
140           ],
141           '#default_value' => isset($image_style_mapping['image_mapping_type']) ? $image_style_mapping['image_mapping_type'] : '_none',
142           '#description' => $description,
143         ];
144         $form['keyed_styles'][$breakpoint_id][$multiplier]['image_style'] = [
145           '#type' => 'select',
146           '#title' => $this->t('Image style'),
147           '#options' => $image_styles,
148           '#default_value' => isset($image_style_mapping['image_mapping']) && is_string($image_style_mapping['image_mapping']) ? $image_style_mapping['image_mapping'] : '',
149           '#description' => $this->t('Select an image style for this breakpoint.'),
150           '#states' => [
151             'visible' => [
152               ':input[name="keyed_styles[' . $breakpoint_id . '][' . $multiplier . '][image_mapping_type]"]' => ['value' => 'image_style'],
153             ],
154           ],
155         ];
156         $form['keyed_styles'][$breakpoint_id][$multiplier]['sizes'] = [
157           '#type' => 'textfield',
158           '#title' => $this->t('Sizes'),
159           '#default_value' => isset($image_style_mapping['image_mapping']['sizes']) ? $image_style_mapping['image_mapping']['sizes'] : '100vw',
160           '#description' => $this->t('Enter the value for the sizes attribute, for example: %example_sizes.', ['%example_sizes' => '(min-width:700px) 700px, 100vw']),
161           '#states' => [
162             'visible' => [
163               ':input[name="keyed_styles[' . $breakpoint_id . '][' . $multiplier . '][image_mapping_type]"]' => ['value' => 'sizes'],
164             ],
165             'required' => [
166               ':input[name="keyed_styles[' . $breakpoint_id . '][' . $multiplier . '][image_mapping_type]"]' => ['value' => 'sizes'],
167             ],
168           ],
169         ];
170         $form['keyed_styles'][$breakpoint_id][$multiplier]['sizes_image_styles'] = [
171           '#title' => $this->t('Image styles'),
172           '#type' => 'checkboxes',
173           '#options' => array_diff_key($image_styles, ['' => '']),
174           '#description' => $this->t('Select image styles with widths that range from the smallest amount of space this image will take up in the layout to the largest, bearing in mind that high resolution screens will need images 1.5x to 2x larger.'),
175           '#default_value' => isset($image_style_mapping['image_mapping']['sizes_image_styles']) ? $image_style_mapping['image_mapping']['sizes_image_styles'] : [],
176           '#states' => [
177             'visible' => [
178               ':input[name="keyed_styles[' . $breakpoint_id . '][' . $multiplier . '][image_mapping_type]"]' => ['value' => 'sizes'],
179             ],
180             'required' => [
181               ':input[name="keyed_styles[' . $breakpoint_id . '][' . $multiplier . '][image_mapping_type]"]' => ['value' => 'sizes'],
182             ],
183           ],
184         ];
185
186         // Expand the details if "do not use this breakpoint" was not selected.
187         if ($form['keyed_styles'][$breakpoint_id][$multiplier]['image_mapping_type']['#default_value'] != '_none') {
188           $form['keyed_styles'][$breakpoint_id][$multiplier]['#open'] = TRUE;
189         }
190       }
191     }
192
193     $form['fallback_image_style'] = [
194       '#title' => $this->t('Fallback image style'),
195       '#type' => 'select',
196       '#default_value' => $responsive_image_style->getFallbackImageStyle(),
197       '#options' => $image_styles,
198       '#required' => TRUE,
199       '#description' => t('Select the smallest image style you expect to appear in this space. The fallback image style should only appear on the site if an error occurs.'),
200     ];
201
202     $form['#tree'] = TRUE;
203
204     return parent::form($form, $form_state, $responsive_image_style);
205   }
206
207   /**
208    * Get the form for mapping breakpoints to image styles.
209    */
210   public function breakpointMappingFormAjax($form, FormStateInterface $form_state) {
211     return $form['keyed_styles'];
212   }
213
214   /**
215    * {@inheritdoc}
216    */
217   public function validateForm(array &$form, FormStateInterface $form_state) {
218     parent::validateForm($form, $form_state);
219     // Only validate on edit.
220     if ($form_state->hasValue('keyed_styles')) {
221       // Check if another breakpoint group is selected.
222       if ($form_state->getValue('breakpoint_group') != $form_state->getCompleteForm()['breakpoint_group']['#default_value']) {
223         // Remove the image style mappings since the breakpoint ID has changed.
224         $form_state->unsetValue('keyed_styles');
225       }
226
227       // Check that at least 1 image style has been selected when using sizes.
228       foreach ($form_state->getValue('keyed_styles') as $breakpoint_id => $multipliers) {
229         foreach ($multipliers as $multiplier => $image_style_mapping) {
230           if ($image_style_mapping['image_mapping_type'] === 'sizes') {
231             if (empty($image_style_mapping['sizes'])) {
232               $form_state->setError($form['keyed_styles'][$breakpoint_id][$multiplier]['sizes'], 'Provide a value for the sizes attribute.');
233             }
234             if (empty(array_keys(array_filter($image_style_mapping['sizes_image_styles'])))) {
235               $form_state->setError($form['keyed_styles'][$breakpoint_id][$multiplier]['sizes_image_styles'], 'Select at least one image style.');
236             }
237           }
238         }
239       }
240     }
241   }
242
243   /**
244    * {@inheritdoc}
245    */
246   public function save(array $form, FormStateInterface $form_state) {
247     /** @var \Drupal\responsive_image\ResponsiveImageStyleInterface $responsive_image_style */
248     $responsive_image_style = $this->entity;
249     // Remove all the existing mappings and replace with submitted values.
250     $responsive_image_style->removeImageStyleMappings();
251     if ($form_state->hasValue('keyed_styles')) {
252       foreach ($form_state->getValue('keyed_styles') as $breakpoint_id => $multipliers) {
253         foreach ($multipliers as $multiplier => $image_style_mapping) {
254           if ($image_style_mapping['image_mapping_type'] === 'sizes') {
255             $mapping = [
256               'image_mapping_type' => 'sizes',
257               'image_mapping' => [
258                 'sizes' => $image_style_mapping['sizes'],
259                 'sizes_image_styles' => array_keys(array_filter($image_style_mapping['sizes_image_styles'])),
260               ]
261             ];
262             $responsive_image_style->addImageStyleMapping($breakpoint_id, $multiplier, $mapping);
263           }
264           elseif ($image_style_mapping['image_mapping_type'] === 'image_style') {
265             $mapping = [
266               'image_mapping_type' => 'image_style',
267               'image_mapping' => $image_style_mapping['image_style'],
268             ];
269             $responsive_image_style->addImageStyleMapping($breakpoint_id, $multiplier, $mapping);
270           }
271         }
272       }
273     }
274     $responsive_image_style->save();
275
276     $this->logger('responsive_image')->notice('Responsive image style @label saved.', ['@label' => $responsive_image_style->label()]);
277     drupal_set_message($this->t('Responsive image style %label saved.', ['%label' => $responsive_image_style->label()]));
278
279     // Redirect to edit form after creating a new responsive image style or
280     // after selecting another breakpoint group.
281     if (!$responsive_image_style->hasImageStyleMappings()) {
282       $form_state->setRedirect(
283         'entity.responsive_image_style.edit_form',
284         ['responsive_image_style' => $responsive_image_style->id()]
285       );
286     }
287     else {
288       $form_state->setRedirectUrl($this->entity->urlInfo('collection'));
289     }
290   }
291
292 }