I have a custom content entity. For this entity, I want add multiple uploaded files.
After I set this up, I looked at the database and saw:
file_managed => stores all files uploaded by a managed_file field
file_usage => links between your entity and the table file_managed
So for the managed_file field form, I don't need to create a field into my entity content (database), I just add a field into the EntityForm directly:
$form['image'] = array(
'#title'=>t('Image du produit'),
'#type' => 'managed_file',
'#upload_location' => 'public://produits/',
//'#default_value' => array(),
'#description' => t('png jpge jpg'),
'#upload_validators' => array(
'file_validate_extensions' => array('png jpg jpeg'),
),
'#multiple'=>true,
);
And then I can upload multiples files.
Then in my submit :
public function save(array $form, FormStateInterface $form_state) {
$entity = $this->entity;
foreach ($form_state->getValue('image') as $image) {
$file = \Drupal\file\Entity\File::load($image);
$file->setPermanent();
$file->save();
$file_usage = \Drupal::service('file.usage');
$file_usage->add($file, 'boutique', 'produits_entity',$entity->id());
}
}
I store image reference into the file_usage table and set it permanent. At this point all is good.
But I need to load all files when user want edit my entity, I can load this from the file_usage table and build my
'#default_value' => array($images)
I want to know if it's a good practice and if Drupal 8 work like that.
file_managed
andfile_usage
. An image item field is an entity reference to a file entity. It is entirely possible and OK to manage files yourself as you have done in your question, but the custom code may not be necessary.