4

I am trying to create one basic module for Drupal 8, where I have added one form with some textfields and multiple file upload element. Now on "submitForm" I am saving textfields values on database, but I am not sure how I can save image fields. I will be only saving the filename in the database.

Will it be using same function as we have in Drupal 7?

8

If you upload a file, it stores the file temporarily in file_managed table in database.And you have to set the file permanent status 1 to save it permanently else it will be deleted from the table by cron after some time.
This sample code to load a image and save it to database might help you to understand.

/* Fetch the array of the image file stored temporarily in database */
$image = $form_state->getValue ('image');

/* Load the object of the image file by it's fid */
$file = File::load ($image[0]);

/* Set the status flag permanent of the image file object */
$file->setPermanent();

/* Save the file in database ( "managed_file" table) */
$file->save();

when you select any file from 'managed_file' field type, drupal make a entry in 'file_managed' table, you just have to set the permanent flag as above to decide whether you have to save it permanently or not.

  • @parth.k , you may accept the answer if it worked for you so other people see easily the answer is right. – sanzante Feb 23 '17 at 10:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.