Is there any example how to set up form element with type file to upload it via AJAX. I want to be same as field image in node type article.
thx
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityIs there any example how to set up form element with type file to upload it via AJAX. I want to be same as field image in node type article.
thx
Maybe this will be helpful (in a custom module):
function testmodule_forma($form, & $form_state) {
$form['im-container'] = array(
'#prefix' => '<div id="im-area">',
'#suffix' => '</div>',
);
$form['image_file'] = array(
'#type' => 'file',
);
$form['upload'] = array(
'#type' => 'submit',
'#value' => 'upload',
'#submit' => array('upload_image'),
'#ajax' => array(
'callback' => 'upload_image',
'wrapper' => 'im-area',
'method' => 'replace',
'effect' => 'fade',
),
);
return $form;
}
function upload_image($form, $form_state) {
$file = file_save_upload('image_file', array('file_validate_extensions' => array('png gif jpg jpeg')), "public://", FILE_EXISTS_REPLACE);
if ($file) {
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
$form['im-container'] = array(
'#title' => t('Preview:'),
'#prefix' => '<div id="im-area">',
'#markup' => '<img src="sites/default/files/'.$file - > filename.
'" height="250" width="250" />',
'#suffix' => '</div>',
);
} else {
drupal_set_message('No file uploaded.');
}
return $form['im-container'];
}
If you are using D7, Why you are writting messy code to achieve this task?
In D7 form API we have type = managed_file which uploads file using ajax.
Try this example:
$form['image'] = array(
'#type' => 'managed_file',
'#title' => t('Upload Image'),
'#default_value' => '',
'#required' => TRUE,
'#description' => t("Upload Image description"),
);