CSV File To DB In Yii

CSV File Upload

Using the below code i created the form "importcsvform.php".

importcsvform

<div class="form">
<?php 
$form=$this->beginWidget('CActiveForm', array(
    'id'=>'csv-form',
    'enableAjaxValidation'=>false,
    'htmlOptions'=>array('enctype' => 'multipart/form-data'),
)); 
?>

<?php 
//echo $form->errorSummary($model); 
?>

<div class="row">
<?php echo $form->labelEx($model,'csvfile'); ?>
<?php 
    $this->widget('CMultiFileUpload', array(
        'model'=>$model,
        'name' => 'csvfile',
        'max'=>1,
        'accept' => 'csv',
        'duplicate' => 'Duplicate file!', 
        'denied' => 'Invalid file type',              
    ));
?>
<?php echo $form->error($model,'csvfile'); ?>
</div>

<div class="row buttons">
    <?php echo CHtml::submitButton('Import',array("id"=>"Import",'name'=>'Import')); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->

Read CSV In Controller

CSV file contains the data in follwoing format

Name Age
Yii 20
Framework 25

public function actionImport(){
    $model=new Csv;
    if(isset($_POST['csv']))
    {
        $model->attributes=$_POST['csv'];
        $filelist=CUploadedFile::getInstancesByName('csvfile');
        // To validate 
        if($filelist)
            $model->csvfile=1;

        if($model->validate())
        {
            foreach($filelist as $file)
            {
                try{
                    $transaction = Yii::app()->db->beginTransaction();
                    $handle = fopen("$file->tempName", "r");
                    $row = 1;
                    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                        if($row>1){
                            $newmodel=new Csv;       
                            $newmodel->name=$data[0];
                            $newmodel->age=$data[1];
                            $newmodel->save();            
                        }
                        $row++;               
                    }
                    $transaction->commit();
                }catch(Exception $error){
                    print_r($error);
                    $transaction->rollback();
                }                    
            }                            
        }                        
    }
    $this->render('importcsvform',array(
        'model'=>$model,
    ));        
}


  • What is $_POST[‘csv’]? I can’t find form element has name ‘csv’ in view

    • m bala

      $_POST[‘csv’] is a form name. If we submit the form, we will process the value inside the form

      • I see form’s id is ‘csv-form’. So, why form name is ‘csv’?

        • m bala

          SORRY, It is not a form name. My model name is ‘csv’ and yii will display the input fields like below.

          When we submit the form, we will get it as multidimensional array (csv[name], etc) in controller. so we have to validate the form is submitted or not using $_POST[‘csv’] value,