web-dev-qa-db-ja.com

設定フォームからアップロードされた画像をレンダリングする方法

私はブロックを含むカスタムモジュールに取り組んでいますが、現在、ブロックの構成でフォームを介してアップロードされている画像をレンダリングする問題があります。

このエラーが発生します:

エラー:Drupal\onyx_experiencia\Plugin\Block\onyx_experiencia-> build()のnullでメンバー関数getFileUri()を呼び出す(行52 ...)

ファイルは指定されたディレクトリに正しくアップロードされています。同様の問題やエラーについて読んでいますが、正しい解決策が見つかりません。

私が達成しようとしているのは、フォームからアップロードされた画像のuriを取得することです。最初にエンティティまたはイメージをロードするために必要な場合があることを読みました。すでに試しましたが、同じエラーが発生しますが、ファイルをロードしようとした行に表示されます。

これはコードです:

<?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
Hawk

ようやく機能しましたが、少し迷っていました。重要なのは、blockSubmit functionでイメージを正しく送信し、build function

これは私のために働いている最後のコードです

<?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');
  }

}
1
Hawk