3 namespace Drupal\responsive_image;
5 use Drupal\breakpoint\BreakpointManagerInterface;
6 use Drupal\Core\Entity\EntityForm;
7 use Drupal\Core\Form\FormStateInterface;
8 use Symfony\Component\DependencyInjection\ContainerInterface;
11 * Form controller for the responsive image edit/add forms.
13 class ResponsiveImageStyleForm extends EntityForm {
16 * The breakpoint manager.
18 * @var \Drupal\breakpoint\BreakpointManagerInterface
20 protected $breakpointManager;
25 public static function create(ContainerInterface $container) {
27 $container->get('breakpoint.manager')
32 * Constructs the responsive image style form.
34 * @param \Drupal\breakpoint\BreakpointManagerInterface $breakpoint_manager
35 * The breakpoint manager.
37 public function __construct(BreakpointManagerInterface $breakpoint_manager) {
38 $this->breakpointManager = $breakpoint_manager;
42 * Overrides Drupal\Core\Entity\EntityForm::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.
50 * The array containing the complete form.
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();
57 if ($this->operation == 'edit') {
58 $form['#title'] = $this->t('<em>Edit responsive image style</em> @label', ['@label' => $this->entity->label()]);
61 /** @var \Drupal\responsive_image\ResponsiveImageStyleInterface $responsive_image_style */
62 $responsive_image_style = $this->entity;
64 '#type' => 'textfield',
65 '#title' => $this->t('Label'),
67 '#default_value' => $responsive_image_style->label(),
68 '#description' => $this->t("Example: 'Hero image' or 'Author image'."),
72 '#type' => 'machine_name',
73 '#default_value' => $responsive_image_style->id(),
75 'exists' => '\Drupal\responsive_image\Entity\ResponsiveImageStyle::load',
76 'source' => ['label'],
78 '#disabled' => (bool) $responsive_image_style->id() && $this->operation != 'duplicate',
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 -');
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.");
89 $description = $this->t('Select a breakpoint group from the installed themes and modules.');
92 $form['breakpoint_group'] = [
94 '#title' => $this->t('Breakpoint group'),
95 '#default_value' => $responsive_image_style->getBreakpointGroup() ?: 'responsive_image',
96 '#options' => $this->breakpointManager->getGroups(),
98 '#description' => $description,
100 'callback' => '::breakpointMappingFormAjax',
101 'wrapper' => 'responsive-image-style-breakpoints-wrapper',
105 $form['keyed_styles'] = [
106 '#type' => 'container',
108 'id' => 'responsive-image-style-breakpoints-wrapper',
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()));
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',
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'])]);
131 $description = $this->t('Enable the Help module for more information on the sizes attribute.');
133 $form['keyed_styles'][$breakpoint_id][$multiplier]['image_mapping_type'] = [
134 '#title' => $this->t('Type'),
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.'),
141 '#default_value' => isset($image_style_mapping['image_mapping_type']) ? $image_style_mapping['image_mapping_type'] : '_none',
142 '#description' => $description,
144 $form['keyed_styles'][$breakpoint_id][$multiplier]['image_style'] = [
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.'),
152 ':input[name="keyed_styles[' . $breakpoint_id . '][' . $multiplier . '][image_mapping_type]"]' => ['value' => 'image_style'],
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']),
163 ':input[name="keyed_styles[' . $breakpoint_id . '][' . $multiplier . '][image_mapping_type]"]' => ['value' => 'sizes'],
166 ':input[name="keyed_styles[' . $breakpoint_id . '][' . $multiplier . '][image_mapping_type]"]' => ['value' => 'sizes'],
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'] : [],
178 ':input[name="keyed_styles[' . $breakpoint_id . '][' . $multiplier . '][image_mapping_type]"]' => ['value' => 'sizes'],
181 ':input[name="keyed_styles[' . $breakpoint_id . '][' . $multiplier . '][image_mapping_type]"]' => ['value' => 'sizes'],
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;
193 $form['fallback_image_style'] = [
194 '#title' => $this->t('Fallback image style'),
196 '#default_value' => $responsive_image_style->getFallbackImageStyle(),
197 '#options' => $image_styles,
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.'),
202 $form['#tree'] = TRUE;
204 return parent::form($form, $form_state, $responsive_image_style);
208 * Get the form for mapping breakpoints to image styles.
210 public function breakpointMappingFormAjax($form, FormStateInterface $form_state) {
211 return $form['keyed_styles'];
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');
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.');
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.');
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') {
256 'image_mapping_type' => 'sizes',
258 'sizes' => $image_style_mapping['sizes'],
259 'sizes_image_styles' => array_keys(array_filter($image_style_mapping['sizes_image_styles'])),
262 $responsive_image_style->addImageStyleMapping($breakpoint_id, $multiplier, $mapping);
264 elseif ($image_style_mapping['image_mapping_type'] === 'image_style') {
266 'image_mapping_type' => 'image_style',
267 'image_mapping' => $image_style_mapping['image_style'],
269 $responsive_image_style->addImageStyleMapping($breakpoint_id, $multiplier, $mapping);
274 $responsive_image_style->save();
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()]));
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()]
288 $form_state->setRedirectUrl($this->entity->urlInfo('collection'));