【问题标题】:how to add default value for manged_file in custom configration entity type如何在自定义配置实体类型中为托管文件添加默认值
【发布时间】:2017-08-12 15:36:05
【问题描述】:

我创建了一个自定义配置实体表单,其中包含一个图像字段 {{ manged_file}} 。在这里,我必须设置它的默认值。

下面是我的表单元素代码:

$img = $vajra_entity->getBgimage();

  $form['background']['bgimage'] = [
    '#type'              => 'managed_file',
    '#title'             => t('Background Image'),
    '#default_value'     => $img,
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),
      'file_validate_size'       => array(25600000),
    ),
    '#upload_location'   => 'public://Background',
    '#description'       => $this->t('Add image for body of a page (gif, png, jpg, jpeg).'),
  ];

当我提交表单时出现以下错误:

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[HY000]: General error: 1364 Field 'type' doesn't have a default value: INSERT INTO {file_managed} (uuid, langcode, uid, filename, uri, filemime, filesize, status, created, changed) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 77433757-4b5c-432b-b7d4-b647e90d40bf [:db_insert_placeholder_1] => en [:db_insert_placeholder_2] => 1 [:db_insert_placeholder_3] => 2015-8-14-drupal-8-hero_0.png [:db_insert_placeholder_4] => public://Background/2015-8-14-drupal-8-hero_0_0.png [:db_insert_placeholder_5] => image/png [:db_insert_placeholder_6] => 6119 [:db_insert_placeholder_7] => 0 [:db_insert_placeholder_8] => 1490073466 [:db_insert_placeholder_9] => 1490073466 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->doSaveFieldItems() (line 843 of /opt/lampp/htdocs/webarch/docroot/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

任何帮助将不胜感激:)

【问题讨论】:

    标签: forms drupal-8 managed-file


    【解决方案1】:

    您不能直接在'#default_value' 中为managed_file 设置文件实体,默认值默认接收一个fid,它是文件的唯一ID。

    因此,例如,要从节点获取 fid,您需要获取所需文件字段的目标 id,如下面的代码:

    $values['fids'][0] = $node_with_image->field_image->target_id;
    

    并在您的表单中设置如下:

    $form['default_image']['uuid'] = array(
      '#type' => 'managed_file',
      '#title' => t('Image'),
      '#description' => t('Image to be shown if no image is uploaded.'),
      '#default_value' => $values
    );
    

    【讨论】:

      猜你喜欢
      • 2021-08-22
      • 2018-03-30
      • 1970-01-01
      • 2012-11-13
      • 2013-11-03
      • 2012-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多