0

I have added my code below which is used to upload a resume in CSV format, but now the requirement changed, and it is required I add the resumes in all formats (docx and doc). I have tried adding '#file_validate_extensions' => array('csv,docx'), but that gives me an error Incorrect string value for title. What are the modifications that should be done in the code to upload the resumes in all formats?

/**
 * @file
 * Contains \Drupal\custom_migration\Form\UploadForm.
 */

namespace Drupal\custom_migration\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;
use Drupal\Core\Form\FormState;
use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;

class CsvUploadForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'csv_upload_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $file_size = t('Maximum file size: %size MB.', array('size' => file_upload_max_size()));
    $form['file_upload'] = array( 
      '#type' => 'file', 
      '#title' => t('File'), 
      '#size' => 40, 
      '#description' => t('Select the CSV file to be imported. ') . $file_size
    ); 
    $form['submit'] = array( '#type' => 'submit', '#value' => t('Save'), ); 
    // set the form encoding type 
    // $form['#attributes']['enctype'] = "multipart/form-data"; 
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $destination='public://csv';
    if (!file_exists($destination)) {
      mkdir($destination, 0777, true);
    }
    $validators = array('file_validate_extensions' => array('csv'));
    $file = file_save_upload('file_upload', $validators, $destination, $replace = FILE_EXISTS_RENAME);
    // check file uploaded OK 
    if (!$file) { 
      $form_state->setErrorByName('file_upload', t('A file must be uploaded'));
    } 
    else { 
      // set files to form_state, to process when form is submitted 
      $form_state->setValue('file_upload', array($file));
    } 
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // drupal_set_message($this->t('@can_name ,Your application is being submitted!', array('@can_name' => $form_state->getValue('candidate_name'))));
    /* Fetch the array of the  file stored temporarily in database */
    $line_max = \Drupal::state()->get('user_import_line_max', 1000);
    ini_set('auto_detect_line_endings', true);
    $filepath = ($form_state->getValue('file_upload')[0]->getFileUri());
    $handle = @fopen($filepath, "r");
    $job_id=\Drupal::request()->query->get('job_id');
    $row = 1;
    if ($handle !== FALSE) {
      while (($data = str_fgetcsv($handle, $line_max, ','))!==FALSE) {
        if ($row == 1) {
          $row++;
          continue;
        }
        $node = Node::create(array(
          'type' => 'job_application',
          'title' => $data[1],
          'langcode' => 'en',
          'uid' => \Drupal::currentUser()->id(),
          'status' => 1,
          'field_fields' => array(),
        ));
        $node->field_email= $data[2];
        $node->field_notice_period = $data[5];
        $node->field_phone_number = $data[6];
        $node->field_i_agree_terms_and_conditio=1;
        $node->field_job_list=$job_id;
        $node->field_resume_status=$this->getTidByName('Applied');
        $location_vocabulary = 'location';
        $tid_l1 = $this->getTidByName($data[3]);
        if (!empty($data[3]) && $tid_l1 === 0) {
          $term = $this->createNewTerm($data[3],$location_vocabulary);
          $node->field_current_location = $term;
        }
        else{
          $node->field_current_location=$this->getTidByName($data[3]);
        }
        $tid_l2 = $this->getTidByName($data[4]);
        if (!empty($data[4]) && $tid_l2 === 0) {
          $term = $this->createNewTerm($data[4],$location_vocabulary);
          $node->field_preferred_location = $term;
        }
        else {
          $node->field_preferred_location = $this->getTidByName($data[3]);
        }
        $field_values = array(
          'uri' => file_create_url('sites/default/files/'.$data[7]),
          'uid' => \Drupal::currentUser()->id(),
          'status' => 0,
        );
        $file = File::create($field_values);
        $file->save();
        $node->field_resume->setValue([
          'target_id' => $file->id(),
        ]);
        $skills_vocabulary = 'skill_sets';
        $skills = $data[8];                                                                                                      
        $node->field_applicant_skills = $skills;
        $node->save();
        $row++;
      }
      fclose($handle);
    }
    drupal_set_message($this->t('You have sucessfully uploaded resumes.'));       
    $form_state->setRedirect('view.review_requirements.review_jobs_page');
  }  

  /**
   * Utility: find term by name and vid.
   * @param null $name
   *  Term name
   * @param null $vid
   *  Term vid
   * @return int
   *  Term id or 0 if none.
   */
  public function getTidByName($name = NULL, $vid = NULL) {
    $properties = [];
    if (!empty($name)) {
      $properties['name'] = $name;
    }
    if (!empty($vid)) {
      $properties['vid'] = $vid;
    }
    $terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadByProperties($properties);
    $term = reset($terms);
    return !empty($term) ? $term->id() : 0;
  }

  public function createNewTerm($value, $categories_vocabulary) {
    $term = Term::create(array(
      'parent' => array(),
      'name' => $value,
      'vid' => $categories_vocabulary,
    ))->save();
    return $term;
  }

}
0

I think you have to replace the file types in the following line.

$validators = array('file_validate_extensions' => array('csv'));

Change it to this.

$validators = array('file_validate_extensions' => array('docx','doc'));

Also, in submitForm() you are parsing the CSV file using str_fgetcsv() and importing the data in a node. So you have to find another way parsing your new data and creating this node.

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.