4

I am trying to add items to a form (in code) similar to the add image item in the Drupal Add Content form that has the Browse and Upload buttons. In Firefox, the Browse button invokes a Pop-up window to search files on the user's computer and returns the selected file & path to the associated text box. I would like to review the code in Drupal to understand and duplicate the action. Thus far I cannot locate the code in core modules (its big in there and a file search does not find the word "Browse"!). Does anyone know where the add content form is, or a reference site that explains it, or how to code it?

1

I recently created a few custom blocks with image upload and preview fields. Here's the relevant code that should be helpful for you:

function mymodule_block_configure($delta = '') {
  // Uploaded image path is saved in a variable.
  $pic_path = variable_get('mymodule_pic1', FALSE);
  $form = array();
  if ($pic_path) {
    $form['preview'] = array(
      '#markup' => '<img src="'. image_style_url('mymodule_img_preview_style', $pic_path) .'" alt="'.t('Preview').'" />',
    );
  }
  // Image upload field.
  $form['image'] = array(
    '#type' => 'file',
    '#title' => t('Upload image from your computer'),
    '#description' => t('Allowed extensions: jpeg, jpg, png, gif'),
  );
  return $form;
}

function mymodule_block_save($delta = '', $edit = array()) {
  // Functionality to validate and save the file.
  $validators = array('file_validate_is_image' => array(), 'file_validate_extensions' => array('png gif jpg jpeg'));
  $file = file_save_upload('image', $validators, file_build_uri('mymodule_images'), FILE_EXISTS_REPLACE);
  if ($file) {
    $file->status |= FILE_STATUS_PERMANENT;
    $file = file_save($file);
    variable_set('mymodule_pic1', $file->destination);
  }
}
1

The functionality you're referring to is built into Firefox (and all other browsers) so you won't be able to find the code in the Drupal code base. It occurs whenever you use <input type="file"/>.

In order to get that functionality in your forms use the $form['image'] code that Dooshta provided.

0

If you are running Drupal 6, you need the Imagefield module (http://drupal.org/project/imagefield) but if running Drupal 7, it's already part of the core Content Construction Kit (CCK). To use it in either case, just create a content type with an image field and when you then create that content, it will bring up what you're used to seeing, eg, that browser form, when you input that field.

  • Thanks, but I am seeking the section in the code that implements the 'Browse' button. I have searched for the word in core modules without success. – Ashlar Dec 1 '11 at 13:47

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.