Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By rk.lubo on
Hi all,
Please, Someone can help me with the best way to upload and rename my file with managed_file field.
I tried this code, everything is good but my files are temporary:
BuildForm
$form['test_field'] = array(
'#title' => 'Join file',
'#type' => 'file',
);
$form['valider'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
return $form;
ValidateForm
public function validateForm(array &$form, FormStateInterface $form_state) {
$validators = array(
'file_validate_size' => array(2 * 1024 * 1024), // 2MB file size limit
);
$file = file_save_upload('test_field', $validators, 'public://my_folder', FILE_EXISTS_RENAME);
if ($file== NULL) {
$form_state->setErrorByName('test_field', 'Error');
return;
}
$parts = pathinfo($file->getFileUri());
$form_state->setValue('test_field', $parts[basename]);
if (null !== $file) {
$file->save();
$file= reset($file);
}
}