how to add default value for manged_file in custom configration entity type

1k views Asked by At

I have created a custom configuration entity form which have a image field {{ manged_file}} . Here, I have to set its default.

Below is my form element code:

$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).'),
  ];

When I submit form I got following error:

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).

Any help will be appreciated :)

1

There are 1 answers

0
valdeci On

You can not set a file entity directly in your '#default_value' for a managed_file, the default value receives by default a fid that is the unique id for files.

So to get the fid from a node for example, you need to get the target id for the file field that you want, like the bellow code:

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

And set it in your form something like this:

$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
);