class StyleForm

Form for interacting with image styles.

Hierarchy

Expanded class hierarchy of StyleForm

Related topics

1 string reference to 'StyleForm'
image_example.routing.yml in modules/image_example/image_example.routing.yml
modules/image_example/image_example.routing.yml

File

modules/image_example/src/Form/StyleForm.php, line 17

Namespace

Drupal\image_example\Form
View source
class StyleForm extends FormBase {
    
    /**
     * The state service.
     *
     * @var \Drupal\Core\State\StateInterface
     */
    protected $state;
    
    /**
     * The file usage service.
     *
     * @var \Drupal\file\FileUsage\FileUsageInterface
     */
    protected $fileUsage;
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container) {
        $instance = new static();
        $instance->setState($container->get('state'));
        $instance->setFileUsage($container->get('file.usage'));
        $instance->setMessenger($container->get('messenger'));
        $instance->setStringTranslation($container->get('string_translation'));
        return $instance;
    }
    
    /**
     * Sets the state service.
     *
     * @param \Drupal\Core\State\StateInterface $state
     *   The state service.
     */
    protected function setState(StateInterface $state) {
        $this->state = $state;
    }
    
    /**
     * Sets the file usage service.
     *
     * @param \Drupal\file\FileUsage\FileUsageInterface $file_usage
     *   The file usage service.
     */
    protected function setFileUsage(FileUsageInterface $file_usage) {
        $this->fileUsage = $file_usage;
    }
    
    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'image_example_style_form';
    }
    
    /**
     * Form for uploading and displaying an image using selected style.
     *
     * This page provides a form that allows the user to upload an image and
     * choose a style from the list of defined image styles to use when displaying
     * the the image. This serves as an example of integrating image styles with
     * your module and as a way to demonstrate that the styles and effects defined
     * by this module are available via Drupal's image handling system.
     */
    public function buildForm(array $form, FormStateInterface $form_state) {
        $image_fid = $this->state
            ->get('image_example.image_fid');
        // If there is already an uploaded image display the image here.
        if ($image_fid) {
            $image = File::load($image_fid);
            $style = $this->state
                ->get('image_example.style_name', 'thumbnail');
            $form['image'] = [
                '#theme' => 'image_style',
                '#style_name' => $style,
                '#uri' => $image->getFileUri(),
            ];
        }
        // Use the #managed_file FAPI element to upload an image file.
        $form['image_fid'] = [
            '#title' => $this->t('Image'),
            '#type' => 'managed_file',
            '#description' => $this->t('The uploaded image will be displayed on this page using the image style set in the next form field.'),
            '#default_value' => $image_fid,
            '#upload_location' => 'public://image_example_images/',
        ];
        // Provide a select field for choosing an image style to use when displaying
        // the image.
        $form['style_name'] = [
            '#title' => $this->t('Image style'),
            '#type' => 'select',
            '#description' => $this->t('Choose an image style to use when displaying this image.'),
            // The image_style_options() function returns an array of all available
            // image styles both the key and the value of the array are the image
            // style's name. The function takes one parameter, a Boolean flag that is
            // TRUE when the array should include a <none> option.
'#options' => image_style_options(TRUE),
            '#default_value' => $this->state
                ->get('image_example.style_name', 'thumbnail'),
        ];
        // Submit Button.
        $form['submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Save'),
        ];
        return $form;
    }
    
    /**
     * Verifies that the user supplied an image with the form.
     */
    public function validateForm(array &$form, FormStateInterface $form_state) {
        if (!$form_state->hasValue('image_fid') || !is_numeric($form_state->getValue('image_fid'))) {
            $form_state->setErrorByName('image_fid', $this->t('Please select an image to upload.'));
        }
    }
    
    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        // When using the #managed_file form element the file is automatically
        // uploaded an saved to the {file} table. The value of the corresponding
        // form element is set to the ID of the new file. If the file ID is not
        // zero, we have a valid file.
        if (($fid = $form_state->getValue('image_fid')) != 0) {
            // The new file's status is set to 0 or temporary and in order to ensure
            // that the file is not removed after 6 hours, we need to change its
            // status to 1. Save the ID of the uploaded image for later use.
            if ($file = File::load($fid)) {
                $file->setPermanent();
                $file->save($file);
                // When a module is managing a file, it must manage the usage count.
                $this->fileUsage
                    ->add($file, 'image_example', 'sample_image');
                $this->messenger
                    ->addMessage($this->t('The image @image_name was uploaded and saved. Its ID is @fid and it will be displayed using the image style @style.', [
                    '@image_name' => $file->getFilename(),
                    '@fid' => $fid,
                    '@style' => $form_state->getValue('style_name'),
                ]));
            }
            else {
                $fid = NULL;
                $this->messenger
                    ->addWarning($this->t('The image could not be saved.'));
            }
        }
        // Delete the previously uploaded image.
        $old_fid = $this->state
            ->get('image_example.image_fid');
        if (!empty($old_fid) && ($old_file = File::load($old_fid))) {
            $image_name = $old_file->getFilename();
            // When a module is managing a file, it must manage the usage count.
            $this->fileUsage
                ->delete($old_file, 'image_example', 'sample_image');
            // File::delete() verifies the file is used by any other modules. If it
            // is, the file will not be deleted. The module still needs to update
            // its reference.
            $old_file->delete();
            $this->messenger
                ->addMessage($this->t('The image @image_name was removed.', [
                '@image_name' => $image_name,
            ]));
        }
        // Usually, a form submission handler stores the data in a configuration
        // object, or in a custom database table, but in this case we use the state
        // service.
        $this->state
            ->set('image_example.image_fid', $fid);
        $this->state
            ->set('image_example.style_name', $form_state->getValue('style_name'));
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
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. 2
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.
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.
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. 16
MessengerTrait::messenger public function Gets the messenger. 16
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 2
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.
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
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.
StyleForm::$fileUsage protected property The file usage service.
StyleForm::$state protected property The state service.
StyleForm::buildForm public function Form for uploading and displaying an image using selected style. Overrides FormInterface::buildForm
StyleForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
StyleForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
StyleForm::setFileUsage protected function Sets the file usage service.
StyleForm::setState protected function Sets the state service.
StyleForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
StyleForm::validateForm public function Verifies that the user supplied an image with the form. Overrides FormBase::validateForm