how to change taxonomy term fields before being created first time I'm trying to copy parent's image field to a "goint to be created" taxonomy term using this code but it isn't working:

function my_module_taxonomy_term_insert($term) {
    if ($term-&gt;vid == 29) {

        //if any of parents have logo then copy it
            foreach ($term-&gt;parent as $p) {

            if (isset($p-&gt;field_image[LANGUAGE_NONE][0]['fid'])) {
                //copy the image
                $filepath = drupal_realpath($p-&gt;field_image[LANGUAGE_NONE][0]['uri']);

                // Create managed File object and associate with Image field.
                $file = (object) array(
                            'uid' =&gt; 1,
                            'uri' =&gt; $filepath,
                            'filemime' =&gt; file_get_mimetype($filepath),
                            'status' =&gt; 1,
                );

                $term-&gt;field_image[LANGUAGE_NONE][0] = (array) $file;
            }
        }
    }
}


How to do this?
In Drupal 7, you can achieve this by using the following taxonomy APIs


hook_taxonomy_term_insert : Act on taxonomy terms when inserted.
taxonomy_term_load : To load the taxonomy by using term ID
taxonomy_term_save : To update the taxonomy by using term ID



/**
 * Implementing hook_taxonomy_term_insert
 */
function hook_taxonomy_term_insert($term) {
  $vid = 2; //User your vid
  if (is_object($term) && $term->vid == $vid && isset($term->parent)) {
    //get parent tid using $term->parent array
    foreach ($term->parent as $ptid) {//check image for each parent, if image exist assign and exit
      if ($ptid > 0) {//except root
        //get parent image WHERE field_data_field_image_vocab_image is the parent image field
        $pfid = db_select('field_data_field_image_vocab_image', 'pimg')//change field_data_field_image_vocab_image with your field name
            ->condition('pimg.entity_id', $ptid, '=')
            ->fields('pimg', array('field_image_vocab_image_fid'))//change field_image_vocab_image_fid with your image fid name
            ->execute()->fetchField();
        $update_taxo = taxonomy_term_load($term->tid); //load created taxonomy
        if ($pfid > 0 && empty($update_taxo->field_image_vocab_image)) {//image exist for this parent $ptid and image is not assigned yet
          $update_taxo->field_image_vocab_image[LANGUAGE_NONE][0]['fid'] = $pfid;
          taxonomy_term_save($update_taxo); //update taxonomy after assigning image
          break; //break after saving the image
        }
      }
    }
  }
}


Note : 


Change the field names
Go through the comments for explanation.