2

我创建了一个自定义配置实体表单,其中包含一个图像字段 {{ 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).

任何帮助将不胜感激 :)

4

1 回答 1

3

您不能直接在'#default_value'for a中设置文件实体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
);
于 2017-03-24T01:56:22.227 回答