Issue
I used CUploadedFile
in order to upload multiple files in my web applcation. I used following code for this purpose:
public function actionCreate(){
$model=new Status();
$this->performAjaxValidation($model);
if(isset($_POST['Status']))
{
$model->attributes=$_POST['Status'];
Yii::log("actionCreate actionCreate inside if" .isset($_POST['Status']));
$images = CUploadedFile::getInstancesByName('description');
if(isset($images) && count($images)> 0)
{
foreach ($images as $image=>$pic)
{
if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/uploads/'.$pic->name,0777))
{
$model= new Status();
$model->description =$pic->name;
$url = Yii::getPathOfAlias('webroot').'/uploads';
$model->insert();
}
}
$this->redirect(array('view','id'=>$model->status_id));
}
}
$this->render('create',array(
'model'=>$model,
));
}
When I upload multiple files, it saves all of them but with different ids(PK).I need to save all uploaded files names to the one field called description
. How can I do it?
Solution
Try doing it this way
public function actionCreate(){
$model=new Status();
$this->performAjaxValidation($model);
if(isset($_POST['Status']))
{
$model->attributes=$_POST['Status'];
Yii::log("actionCreate actionCreate inside if" .isset($_POST['Status']));
$images = CUploadedFile::getInstancesByName('description');
if(isset($images) && count($images)> 0)
{
// Create a blank array.
$pic_name = array();
foreach ($images as $image=>$pic)
{
if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/uploads/'.$pic->name,0777))
{
//Put values in array.
$pic_name[$image] = $pic->name;
$url = Yii::getPathOfAlias('webroot').'/uploads';
}
}
// If array has multiple values i.e. more than zero then and only then save it in description as a string.
if(count($pic_name) > 0){
$_pics = implode('|',$pic_name);
// Do not create model everytime a new image is iterated
$model= new Status();
$model->description = $_pics;
$model->insert();
}
$this->redirect(array('view','id'=>$model->status_id));
}
}
$this->render('create',array(
'model'=>$model,
));
}
I don't know what is the use of $url in the loop, that's why I have kept it as it is.
Answered By - Onkar
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.