class ResponsiveImageStyleForm

Same name in other branches
  1. 9 core/modules/responsive_image/src/ResponsiveImageStyleForm.php \Drupal\responsive_image\ResponsiveImageStyleForm
  2. 10 core/modules/responsive_image/src/ResponsiveImageStyleForm.php \Drupal\responsive_image\ResponsiveImageStyleForm
  3. 11.x core/modules/responsive_image/src/ResponsiveImageStyleForm.php \Drupal\responsive_image\ResponsiveImageStyleForm

Form controller for the responsive image edit/add forms.

@internal

Hierarchy

Expanded class hierarchy of ResponsiveImageStyleForm

File

core/modules/responsive_image/src/ResponsiveImageStyleForm.php, line 16

Namespace

Drupal\responsive_image
View source
class ResponsiveImageStyleForm extends EntityForm {
    
    /**
     * The breakpoint manager.
     *
     * @var \Drupal\breakpoint\BreakpointManagerInterface
     */
    protected $breakpointManager;
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container) {
        return new static($container->get('breakpoint.manager'));
    }
    
    /**
     * Constructs the responsive image style form.
     *
     * @param \Drupal\breakpoint\BreakpointManagerInterface $breakpoint_manager
     *   The breakpoint manager.
     */
    public function __construct(BreakpointManagerInterface $breakpoint_manager) {
        $this->breakpointManager = $breakpoint_manager;
    }
    
    /**
     * Overrides Drupal\Core\Entity\EntityForm::form().
     *
     * @param array $form
     *   A nested array form elements comprising the form.
     * @param \Drupal\Core\Form\FormStateInterface $form_state
     *   The current state of the form.
     *
     * @return array
     *   The array containing the complete form.
     */
    public function form(array $form, FormStateInterface $form_state) {
        if ($this->operation == 'duplicate') {
            $form['#title'] = $this->t('<em>Duplicate responsive image style</em> @label', [
                '@label' => $this->entity
                    ->label(),
            ]);
            $this->entity = $this->entity
                ->createDuplicate();
        }
        if ($this->operation == 'edit') {
            $form['#title'] = $this->t('<em>Edit responsive image style</em> @label', [
                '@label' => $this->entity
                    ->label(),
            ]);
        }
        
        /** @var \Drupal\responsive_image\ResponsiveImageStyleInterface $responsive_image_style */
        $responsive_image_style = $this->entity;
        $form['label'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Label'),
            '#maxlength' => 255,
            '#default_value' => $responsive_image_style->label(),
            '#description' => $this->t("Example: 'Hero image' or 'Author image'."),
            '#required' => TRUE,
        ];
        $form['id'] = [
            '#type' => 'machine_name',
            '#default_value' => $responsive_image_style->id(),
            '#machine_name' => [
                'exists' => '\\Drupal\\responsive_image\\Entity\\ResponsiveImageStyle::load',
                'source' => [
                    'label',
                ],
            ],
            '#disabled' => (bool) $responsive_image_style->id() && $this->operation != 'duplicate',
        ];
        $image_styles = image_style_options(TRUE);
        $image_styles[ResponsiveImageStyleInterface::ORIGINAL_IMAGE] = $this->t('- None (original image) -');
        $image_styles[ResponsiveImageStyleInterface::EMPTY_IMAGE] = $this->t('- empty image -');
        if ((bool) $responsive_image_style->id() && $this->operation != 'duplicate') {
            $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.");
        }
        else {
            $description = $this->t('Select a breakpoint group from the installed themes and modules.');
        }
        $form['breakpoint_group'] = [
            '#type' => 'select',
            '#title' => $this->t('Breakpoint group'),
            '#default_value' => $responsive_image_style->getBreakpointGroup() ?: 'responsive_image',
            '#options' => $this->breakpointManager
                ->getGroups(),
            '#required' => TRUE,
            '#description' => $description,
            '#ajax' => [
                'callback' => '::breakpointMappingFormAjax',
                'wrapper' => 'responsive-image-style-breakpoints-wrapper',
            ],
        ];
        $form['keyed_styles'] = [
            '#type' => 'container',
            '#attributes' => [
                'id' => 'responsive-image-style-breakpoints-wrapper',
            ],
        ];
        // By default, breakpoints are ordered from smallest weight to largest:
        // the smallest weight is expected to have the smallest breakpoint width,
        // while the largest weight is expected to have the largest breakpoint
        // width. For responsive images, we need largest breakpoint widths first, so
        // we need to reverse the order of these breakpoints.
        $breakpoints = array_reverse($this->breakpointManager
            ->getBreakpointsByGroup($responsive_image_style->getBreakpointGroup()));
        foreach ($breakpoints as $breakpoint_id => $breakpoint) {
            foreach ($breakpoint->getMultipliers() as $multiplier) {
                $label = $multiplier . ' ' . $breakpoint->getLabel() . ' [' . $breakpoint->getMediaQuery() . ']';
                $form['keyed_styles'][$breakpoint_id][$multiplier] = [
                    '#type' => 'details',
                    '#title' => $label,
                ];
                $image_style_mapping = $responsive_image_style->getImageStyleMapping($breakpoint_id, $multiplier);
                if (\Drupal::moduleHandler()->moduleExists('help')) {
                    $description = $this->t('See the <a href=":responsive_image_help">Responsive Image help page</a> for information on the sizes attribute.', [
                        ':responsive_image_help' => Url::fromRoute('help.page', [
                            'name' => 'responsive_image',
                        ])->toString(),
                    ]);
                }
                else {
                    $description = $this->t('Enable the Help module for more information on the sizes attribute.');
                }
                $form['keyed_styles'][$breakpoint_id][$multiplier]['image_mapping_type'] = [
                    '#title' => $this->t('Type'),
                    '#type' => 'radios',
                    '#options' => [
                        'sizes' => $this->t('Select multiple image styles and use the sizes attribute.'),
                        'image_style' => $this->t('Select a single image style.'),
                        '_none' => $this->t('Do not use this breakpoint.'),
                    ],
                    '#default_value' => isset($image_style_mapping['image_mapping_type']) ? $image_style_mapping['image_mapping_type'] : '_none',
                    '#description' => $description,
                ];
                $form['keyed_styles'][$breakpoint_id][$multiplier]['image_style'] = [
                    '#type' => 'select',
                    '#title' => $this->t('Image style'),
                    '#options' => $image_styles,
                    '#default_value' => isset($image_style_mapping['image_mapping']) && is_string($image_style_mapping['image_mapping']) ? $image_style_mapping['image_mapping'] : '',
                    '#description' => $this->t('Select an image style for this breakpoint.'),
                    '#states' => [
                        'visible' => [
                            ':input[name="keyed_styles[' . $breakpoint_id . '][' . $multiplier . '][image_mapping_type]"]' => [
                                'value' => 'image_style',
                            ],
                        ],
                    ],
                ];
                $form['keyed_styles'][$breakpoint_id][$multiplier]['sizes'] = [
                    '#type' => 'textarea',
                    '#title' => $this->t('Sizes'),
                    '#default_value' => isset($image_style_mapping['image_mapping']['sizes']) ? $image_style_mapping['image_mapping']['sizes'] : '100vw',
                    '#description' => $this->t('Enter the value for the sizes attribute, for example: %example_sizes.', [
                        '%example_sizes' => '(min-width:700px) 700px, 100vw',
                    ]),
                    '#states' => [
                        'visible' => [
                            ':input[name="keyed_styles[' . $breakpoint_id . '][' . $multiplier . '][image_mapping_type]"]' => [
                                'value' => 'sizes',
                            ],
                        ],
                        'required' => [
                            ':input[name="keyed_styles[' . $breakpoint_id . '][' . $multiplier . '][image_mapping_type]"]' => [
                                'value' => 'sizes',
                            ],
                        ],
                    ],
                ];
                $form['keyed_styles'][$breakpoint_id][$multiplier]['sizes_image_styles'] = [
                    '#title' => $this->t('Image styles'),
                    '#type' => 'checkboxes',
                    '#options' => array_diff_key($image_styles, [
                        '' => '',
                    ]),
                    '#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.'),
                    '#default_value' => isset($image_style_mapping['image_mapping']['sizes_image_styles']) ? $image_style_mapping['image_mapping']['sizes_image_styles'] : [],
                    '#states' => [
                        'visible' => [
                            ':input[name="keyed_styles[' . $breakpoint_id . '][' . $multiplier . '][image_mapping_type]"]' => [
                                'value' => 'sizes',
                            ],
                        ],
                        'required' => [
                            ':input[name="keyed_styles[' . $breakpoint_id . '][' . $multiplier . '][image_mapping_type]"]' => [
                                'value' => 'sizes',
                            ],
                        ],
                    ],
                ];
                // Expand the details if "do not use this breakpoint" was not selected.
                if ($form['keyed_styles'][$breakpoint_id][$multiplier]['image_mapping_type']['#default_value'] != '_none') {
                    $form['keyed_styles'][$breakpoint_id][$multiplier]['#open'] = TRUE;
                }
            }
        }
        $form['fallback_image_style'] = [
            '#title' => $this->t('Fallback image style'),
            '#type' => 'select',
            '#default_value' => $responsive_image_style->getFallbackImageStyle(),
            '#options' => $image_styles,
            '#required' => TRUE,
            '#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.'),
        ];
        $form['#tree'] = TRUE;
        return parent::form($form, $form_state, $responsive_image_style);
    }
    
    /**
     * Get the form for mapping breakpoints to image styles.
     */
    public function breakpointMappingFormAjax($form, FormStateInterface $form_state) {
        return $form['keyed_styles'];
    }
    
    /**
     * {@inheritdoc}
     */
    public function validateForm(array &$form, FormStateInterface $form_state) {
        parent::validateForm($form, $form_state);
        // Only validate on edit.
        if ($form_state->hasValue('keyed_styles')) {
            // Check if another breakpoint group is selected.
            if ($form_state->getValue('breakpoint_group') != $form_state->getCompleteForm()['breakpoint_group']['#default_value']) {
                // Remove the image style mappings since the breakpoint ID has changed.
                $form_state->unsetValue('keyed_styles');
            }
            // Check that at least 1 image style has been selected when using sizes.
            foreach ($form_state->getValue('keyed_styles') as $breakpoint_id => $multipliers) {
                foreach ($multipliers as $multiplier => $image_style_mapping) {
                    if ($image_style_mapping['image_mapping_type'] === 'sizes') {
                        if (empty($image_style_mapping['sizes'])) {
                            $form_state->setError($form['keyed_styles'][$breakpoint_id][$multiplier]['sizes'], 'Provide a value for the sizes attribute.');
                        }
                        if (empty(array_keys(array_filter($image_style_mapping['sizes_image_styles'])))) {
                            $form_state->setError($form['keyed_styles'][$breakpoint_id][$multiplier]['sizes_image_styles'], 'Select at least one image style.');
                        }
                    }
                }
            }
        }
    }
    
    /**
     * {@inheritdoc}
     */
    public function save(array $form, FormStateInterface $form_state) {
        
        /** @var \Drupal\responsive_image\ResponsiveImageStyleInterface $responsive_image_style */
        $responsive_image_style = $this->entity;
        // Remove all the existing mappings and replace with submitted values.
        $responsive_image_style->removeImageStyleMappings();
        if ($form_state->hasValue('keyed_styles')) {
            foreach ($form_state->getValue('keyed_styles') as $breakpoint_id => $multipliers) {
                foreach ($multipliers as $multiplier => $image_style_mapping) {
                    if ($image_style_mapping['image_mapping_type'] === 'sizes') {
                        $mapping = [
                            'image_mapping_type' => 'sizes',
                            'image_mapping' => [
                                'sizes' => $image_style_mapping['sizes'],
                                'sizes_image_styles' => array_keys(array_filter($image_style_mapping['sizes_image_styles'])),
                            ],
                        ];
                        $responsive_image_style->addImageStyleMapping($breakpoint_id, $multiplier, $mapping);
                    }
                    elseif ($image_style_mapping['image_mapping_type'] === 'image_style') {
                        $mapping = [
                            'image_mapping_type' => 'image_style',
                            'image_mapping' => $image_style_mapping['image_style'],
                        ];
                        $responsive_image_style->addImageStyleMapping($breakpoint_id, $multiplier, $mapping);
                    }
                }
            }
        }
        $responsive_image_style->save();
        $this->logger('responsive_image')
            ->notice('Responsive image style @label saved.', [
            '@label' => $responsive_image_style->label(),
        ]);
        $this->messenger()
            ->addStatus($this->t('Responsive image style %label saved.', [
            '%label' => $responsive_image_style->label(),
        ]));
        // Redirect to edit form after creating a new responsive image style or
        // after selecting another breakpoint group.
        if (!$responsive_image_style->hasImageStyleMappings()) {
            $form_state->setRedirect('entity.responsive_image_style.edit_form', [
                'responsive_image_style' => $responsive_image_style->id(),
            ]);
        }
        else {
            $form_state->setRedirectUrl($this->entity
                ->toUrl('collection'));
        }
    }

}

Members

Title Sort descending Deprecated Modifiers Object type Summary Overriden Title Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityForm::$entity protected property The entity being used by this form. 11
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 36
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 3
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 13
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 9
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 6
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 3
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 12
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::submitForm public function This is the default entity object builder function. It is called before any
other submit handler to build the new entity object to be used by the
following submit handlers. At this point of the form workflow the entity is
validated and the form state…
Overrides FormInterface::submitForm 20
EntityForm::__get public function
EntityForm::__set public function
FormBase::$configFactory protected property The config factory. 3
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 3
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 17
MessengerTrait::messenger public function Gets the messenger. 17
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a &#039;destination&#039; URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
ResponsiveImageStyleForm::$breakpointManager protected property The breakpoint manager.
ResponsiveImageStyleForm::breakpointMappingFormAjax public function Get the form for mapping breakpoints to image styles.
ResponsiveImageStyleForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ResponsiveImageStyleForm::form public function Overrides Drupal\Core\Entity\EntityForm::form(). Overrides EntityForm::form
ResponsiveImageStyleForm::save public function Form submission handler for the &#039;save&#039; action. Overrides EntityForm::save
ResponsiveImageStyleForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
ResponsiveImageStyleForm::__construct public function Constructs the responsive image style form.
StringTranslationTrait::$stringTranslation protected property The string translation service.
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.