2

I'm working on a custom module, that contains a block and I'm currently having an issue to render an image that is being uploaded through a form at the configuration of the block.

I'm getting this error:

Error: Call to a member function getFileUri() on null in Drupal\onyx_experiencia\Plugin\Block\onyx_experiencia->build() (line 52 of....)

The file is being uploaded correctly to the specified directory. I've been reading about similar problems and errors but haven't found the correct solution.

What I'm trying to achieve is to get the uri of the image uploaded through the form. I've read that some times is necessary to load the entity or the image first, I've already tried but I still get the same error but on the line where I try to load the file.

This is the code:

<?php

namespace Drupal\onyx_experiencia\Plugin\Block;



use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;
use Druap\image\Entity\ImageStyle;



/**
 * Provides a 'Hello' Block.
 *
 * @Block(
 *   id = "onyx_experiencia",
 *   admin_label = @Translation("Servicios OnyxGroup"),
 *   category = @Translation("Servicios OnyxGroup"),
 * )
 */
class onyx_experiencia extends BlockBase implements BlockPluginInterface {

 /**
   * {@inheritdoc}
   */  
  public function build() {
    $config = $this->getConfiguration();
    $build = array();

    if (!empty($config['card_title'])) {
      $name = $config['card_title'];
    }
    else {
      $name = $this->t('Onyx Group Card');
    }

    if (!empty($config['card_text'])) {
      $cardText = $config['card_text'];
    }
    else {
      $cardText = $this->t('A service of Onyx Group');
    }

    $cardImg = File::load($config['card_image']);
    $cardUrl = $config['card_link'];

    $imgVar = array(
        'style_name' => 'thumbnail',
        'uri' => $cardImg->getFileUri(), //<--- THIS IS LINE 52:ERROR
    );

    $image = \Drupal::service('image.factory')->get($cardImg->getFileUri());
      if($image->isValid()) {
          $imgVar['width'] = $image->getWidth();
          $imgVar['height'] = $image->getHeight();
      } else {
          $imgVar['width'] = $imgVar['height'] = NULL;
      }


    $build[]['#attached']['library'][] = 'onyx_experiencia/onyx-experiencia-style';

    $build['CardTitle'] = array(
            '#prefix' => '',
            '#markup' => $this->t('Hello @name!', array('@name' => $name,)),
            '#suffix' => '',
        );

    $build['CardText'] = array(
            '#prefix' => '',
            '#markup' => $this->t('Card text: @cardText!', array('@cardText' => $cardText,)),
            '#suffix' => '',
        );

    $cardImg_array = array(
        '#prefix' => '',
        '#theme' => 'image_style',
        '#style_name' => $imgVar['style_name'],
        '#width' => $imgVar['width'],
        '#height' => $imgVar['height'],
        '#uri' => $imgVar['uri'],
        '#suffix' => '',
    );

      $renderer = \Drupal::service('renderer');
      $renderer->addCacheableDependecy($cardImg_array, $cardImg);

    return $build;


  }


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

    $config = $this->getConfiguration();

    $form['card_title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Card Title'),
      '#description' => $this->t('Type title of the service card.'),
      '#default_value' => isset($config['card_title']) ? $config['card_title'] : '',
    ];

    $form['card_text'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Card Text'),
      '#format' => 'full_html',
      '#description' => $this->t('Type the list of the services.'),
      '#default_value' => isset($config['card_text']) ? $config['card_text'] : '',
    ];

    $form['card_image'] = [
        '#type' => 'managed_file',
        '#title' => t('Card image background'),
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            'file_validate_size' => array(25600000),
        ),
        '#theme' => 'image_widget',
        '#preview_imgage_style' => 'medium',
        '#upload_location' => 'private://card_service_img',
        '#progress_message' => 'One moment while we save your file...',
        '#required' => TRUE,
    ];

    $form['card_link'] = [
        '#title' => t('Type card link. Example: /erp_cloud'),
        '#type' => 'url',
    ];

    return $form;
  }

 /**
   * Custom submit actions
   */
  public function custom_submit_form($form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    //Perform the required actions
  }

 /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['card_title'] = $form_state->getValue('card_title');
    $this->configuration['card_text'] = $form_state->getValue('card_text');
    $this->configuration['card_image'] = $form_state->getValue('card_image');
    $this->configuration['card_link'] = $form_state->getValue('card_link');
  }

}
1
  • Are you sure $config['card_image'] is a valid fid? Seems like it is not. If $cardImgFile::load($config['card_image']); returns null (empty) then it makes sense that you can't do getFileUri() on an empty object. It's like if I told you that a toy car does not exists. How can you make an non existent toy car roll?
    – No Sssweat
    Commented Apr 27, 2019 at 3:53

1 Answer 1

2

I finally got it working, I was kind of lost. The key was to correctly submit the image at blockSubmit function and effectively load the file at the build function

This is the final code that is working for me

<?php

namespace Drupal\onyx_experiencia\Plugin\Block;



use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;
use Druap\image\Entity\ImageStyle;



/**
 * Provides a 'Hello' Block.
 *
 * @Block(
 *   id = "onyx_experiencia",
 *   admin_label = @Translation("Servicios OnyxGroup"),
 *   category = @Translation("Servicios OnyxGroup"),
 * )
 */
class onyx_experiencia extends BlockBase implements BlockPluginInterface {

 /**
   * {@inheritdoc}
   */  
  public function build() {
    $config = $this->getConfiguration();
    $build = array();

    if (!empty($config['card_title'])) {
      $name = $config['card_title'];
    }
    else {
      $name = $this->t('Onyx Group Card');
    }

    if (!empty($config['card_text'])) {
      $cardText = $config['card_text'];
    }
    else {
      $cardText = $this->t('A service of Onyx Group');
    }

    $build[]['#attached']['library'][] = 'onyx_experiencia/onyx-experiencia-style';

    $build['CardTitle'] = array(
            '#prefix' => '',
            '#markup' => $name,
            '#suffix' => '',
        );

    $build['CardText'] = array(
            '#prefix' => '',
            '#markup' => $cardText,
            '#suffix' => '',
        );

    $cardImage = $this->configuration['card_image'];
    if (!empty($cardImage[0])) {
        if ($file = File::load($cardImage[0])) {
            $build['CardImg'] = array(
                '#theme' => 'image_style',
                '#style_name' => 'medium',
                '#uri' => $file->getFileUri(),
            );
        }
    }

    $cardLink = $this->configuration['card_link'];
    $build['CardLink'] = array(
        '#markup' => $cardLink,
    );

    return $build;

  }

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

    $config = $this->getConfiguration();

    $form['card_title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Card Title'),
      '#description' => $this->t('Type title of the service card.'),
      '#default_value' => isset($config['card_title']) ? $config['card_title'] : '',
    ];

    $form['card_text'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Card Text'),
      '#format' => 'full_html',
      '#description' => $this->t('Type the list of the services.'),
      '#default_value' => isset($config['card_text']) ? $config['card_text'] : '',
    ];

    $form['card_image'] = [
        '#type' => 'managed_file',
        '#title' => t('Card image background'),
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            'file_validate_size' => array(25600000),
        ),
        '#theme' => 'image_widget',
        '#preview_imgage_style' => 'medium',
        '#upload_location' => 'private://card_service_img',
        '#progress_message' => 'One moment while we save your file...',
        '#default_value' => isset($this->configuration['card_image']) ? $this->configuration['card_image'] : '',
        '#required' => TRUE,
    ];

    $form['card_link'] = [
        '#title' => t('Type card link. Example: /erp_cloud'),
        '#type' => 'url',
        '#default_value' => isset($this->configuration['card_link']) ? $this->configuration['card_link'] : '',

    ];

    return $form;
  }

 /**
   * Custom submit actions
   */
  public function custom_submit_form($form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    //Perform the required actions
  }

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

      $cardImage = $form_state->getValue('card_image');
      if ($cardImage != $this->configuration['card_image']) {
          if (!empty($cardImage[0])) {
              $file = File::load($cardImage[0]);
              $file->setPermanent();
              $file->save;
          }
      }

    $this->configuration['card_title'] = $form_state->getValue('card_title');
    $this->configuration['card_text'] = $form_state->getValue('card_text');
    $this->configuration['card_image'] = $form_state->getValue('card_image');
    $this->configuration['card_link'] = $form_state->getValue('card_link');
  }

}

Your Answer

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

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