Reputation: 10061
I want to upload multiple images and save the image name to database table. There are two attributes in the table - id
and image_name
. In form, I use CMultifileupload
widget to upload number of images. When I submit the form, there is no effect. Then I try to echo something underneath of if (isset($_POST['ImageTemp'])) {
but no effect. So I am on hold to see the output whether multiple image upload or not. However, I wrote as:
in form:
<div class="form form-custom">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'image-temp-form',
'enableAjaxValidation'=>false,
'htmlOptions'=>array('enctype'=>'multipart/form-data' ),
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'image_name'); ?>
<?php
$this->widget('CMultiFileUpload', array(
'model'=>$model,
'attribute'=>'image_name',
//'name' => 'files',
'accept'=>'jpg|gif|png',
'denied'=>'File is not allowed',
'max'=>3, // max 10 files
));
?>
<?php echo $form->error($model,'image_name'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
in controller:
public function actionCreate()
{
$model=new ImageTemp;
$type = isset($_GET['type']) ? $_GET['type'] : 'post';
if (isset($_POST['ImageTemp'])) {
echo "something but no output";
$model->attributes = $_POST['ImageTemp'];
$photos = CUploadedFile::getInstancesByName('image_name');
// proceed if the images have been set
if (isset($photos) && count($photos) > 0) {
// go through each uploaded image
foreach ($photos as $image => $pic) {
echo $pic->name.'<br />';
if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/images/project'.$pic->name)) {
// add it to the main model now
$model->image_name = $pic->name; //it might be $img_add->name for you, filename is just what I chose to call it in my model
$model->save(); // DONE
}
else{
echo 'Cannot upload!';
}
}
}
}
$this->render('create',array(
'model'=>$model,
));
}
and in model, I have written the rule:
public function rules()
{
return array(
array('image_name', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, image_name', 'safe', 'on'=>'search'),
);
}
I am trying based on this but do not understand where I did wrong.
Upvotes: 1
Views: 568
Reputation: 3731
$_FILES['ImageTemp']
is your friend ;)
So in your controller you should do
if (isset($_FILES['ImageTemp'])) {
// do something..
}
Upvotes: 1