0

I have a node type "Kaboodle" and its image field is media entity reference field. I want to set default image fid in image field value if user has not uploaded any image on the field while saving node edit form or adding new node.

Please provide solution if anyone has or share your logic so that I can solve this.

Thanks

2 Answers2

1

If you dont wanna save the data of your media you can even create a preprocess on your node type hook_preprocess_node__node_type(&$variables)

And add a media if the field is empty.

Sharklalu
  • 339
  • 1
  • 8
0

In a hook_node_presave(NodeInterface $node), for the $node->bundle() you want, if the value of your media field is empty set it to the media entity id you want (be careful this media entity id might be different between your dev and prod environments, you might need to load the media by title property in order to get its id). Just set the value for the field, it will be saved automatically when node_save wil be called.

MacSim
  • 374
  • 3
  • 10
  • Thanks for the response and solution. I am doing the same on hook_entity_presave and checking bundle of the entity. For saving fid I am using below code but it doesn't work and showing message "Unable to load the referenced entity." on node edit form Fid is set on the reference field target id but still not loading image. $entity->field_cover_image->target_id == $fid; I also tried to set $$file entity on the reference field target id but it also not worked. Please share code for setting fid on media entity reference field for image type. – Karuna Patel Oct 09 '20 at 06:14
  • Sorry I misread, the solution I gave was for an image field. Here you need to set the media entity id not the file id on hook_node_presave I am gonna edit the first answer – MacSim Oct 09 '20 at 16:08