- Issue created by @markusdala
- 🇧🇷Brazil aluzzardi Pelotas, RS
I’m not sure if you’re familiar with working with hooks, but I couldn’t find a way to map file uploads to Media directly. So, I used the hook_entity_presave() to handle that.
function mymodule_ENTITY_TYPE_ID_presave(EntityInterface &$entity) { // On webform creation, if the entity is a node of type, // create a media entity for the field_logo if it exists. // This is to ensure that the field_logo is a media entity. // This is a workaround for the fact that webforms do not support media // entities directly. // Get field_logo target_id. $field_logo = $entity->get('field_logo'); $field_logo_value = $field_logo->getValue(); $logo_entity_type = $field_logo->entity; // If logo_entity_type is empty, it's a new media from webform as presave // from node add/edit will have the media entity already. if (isset($field_logo_value[0]['target_id']) && empty($logo_entity_type)) { // Get the file entity. $file = File::load($field_logo_value[0]['target_id']); if ($file) { // Create media entry. $media = Media::create([ 'bundle' => 'image', 'name' => $file->getFilename(), 'field_media_image' => [ 'target_id' => $file->id(), 'alt' => $file->getFilename(), ], 'field_caption' => $file->getFilename() ]); // Save the media entity. $media->save(); $entity->set('field_logo', [ 'target_id' => $media->id(), 'alt' => $file->getFilename(), ]); } } }