I am trying to upload CSV file using an Yii framework. I have added the code below :
Model
<?php
class Import extends CModel
{
public $name,$email,$doctor = 0,$hospital = 0,$diagnostic = 0;
public function rules()
{
return array(
array('name,email,doctor,hospital,diagnostic','required')
);
}
public function attributeNames()
{
return array();
}
}
?>
View(index.php)
<div class="form">
<?php echo CHtml::beginForm('site/import',$method='post',$htmlOptions =array('enctype'=>'multipart/form-data')); ?>
<div class="row">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" name="filename" value="file">
<?php echo CHtml::submitButton('Submit', array('name'=>'submitCSV')); ?>
<?php
if(is_array($buffer))
{
foreach($buffer as $line){
echo '<div class="clear"></div>';
echo CHtml::activeTextField($buffer[0],'name',array('value',$line['name']));
echo CHtml::activeTextField($buffer[0],'email',array('value',$line['email']));
echo CHtml::activeTextField($buffer[0],'doctor',array('value',$line['doctor']));
echo CHtml::activeTextField($buffer[0],'hospital',array('value',$line['hospital']));
echo CHtml::activeTextField($buffer[0],'diagnostic',array('value',$line['diagnostic']));
}}?>
</div>
<?php echo CHtml::endForm(); ?>
</div>
Controller
public function actionImport()
{
$model = new Import;
$buffer = array($model);
if(isset($_POST['submitCSV'])){
$filename=$_FILES['filename']['tmp_name'];
$fp = fopen("$filename","r");
if($fp){
$i =0;
while(($buffer[$i] = fgetcsv($fp,1000,",")) !== false)
{
$model = new Import;
$model->name = $buffer[$i][0];
$model->email = $buffer[$i][1];
$model->doctor = $buffer[$i][2];
$model->hospital = $buffer[$i][3];
$model->diagnostic = $buffer[$i][4];
$buffer[$i++] = $model;
}
if(!feof($fp))
echo "Echo: Unexpected fgets() fail\n";
}
fclose($fp);
unset($_POST['submitCSV']);
}
$this->render('index',array('buffer'=>$buffer));
}
Issues facing with this code :
Since
$lineis an instance ofImport, i should be able to use the elements of object$linebut I am not able to do that. I used$line->'name'for this, but i got this error : Parse error: syntax error, unexpected ''name'' (T_CONSTANT_ENCAPSED_STRING), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'$lineis amodelhere, so I should be able to place it as the first argument in theactiveTextFieldstatements. I get this error : get_class() expects parameter 1 to be object, boolean givenThirdly, this code generates same rows of text-field five times, so i thought of experimenting the
activeTextFieldby placing$iin place of0in the code and incrementing it in theforeachloop. That creates the same error as in 2.
Regards
First of all use
CFormModelinstead ofCModel. You may want to remove theattributeNames()function too.issue 1:
$label->'name'is incorrect. use$label->name.issue 2 & 3 should work if you make changes as above