1

I want to important a .csv file to database table with the validations..

I have a function add user on a add user form, It has validation on extension number, which is unique..

I also have an option to add bulk users using .csv file. I can add users to it but how to add validations to it, when i try to upload .csv file with user details, it should show error that extension is already used but upload other extension numbers.

for example if the .csv have 100 users, and 80 users are uploaded, but 20 users are not uploaded because their extension number already exists in database table, so i want these 20 to be exported in .csv file. and display error.

My model is

I have a company, each company has many users, each user has unique extension number. if extension number 100 is assigned to user 1 then it cannot be assigned to user 2.

How can i achieve this? any suggestions, help with some code.? Thanks

2 Answers 2

1

Generally, if you are using Yii with any DataBase, you should be maintaining a Model class which extends ActiveQuery like so:

<?php

namespace common\models;

use Yii;

class Profile extends \yii\db\ActiveRecord
{
public static function tableName()
{
    return 'TABLE_NAME';
}

public function rules()
{
    return [
        [['Phone', 'Email'], 'required'],
        [['Phone'], 'string', 'max' => 30],
        [['Email'], 'string', 'max' => 100],
    ];
}

public function attributeLabels()
{
    return [
        'Phone' => Yii::t('profile', 'Phone'),
        'Email' => Yii::t('profile', 'Email')
    ];
}

As you can see you can declare your Validation rules in the return of function rules(). The ones in the example here are very simple, however, many other built-in validators exist along with the ability to use your own custom validators, including the possibility of adding JS validation. You can read more about it here.

Now, when you are using your Model, you have to load data into it and validate it to save it afterwards. First of all, making sure that your input is Valid (in this case a .csv file) on the PHP server before sending it to the DataBase is more correct in my opinion, rather than receive a "hard error" from the DataBase's validation engine. Anyhow, in order to load the data into the model, we first need to load the .csv as a string. For this place your .csv into the projects folder, somewhere like \common\models\file.csv

<?php
$csv = file_get_contents(Yii::getAlias('@app/common/models/').'file.csv');
$csvArray = str_getcsv($csv);
$errorCsvArray = [];

foreach ($csvArray as $newEntry) {
    $model = new \common\models\Profile();
    if ($model->load($newEntry)) {
        $model->save();
    } else {
        $errorCsvArray[] = $model->errors;
    }
}

All that is left, is to convert $errorCsvArray to .csv. One way of doing this you can find here.

Moreover, notice that load() also validates before populating the model. More on load(), validate(), save() and errors you can find here.

Sign up to request clarification or add additional context in comments.

Comments

0

In my Yii application also having employee import. In that unique field is employee code. My function is,

 public function actionEmployeeimport() {
    $model = new ContactForm;
    if (isset($_POST['ContactForm'])) {
        $model->attributes = $_POST['ContactForm'];
        $uploadedFile = CUploadedFile::getInstance($model, 'filea');
        if ($uploadedFile == "") {
            Yii::app()->user->setFlash('error', 'Please select a file.');
        } else {
            $allowed = array('xlsx', 'xls');
            $filename = CUploadedFile::getInstance($model, 'filea');
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
            if (!in_array($ext, $allowed)) {
                throw new CHttpException(404, 'File extension error. The allowed extension is xlsx.');
                exit(0);
            } else {

                $ext = end((explode(".", $uploadedFile)));
                $timezone = new DateTimeZone(Yii::app()->params['timezone']);
                $date = new DateTime();
                $date->setTimezone($timezone);
                $date = $date->format('dmYhis');
                $fileName = "{$date}.{$ext}";
                if (isset($uploadedFile)) {
                    $uploadedFile->saveAs(Yii::app()->basePath . '/../banner/' . $fileName);
                }
                //reading portion : here each column is read row and column wise; please check the sample
                //import file to get the column format. The heading row can be kept. The heading is ignored
                //while reading the excel or csv file.

                $sheet_array = Yii::app()->yexcel->readActiveSheet(Yii::app()->basePath . '/../banner/' . $fileName);
                $count = 0;
                foreach ($sheet_array as $row) {
                    $count = $count + 1;
                }
                for ($x = 2; $x <= $count; $x++) {

                    try {
                        if ($sheet_array[$x]['A'] == "" && $sheet_array[$x]['B'] == "" && $sheet_array[$x]['C'] == "" && $sheet_array[$x]['D'] == "" && $sheet_array[$x]['E'] == "" && $sheet_array[$x]['F'] == "" && $sheet_array[$x]['G'] == "" && $sheet_array[$x]['H'] == "" && $sheet_array[$x]['I'] == "" && $sheet_array[$x]['J'] == "" && $sheet_array[$x]['K'] == "" && $sheet_array[$x]['L'] == "" && $sheet_array[$x]['M'] == "" && $sheet_array[$x]['N'] == "" && $sheet_array[$x]['O'] == "" && $sheet_array[$x]['P'] == "" && $sheet_array[$x]['Q'] == "" && $sheet_array[$x]['R'] == "" && $sheet_array[$x]['S'] == "" && $sheet_array[$x]['T'] == "" && $sheet_array[$x]['U'] == "" && $sheet_array[$x]['V'] == "") {
                            $this->redirect(array('/core/employeedetails/admin'), array('message' => 'Successfuly Updated!'));
                        }
                        $employee_master = new Employeemaster;
                        $emp_code = Employeemaster::model()->findByAttributes(array('employee_code' => $sheet_array[$x]['A']));

                        if ($sheet_array[$x]['A'] == "") {
                            throw new CHttpException(404, 'Row number :' . $x . 'The field employee code validation error');
                            exit(0);
                        } elseif ($emp_code != "") {
                            throw new CHttpException(404, 'Row number :' . $x . 'Employee code already exist.');
                            exit(0);
                        } else {
                            $institution = Institution::model()->findByPk(Yii::app()->user->institutionid);
                            if ($institution->isautogeneration === '1') {
                                $schoolcode = $institution->institution_code;
                                $employee_master->employee_code = "e" . $schoolcode . $sheet_array[$x]['A'];
                            } else {
                                $employee_master->employee_code = "e" . $sheet_array[$x]['A'];
                            }
                        }
                        if ($sheet_array[$x]['B'] == "") {
                            throw new CHttpException(404, 'Row number :' . $x . 'The field employee name validation error');
                            exit(0);
                        } else {
                            $employee_master->employee_firstname = $sheet_array[$x]['B'];
                        }
                        $employee_master->employee_middlename = $sheet_array[$x]['C'];
                        $employee_master->employee_lastname = $sheet_array[$x]['D'];
                        if ($sheet_array[$x]['E'] == "") {
                            throw new CHttpException(404, 'Row number :' . $x . 'The field date of birth validation error');
                            exit(0);
                        } else {
                            $date1 = date_create($sheet_array[$x]['E']);
                            $date = date_format($date1, 'Y-m-d');
                            $employee_master->employee_dob = $date;
                        }
                        if ($sheet_array[$x]['F'] == "") {
                            throw new CHttpException(404, 'Row number :' . $x . 'The field gender validation error');
                            exit(0);
                        } else {
                            $gender = (strcasecmp($sheet_array[$x]['F'], "female")) ? 1 : 2;
                            $employee_master->employee_gender = $gender;
                        }
                        $department = Department::model()->findByAttributes(array('department_name' => $sheet_array[$x]['G']));
                        if ($department == "") {
                            throw new CHttpException(404, 'Row number :' . $x . 'The field department validation error');
                            exit(0);
                        } else {
                            $employee_master->departmentid = $department->departmentid;
                        }
                        $designation = Designation::model()->findByAttributes(array('designation_name' => $sheet_array[$x]['I']));

                        if ($designation == "") {
                            throw new CHttpException(404, 'Row number :' . $x . 'The field designation validation error');
                            exit(0);
                        } else {
                            $employee_master->designationid = $designation->designationid;
                        }
                        if ($sheet_array[$x]['J'] == "") {
                            throw new CHttpException(404, 'Row number :' . $x . 'The field joining date validation error');
                            exit(0);
                        } else {
                            $date1 = date_create($sheet_array[$x]['J']);
                            $date = date_format($date1, 'Y-m-d');
                            $employee_master->employee_joiningdate = $date;
                        }
                        $employee_master->institutionid = $sheet_array[$x]['H'];
                        $employee_master->status = 1; //! existing employee
                        $employee_master->save(false);} catch (CDbException $e) {
                        throw new CHttpException(404, 'Something went wrong while uploading your excel file.');
                    }
                }
//                $this->render('contact_emp', array('model' => $model, 'message' => 'Successfuly Updated!'));
                if ($x == 2) {
                    $this->render('contact', array('model' => $model, 'message' => 'The file you uploaded is empty.!'));
                } else {
                    $this->redirect(array('/core/employeedetails/admin'), array('message' => 'Successfuly Updated!'));
                }
            }
        }
    }

    $this->render('contact_emp', array('model' => $model, 'message' => ''));
}

I think this will help you. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.