in this article, I'll show you How to set default value of a managed file field in Drupal 8 & 9.
Question:
I created an edit custom form via a custom module. From this form, I have a managed file field and I set his default value to a fid; However, when my form is rendered, the managed file field doesn't show the image ratached. I don't understand why ?
My code:
$form['picture'] = array(
'#title' => t('picture'),
'#description' => $this->t('Chossir Image gif png jpg jpeg'),
'#type' => 'managed_file',
'#required' => true,
'#default_value' = 10, //Set 10 for the test, the fid "10" exist, I checked
'#upload_location' => 'public://images/',
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg')),
);
Solution:
You need to give the fid in array format. Please try it and let me know whether you got the result.
$form['picture'] = array(
'#title' => t('picture'),
'#description' => $this->t('Chossir Image gif png jpg jpeg'),
'#type' => 'managed_file',
'#required' => true,
'#default_value' => (isset($data['fid'])) ? [$data['fid']] : [],
'#upload_location' => 'public://images/',
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg')),
);