2

I want to add a block containing an image field to Drupal to add it to the page layout.

I can see the image gets uploaded (because it appears in my file system), but the block forgets the image; next time I configure the block, the image I just uploaded has disappeared.

What I've got so far is the following code.

/**
 * {@inheritdoc}
 */
public function build() {
  $build = [];
  $build['image']['#markup'] = '';

  return $build;
}

/**
 * {@inheritdoc}
 */
public function blockForm($form, FormStateInterface $form_state) {
  $form['image'] = array(
    '#type' => 'managed_file',
    '#upload_location' => 'public://images/',
    '#title' => $this->t('Image'),
    '#description' => t("Image to show on the contact form"),
    '#default_value' => $this->configuration['image']['value'],
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),
      'file_validate_size' => array(25600000),
    ),
    '#states' => array(
      'visible' => array(
        ':input[name="image_type"]' => array('value' => t('Upload New Image(s)')),
      )
    )
  );

  return $form;
}

public function blockValidate($form, FormStateInterface $form_state) {}

/**
 * {@inheritdoc}
 */
public function blockSubmit($form, FormStateInterface $form_state) {
  $image = $form_state->getValue('image');
  $this->configuration['image'] = $image;
  $file = \Drupal\file\Entity\File::load($image[0]);
  $file->setPermanent();
  $file->save();
}

How do I display a user-uploaded image?
How do I make the block remember this picture?

0

1 Answer 1

5

With help from "Ambidex" on Drupal Slack, I post here the complete plugin-file.

I could not find an example for this use case, and I believe it might benefit others:

file: [drupalroot]/modules/custom/ourcustomername_tweaks/src/Plugin/Block /ContactBlock.php

.

<?php


namespace Drupal\ourcustomername_tweaks\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;



/**
 * Provides a 'Contact' Block.
 *
 * @Block(
 *   id = "contact_block",
 *   admin_label = @Translation("Image Contact block"),
 * )
 */
class ContactBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [

        'image' => [
          'value' => ''
        ],

        'label_display' => FALSE,
      ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function build(){
    $build = [];


    if (  isset($this->configuration['image']) && !empty( $this->configuration['image'] )  ) {

      $image_field = $this->configuration['image'];
      $image_uri = File::load($image_field[0]);

      $build['image'] = [
        '#theme' => 'image_style',
        '#style_name' => 'ourcustomername',
        '#uri' => $image_uri->uri->value
      ];
    } else {
      $build['image']['#markup'] = '['.t('Picture').']';
    }


    return $build;
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {

    $form['image'] = array(
      '#type' => 'managed_file',
      '#upload_location' => 'public://images/',
      '#title' => $this->t('Image'),
      '#description' => t("Image to show on the contact form"),
      '#default_value' => $this->configuration['image'],
      '#upload_validators' => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
        'file_validate_size' => array(25600000),
      ),
      '#states'        => array(
        'visible'      => array(
          ':input[name="image_type"]' => array('value' => t('Upload New Image(s)')),
        )
      )
    );

    return $form;
  }


  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {

    /* Fetch the array of the file stored temporarily in database */
    $image = $form_state->getValue('image');

    $this->configuration['image'] = $image;

    /* Load the object of the file by it's fid */
    $file = \Drupal\file\Entity\File::load( $image[0] );

    /* Set the status flag permanent of the file object */
    $file->setPermanent();

    /* Save the file in database */
    $file->save();
  }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.