function StyleForm::buildForm

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.

Overrides FormInterface::buildForm

File

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

Class

StyleForm
Form for interacting with image styles.

Namespace

Drupal\image_example\Form

Code

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;
}