I am building a form and where te user can upload a file. Since I am using Drupal I am using the managed_file. The file is being uploaded but I cannot seem to get the filename out of the form... This is my code
Buildform:
$form['formfile'] = array(
'#type' => 'managed_file',
'#name' => 'formfile',
'#title' => t('File'),
'#upload_validators' => $validators,
'#upload_location' => 'public://trainingrequests/',
);
Submit
drupal_set_message($form_state->getValue('formfile'));
I have literally tried everything.
You first need to get the entity ID of the File entity, then load the entity:
$formfile = $form_state->getValue('formfile');
if ($formfile) {
$oNewFile = File::load(reset($formfile));
$oNewFile->setPermanent();
drupal_set_message('Filename: ' . $oNewFile->getFilename());
}
You can browse the source code of the File entity in your file system: core/modules/file/src/Entity/File.php
Related
Hi i have used this code
<?php
$elements = drupal_get_form("user_login");
$form = drupal_render($elements);
echo $form;
?>
to get the default Drupal login form for my site but I need to customize the HTML, I have found some pages in module/users but did not understand how to customize the structure.
The user login form for Drupal is built by the user_login function in user.module using Drupal Form API. If you need to customize it, you should do it using hook_form_alter() in your module
function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
if ($form_id=='user_login') {
// YOUR CUSTOM CODE FOR THE FORM GOES HERE
}
}
** EDIT, AFTER YOUR COMMENT **
You don't need to call the YOUR_MODULE_NAME_form_alter() function: Drupal does that for you via the hook mechanism everytime it needs to build a form, and, when $form_id=='user_login', it modifies the login form to allow your customization. The way Drupal does that is discussed in detail in drupal.org, just follow the link I wrote at the beginning of this answer.
The user login form is declared this way in user.module:
// Display login form:
$form['name'] = array('#type' => 'textfield',
'#title' => t('Username'),
'#size' => 60,
'#maxlength' => USERNAME_MAX_LENGTH,
'#required' => TRUE,
);
$form['name']['#description'] = t('Enter your #s username.', array('#s' => variable_get('site_name', 'Drupal')));
$form['pass'] = array('#type' => 'password',
'#title' => t('Password'),
'#description' => t('Enter the password that accompanies your username.'),
'#required' => TRUE,
);
$form['#validate'] = user_login_default_validators();
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Log in'));
The $form array is passed by reference to your hook_form_alter() before being rendered, allowing for customization. So, let's say that you want to change the label of the textfield for the user name from "Username" to "Name of the User", you write
$form['name']['#title'] = t("Name of the User");
in your custom code. If you want to add another field to the form (a textarea, for example), you do
$form['otherfield'] = array(
'#title' => t('My new custom textarea'),
'#type' => 'textarea',
'#description' => t("A description of what this area is for"),
'#cols' => 10,
'#rows' => 3,
'#weight' => 20,
);
and Drupal will add the field to the user login form.
There are many different kind of fields and properties that you can customize this way: I encourage you to fully read the Form API documentation. This way you let Drupal take care of form generation, translation, rendering, validation and submission, also permitting to other modules to manipulate your form if needed.
I hope it's clear, have a good day.
use this in template.php
function themename_theme() {
$items = array();
$items['user_login'] = array(
'render element' => 'form',
'path' => drupal_get_path('theme', 'corporateclean') . '/templates',
'template' => 'user-login',
);
and create a template folder and within that create a file user-login.tpl.php and in this file you can put your html and could customize drupal login
I have a custom form, with a field for the user to upload an image file (their logo). In the form validate hook, I've implemented file_save_upload, which is continually returning false. I can see that the file is in fact being saved in the correct location on upload, so why isn't file_save_upload working?
The form field:
$form['company_logo'] = array(
'#type' => 'managed_file',
'#title' => t('Company Logo'),
'#description' => t('Allowed extensions: gif png jpg jpeg'),
'#upload_location' => 'public://uploads/',
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
// Pass the maximum file size in bytes
//'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
),
);
The validation hook:
$file = file_save_upload( 'company_logo' , array(), 'public://uploads/', FILE_EXISTS_RENAME);
if (!$file) {
form_set_error('company_logo', t('Unable to access file or file is missing.'));
}
The managed file element handles moving the uploaded file for you, so there's no need to call file_save_upload() manually.
You're getting a NULL return because of these lines in file_save_upload():
// Make sure there's an upload to process.
if (empty($_FILES['files']['name'][$source])) {
return NULL;
}
As the file's already been processed there's nothing for the function to do.
You can persist the file entry by adding a submit handler to the form and using code similar to
$file = file_load($form_state['values']['company_logo']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
I am building a theme with ability to upload custom background images but now I am stuck at a point.
How do I properly add FILE field in drupal form via theme-setting.php and after that how can I get public url to this file in my template files??
In your theme_form_system_theme_settings_alter hook you need to add the following form element:
$form['theme_settings']['background_file'] = array(
'#type' => 'managed_file',
'#title' => t('Background'),
'#required' => FALSE,
'#upload_location' => file_default_scheme() . '://theme/backgrounds/',
'#default_value' => theme_get_setting('background_file'),
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
),
);
This will save the file id to your theme settigns variable 'background_file', notice that i set the upload location to theme/backgrounds, this will be inside your files folder.
Finally you'll get the complete URL to the file with file_create_url:
$fid = theme_get_setting('background_file');
$image_url = file_create_url(file_load($fid)->uri);
Edit:
In your template.php you can add in the theme_preprocess_page hook the variable so all the tpl's can access it, this is how:
function theme_preprocess_page(&$variables, $hook) {
$fid = theme_get_setting('background_file');
$variables['background_url'] = file_create_url(file_load($fid)->uri);
}
Hope this helps! :D
I have a file upload form
how can I retain this file when there are other validation errors so that the user doesn't have to upload the file again?
I tried this in my validation function but it doesn't work:
function mymodule_someform_validate($form, &$form_state) {
$form_state["values"]["some_field"] = some_value;
}
the $form_state["values"] variable is not available in my form definition function - mymodule_someform($form, &$form_state)
Any ideas?
Just use the managed_file type, it'll do it for you:
$form['my_file_field'] = array(
'#type' => 'managed_file',
'#title' => 'File',
'#upload_location' => 'public://my-folder/'
);
And then in your submit handler:
// Load the file via file.fid.
$file = file_load($form_state['values']['my_file_field']);
// Change status to permanent.
$file->status = FILE_STATUS_PERMANENT;
// Save.
file_save($file);
If the validation fails and the user leaves the form, the file will be automatically deleted a few hours later (as all files in the file_managed table without FILE_STATUS_PERMANENT are). If the validation doesn't fail, the submit handler will be run and the file will be marked as permanent in the system.
Admin form example for others who may be looking:
function example_admin_form(){
$form = array();
$form['image'] = array(
'#type' => 'managed_file',
'#name' => 'image',
'#title' => t('upload your image here!'),
'#default_value' => variable_get('image', ''),
'#description' => t("Here you can upload an image"),
'#progress_indicator' => 'bar',
'#upload_location' => 'public://my_images/'
);
// Add your submit function to the #submit array
$form['#submit'][] = 'example_admin_form_submit';
return system_settings_form($form);
}
function example_admin_form_submit($form, &$form_state){
// Load the file
$file = file_load($form_state['values']['image']);
// Change status to permanent.
$file->status = FILE_STATUS_PERMANENT;
// Save.
file_save($file);
}
How can I process a file upload in a module configuration section? Here is what I have so far.
<?php
function dc_staff_directory_admin_settings()
{
$form['dc_staff_directory_upload_file'] = array(
'#type' => 'file',
'#title' => t('Upload staff directory excel (.xls) file'),
'#description' => t('Uploading a file will replace the current staff directory'),
);
$form['#submit'][] = 'dc_staff_directory_process_uploaded_file';
return system_settings_form($form);
}
function dc_staff_directory_process_uploaded_file($form, &$form_state)
{
//What can I do here to get the file data?
}
If you use the managed_file type instead Drupal will do most of the processing for you, you just need to mark the file for permanent storage in your submit function:
function dc_staff_directory_admin_settings() {
$form['dc_staff_directory_upload_file'] = array(
'#type' => 'managed_file',
'#title' => t('Upload staff directory excel (.xls) file'),
'#description' => t('Uploading a file will replace the current staff directory'),
'#upload_location' => 'public://path/'
);
$form['#submit'][] = 'dc_staff_directory_process_uploaded_file';
$form['#validate'][] = 'dc_staff_directory_validate_uploaded_file';
return system_settings_form($form);
}
function db_staff_directory_validate_uploaded_file($form, &$form_state) {
if (!isset($form_state['values']['dc_staff_directory_upload_file']) || !is_numeric($form_state['values']['dc_staff_directory_upload_file'])) {
form_set_error('dc_staff_directory_upload_file', t('Please select an file to upload.'));
}
}
function dc_staff_directory_process_uploaded_file($form, &$form_state) {
if ($form_state['values']['dc_staff_directory_upload_file'] != 0) {
// The new file's status is set to 0 or temporary and in order to ensure
// that the file is not removed after 6 hours we need to change it's status
// to 1.
$file = file_load($form_state['values']['dc_staff_directory_upload_file']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
}
}
The validate function is probably a good idea as well, obviously you won't need it if the file is not a required field.
This is mostly taken from the image_example module, part of the Examples Module. If you really don't want to use the managed_file type have a look at the file_example module in that same collection, it has examples of how to uploaded an unmanaged file.
Hope that helps