File validation when the file field isn’t required

I have a Drupal 7 custom form where the image or file field is not required. When the form is submitted and no file/image has been uploaded, I get the following errors.

Notice: Undefined index: storage in jobform_my_form_submit() (line 136 of /var/www/html/drupaltst/sites/all/modules/jobpackage/jobform.module).
Warning: Creating default object from empty value in jobform_my_form_submit() (line 141 of var/www/html/drupaltst/sites/all/modules/jobpackage/jobform.module). Notice: Undefined property: stdClass::$uri in file_save() (line 601 of /var/www/html/drupaltst/includes/file.inc).

Any help is appreciated!

function jobform_permission() {   return array(     'add jobs module' => array(        'title' => t('Administer permission for your module'),        'description' => t('Some description that would appear on the permission page..'),     ),   ); }  function jobform_menu() {   $items = array();   //$items['jobform/form'] = array(   $items['jobform'] = array(     'title' => t('Job Form Details'),     'page callback' => 'jobform_form',     'page arguments' => array('jobform_form'),     'access arguments' => array('add jobs module'),     'description' => t('My form'),     'type' => MENU_CALLBACK,   );   return $items; }      function jobform_form() {   return drupal_get_form('jobform_my_form'); }   function jobform_my_form($form, &$form_state) {   $form['title'] = array(     '#type' => 'textfield',     '#title' => t('Title'),     '#required' => TRUE,     '#maxlength' => 100,     '#prefix' => '<div class="titletle"><img src="/drupaltst/sites/default/files/images/title_icon.png" height="50" width="45">',       '#suffix' => '</img></div>',      '#attributes' => array(        'placeholder' => t('Enter a Short Title'),      ),     );        $form['descr'] = array(      '#type' => 'textarea',      '#title' => t('Description'),      '#required' => TRUE,      '#size' => 150,      '#maxlength' => 5000,      '#prefix' => '<div class="titledescr"><img src="/drupaltst/sites/default/files/images/descr_req_icon.png" height="50" width="45">',       '#suffix' => '</img></div>',      '#attributes' => array(        'placeholder' => t('Enter some specific details about the service you provide!'),      ),     );           $form['location'] = array(      '#type' => 'textfield',      '#title' => t('Enter Your Location'),      '#required' => TRUE,      '#size' => 75,      '#prefix' => '<div class="titleloc"><img src="/drupaltst/sites/default/files/images/loc_icon.png" height="50" width="41">',       '#suffix' => '</img></div>',      '#attributes' => array(       'placeholder' => t('Where Can the Work Be Completed? (i.e. Online, City, State, Zip)'),      ),        );             //Image Field    $form['image'] = array(      '#type' => 'file',      '#title' => t('Upload a Photo'),      '#description' => t('Allowed extensions: gif png jpg jpeg'),      '#prefix' => '<br><div class="titlefile"><img src="/drupaltst/sites/default/files/images/upload_image_icon.png" height="50" width="41">',       '#suffix' => '</img></div>',    );    $form['submit'] = array(      '#type' => 'submit',      '#value' => 'Submit',      '#prefix' => '<br><div class="titlesubmit">',       '#suffix' => '</div>',    );           return $form;  }   function jobform_my_form_validate($form, &$form_state) {    $file = file_save_upload('image', array(      // Validates file is really an image.      'file_validate_is_image' => array(),      // Validate extensions.      'file_validate_extensions' => array('png gif jpg jpeg'),    ));    // If the file passed validation:    if ($file) {      // Move the file into the Drupal file system.      if ($file = file_move($file, 'public://images/')) {        // Save the file for use in the submit handler.        //$form_state['image'] = $file;        $form_state['storage']['image'] = $file;      }      else {        form_set_error('image', t("Failed to write the uploaded file to the site's file folder."));      }    }     else {      form_set_error('image', t('No file was uploaded.'));      //$file = file_move($file, 'public://images/title_icon.png');    }  }      function jobform_my_form_submit($form, $form_state) {        $file = $form_state['storage']['image'];    // We are done with the file, remove it from storage.    //unset($form_state['image']);    unset($form_state['storage']['image']);    // Make the storage of the file permanent.    $file->status = FILE_STATUS_PERMANENT;    // Save file status.    file_save($file);    global $user;     $na = 0;    $istat = 1;    db_insert('job_mp_catalog')      ->fields(array(        'user_id' => $user->uid,        'title' => $form_state['values']['title'],        'descr' => $form_state['values']['descr'],        'location' => $form_state['values']['location'],        'image' => $file->fid,))      ->execute();         drupal_set_message("successfully saved ");    //Example:    //drupal_goto("user/".$user->uid."/edit");    drupal_goto("content/test-page");    //drupal_set_message("successfully saved Job!");  } 
This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

File validation when the file field isn’t required

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.