uploading file not validate when tabular input

I am try upload a lot files in tabular input, I can upload get and saveAs it, and also can control all others file like textField’s validate, but only the fileField’s validate not working… somebody help. ><

here is the code…

controller




	public function actionUpdateAll()

	{

	  for ($i=1;$i<7;$i++)

	      $PMaps[$i]=$this->loadModel($i);


		if(isset($_POST['PPreviewMap']))

		{

		    $valid = true;

		    foreach ($PMaps as $k=>$PMap)

		    {

		        $tmp_img_old = $PMap->img;

		        $PMap->attributes = $_POST['PPreviewMap']["$k"];

        		

		        if (@!empty($_FILES['PPreviewMap']['name']["$k"]['img'])){

			        $PMap->img = Map::model()->generateRandomName(0);

			        //validate, oldname, newname, waiting to save and saveAs

    			    if ($PMap->validate(array("img"))){ //this not working.....

    			        $tmp_img = CUploadedFile::getInstance($PMap, "[$k]img");

    			        echo '<pre>';

    			        print_r($tmp_img);

    			        echo '</pre>';

    			        $tmp_img->saveAs(Yii::app()->basePath.'/../map_img/'.$PMap->img);

    			    }

			      }else {

			        $PMap->img = $tmp_img_old==''? 'default.jpg' : $tmp_img_old;

			      }

		        $valid = $valid && $PMap->validate();

		    }

		    

		    if ($valid)

		        echo 'All Pass';


		}


    $this->render('updateAll',

                array('PMaps' =>$PMaps)

                );

	}



view




<?php echo $this->renderPartial('_formAll', array('PMaps'=>$PMaps)); ?>





<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'ppreview-map-form',

	'enableAjaxValidation'=>false,

	'htmlOptions' =>array('enctype'=>"multipart/form-data" )

)); ?>


	<?php 

	foreach ($PMaps as $PMap)

	    echo '<p>'.$form->errorSummary($PMap).'</p>'; 

	?>


<?php foreach ($PMaps as $k=>$PMap):?>

	<div class="row">

		<?php echo $form->labelEx($PMap,"[$k]pre_map_title"); ?>

		<?php echo $form->textField($PMap,"[$k]pre_map_title",array('size'=>32,'maxlength'=>32)); ?>

		<?php echo $form->error($PMap,$k."[$k]pre_map_title"); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($PMap,"[$k]img"); ?>

		<?php echo $form->fileField($PMap,"[$k]img",array('size'=>60,'maxlength'=>150)); ?>

		<?php echo $form->error($PMap,"[$k]img"); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($PMap,"[$k]url"); ?>

		<?php echo $form->textField($PMap,"[$k]url",array('size'=>60,'maxlength'=>1500)); ?>

		<?php echo $form->error($PMap,"[$k]url"); ?>

	</div>

<hr/>

<?php endforeach;?>



model




array('img', 'file', 'allowEmpty'=>true, 'types'=>'jpg','maxSize'=>1024*1024*1, 'tooLarge'=>'Max :1MB'),



I need it work or a way to make everything run. thank you.

anyone help???

In my tabular input validation, I set the model image attributes through the CUploadedFile::getInstances method BEFORE the save/validation method is called.

Controller:




if (isset($_POST['imageFormSubmitted']))

        {

            $model->imageList = CUploadedFile::getInstances($model, "image");


            if ($model->save())

            {

                $this->uploadImages($model);

                $this->redirect(array('portfolio/admin'));

            }

        }



Model:




// Public Property

public $imageList = array();


// Rules

array('imageList', 'file', 'types' => 'jpg, gif, png',

                'allowEmpty' => (count($this->images) == 0) ? false : true,

                'maxFiles' => 4, 'on' => 'imageAdmin',

                'message' => 'Please select image(s) to upload'),



Yours appears to validate the name of the file.




$PMap->img = Map::model()->generateRandomName(0);

if ($PMap->validate(array("img"))){...



in single but tabular model this code working fine.

I mean




$PMap->img = Map::model()->generateRandomName(0);

if ($PMap->validate(array("img"))){...



I hope this is why the validator is not working, I will test this way soon, thx.

finally I fixed it, but I was alway wonder why this code working in normal single model.

code like this.




	public function actionCreate()

	{

		$model=new Map;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Map']))

		{


		  $model->attributes=$_POST['Map'];//valued by mass


		  //check is the user decide to upload cover image, then do different operate

			if (@!empty($_FILES['Map']['name']['map_img'])){

			    $model->map_img = $model->generateRandomName(0);

			    //validate, oldname, newname, waiting to save and saveAs

			    if ($model->validate(array('map_img'))){ //this line is working fine here.

//			        preg_match('|.\w+$|', $_FILES['Map']['name']['map_img'],$out); //get file suffix name, and put it into array $out[0], format like .jpg

			        $model->uploaded_cover_img = CUploadedFile::getInstance($model, 'map_img');

			        $model->uploaded_cover_img->saveAs(Yii::app()->basePath.'/../map_img/'.$model->map_img);

			    }

			}else {

			    $model->map_img = 'default.jpg';

			}



helloww…

can u share the code, i have the same problem, i need to upload many files in one page but by using tabular input like in here but i cant save the files to the database. i already succeed upload one file to database but now i want many…

thanks :D

Hi All,

I have similar problem, I need to upload multiple files using tabular input. I end up with next code (I am using boostrap extension):

View:




<div class="attachs">

	<php /* Add one input filed */ ?>

	<?php echo $form->fileFieldRow($model, '[0]attach'); ?>

</div>


<div class="form-actions">

		

<?php $this->widget('bootstrap.widgets.TbButton', array(

	'buttonType'	=> 'link',

	'type'			=> 'primary',

	'size'			=> 'large',

	'url'			=> 'javascript:void(0)',

	'label'			=> 'Add Attahment',

	'htmlOptions'	=> array('class' => 'addAttach')

)); ?>

</div>


<script type="text/javascript">

$(document).ready(function() {

	/**

	 *		add one more attachemnt field

	 */

	var attachCount = 1;

	$(".addAttach").click(function() {

		

		var template = '<div class="control-group"><label class="control-label" for="Domain_' + attachCount + '_attach">Attach</label><div class="controls"><input id="ytDomain_' + attachCount + '_attach" type="hidden" value="" name="Domain[' + attachCount + '][attach]"><input class="attach_copy" name="Domain[' + attachCount + '][attach]" id="Domain_' + attachCount + '_attach" type="file"></div></div>';

		

		$(".attachs").append(template);

		

		attachCount++;

	});

});

</script>



^ This allows you to add unlimited number of upload buttons

Model:




class Domain extends CActiveRecord {

	

	public $attach;

	

	...




	public function rules() {

		return array(

		...


		array('attach', 'file', 'types' => 'jpg, gif, png, doc, docx, xls, xlsx, pdf', 'allowEmpty'=>true),

		);

	}

}



Controller:




public function actionUpdate($id) {

	$model=$this->loadModel($id);


	// Uncomment the following line if AJAX validation is needed

	// $this->performAjaxValidation($model);


	if(isset($_POST['Domain'])) {

		$model->attributes=$_POST['Domain'];

			

		// validate files

		$valid = true;

		foreach ($_FILES['Domain']['name'] as $i => $item) {

			if(!empty($_FILES['Domain']['name'][$i]['attach'])) {

				$model->attach = CUploadedFile::getInstance($model,'[' . $i . ']attach');

				$valid = $model->validate() && $valid;

			}

		}

			

		if($valid && $model->save()) {

				

			// upload files

			foreach ($_FILES['Domain']['name'] as $i => $item) {

				if(!empty($_FILES['Domain']['name'][$i]['attach'])) {

					$uploadedFile = CUploadedFile::getInstance($model, '[' . $i . ']attach');

					$filename = time() . $uploadedFile->getName();

					$uploadedFile->saveAs(Yii::app()->basePath.'/../images/attach/' . $filename);


					// save in database path to file

					$attach = new Attach();

					$attach->domain = $model->id;

					$attach->path = $filename;

					$attach->name = $uploadedFile->getName();;

					$attach->save();

				}

			}

				

				

			Yii::app()->user->setFlash('success', '<strong>Domain updated successfully</strong>');

			$this->redirect(array('admin'));

		}

	}


	$this->render('update',array(

		'model'=>$model,

	));

}



This is working, but I am not sure is this good approach. So, if anyone have some recommendations for this problem please let me know.

Thanks,