0

I have used use kartik\file\FileInput; (extension) for saving multiple images from single form submit. The images are save locally but are not saving in the database.

Here is my Model Code media.php

namespace app\models;
use yii\web\UploadedFile;
class Media extends \yii\db\ActiveRecord
{
        public function rules(){
        return [
            [['title'], 'file', 'skipOnEmpty' => false, 'extensions' => ['gif', 'jpg', 'png', 'jpeg', 'JPG', 'JPEG', 'PNG', 'GIF'], 'checkExtensionByMimeType' =>  false ,'maxFiles' => 4, 'maxSize' => 1024 * 1024 * 1024],
                        [['extension'], 'string', 'max' => 6],
                ];        
        }

Controller code:

if ($mediamodel->load ( Yii::$app->request->post () )) {
    $title = UploadedFile::getInstances ( $mediamodel, 'title' );
    foreach ($title as $key => $file)          {
        $file->saveAs(Yii::$app->basePath . '/web/images/hotel/'. $file->baseName . '.' . $file->extension);}
        foreach ($title as $key => $file){   
        echo $mediamodel->title."*********";
        $mediamodel->title = $file->baseName . '.' . $file->extension;
        echo " \Title: ".$mediamodel->title;
        $mediamodel->save ();
    }
}

My view code:

use kartik\file\FileInput; 
$form = ActiveForm::begin([ 'layout' => 'horizontal', {label}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{endWrapper}", 
    'fieldConfig' => ['horizontalCssClasses' => ['label' => 'col-md-3','offset' => 'col-md-offset-2','wrapper' => 'col-md-4', 'error' => '','hint' => '',],],'
    options' => [ 'class' => 'form-horizontal', 'enctype' => 'multipart/form-data', ], ]);?>

<?php echo $form->field($mediamodel, 'title[]')->widget(FileInput::classname(), ['options'=>['multiple' => true]]); 
Html::submitButton($model->isNewRecord ? 'Add' : 'Update');
Nana Partykar
  • 10,556
  • 10
  • 48
  • 77
Sohaib1415
  • 53
  • 5
  • Check the log in the debug bar after "Model not inserted due to validation error." or any other hints on what might be wrong. And please update the question with the view code, instead of in a comment. – Jørgen May 30 '16 at 12:30
  • Check for the Errors first i.e `$mediamodel->getErrors()` – Chetan Sharma May 30 '16 at 12:54

2 Answers2

1

// You should handle errors like this.

if(!$mediamodel->save()){
    // handle the errors of model.
    var_dump($mediamodel->getErrors());
}
HeadwindFly
  • 774
  • 3
  • 8
  • 19
  • why is error is given I don't understand array(1) { ["title"]=> array(1) { [0]=> string(21) "Please upload a file." } } – Sohaib1415 May 30 '16 at 16:13
1

use

$mediamodel->save (false);

instead of

$mediamodel->save ();
SAR
  • 57
  • 8