1 image_example.pages.inc image_example_style_form_submit($form, &$form_state)

Form Builder; Display a form for uploading an image.

Related topics

File

modules/examples/image_example/image_example.pages.inc, line 80
Page/form showing image styles in use.

Code

function image_example_style_form_submit($form, &$form_state) {
  $config = config('image_example.settings');

  // When using the #managed_file form element the file is automatically
  // uploaded an saved to the {file} table. The value of the corresponding
  // form element is set to the {file}.fid of the new file.
  //
  // If fid is not 0 we have a valid file.
  if ($form_state['values']['image_example_image_fid'] != 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 its status
    // to 1. Save the image ID for later use.
    $file = file_load($form_state['values']['image_example_image_fid']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    // When a module is managing a file, it must manage the usage count.
    // Here we increment the usage count with file_usage_add().
    file_usage_add($file, 'image_example', 'sample_image', 1);

    // Save the file ID, so that the module can reference it later.
    $config->set('image_example_image_fid', $file->fid);
    backdrop_set_message(t('The image @image_name was uploaded and saved with an ID of @fid and will be displayed using the style @style.', 
    array(
      '@image_name' => $file->filename,
      '@fid' => $file->fid,
      '@style' => $form_state['values']['image_example_style_name'],
    )
    ));
  }
  // If the file was removed we need to remove the module's reference to the
  // removed file's fid, and remove the file.
  elseif ($form_state['values']['image_example_image_fid'] == 0) {
    // Retrieve the old file's id.
    $fid = $config->get('image_example_image_fid');
    $file = $fid ? file_load($fid) : FALSE;
    if ($file) {
      // When a module is managing a file, it must manage the usage count.
      // Here we decrement the usage count with file_usage_delete().
      file_usage_delete($file, 'image_example', 'sample_image', 1);

      // The file_delete() function takes a file ID and checks to see if
      // the file is being used by any other modules. If it is the delete
      // operation is cancelled, otherwise the file is deleted.
      file_delete($file->fid);
    }

    // Either way the module needs to update its reference since even if the
    // file is in use by another module and not deleted we no longer want to
    // use it.
    $config->set('image_example_image_fid', FALSE);
    backdrop_set_message(t('The image @image_name was removed.', array('@image_name' => $file->filename)));
  }

  // Save the name of the image style chosen by the user.
  $config->set('image_example_style_name', $form_state['values']['image_example_style_name']);
  $config->save();
}