Save form to database

Hello,

I just started my first project with yii and I got an problem I can’t solve. Maybe someone of you can help me?

I want to submit a form and save one field "category" in the database and upload the "image" on the server. The Upoad works fine. Even the save works. Every save() creates a new entry in the database. BUT the field "category" is not saved in the database. Where is my mistake?

I have a database:


CREATE TABLE IF NOT EXISTS `photo` (

`id` int(11) NOT NULL,

  `category` text CHARACTER SET utf8 NOT NULL,

  `filename` varchar(255) NOT NULL

) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;

I have a model "Photo":


namespace app\models;


use yii\web\UploadedFile;

use yii\db\ActiveRecord;


class Photo extends ActiveRecord {

	public $image;

	public $category;


    public function rules()

    {

        return [

            [['category'], 'required'],

            [['category'], 'safe'],

            ['image', 'file', 'skipOnEmpty' => false, 'extensions' => 'jpg, png', 'mimeTypes' => 'image/jpeg, image/png']

        ];

    }

}

I have a controller "PhotoController":


namespace app\controllers;


use Yii;

use yii\web\Controller;

use app\models\Photo;

use yii\web\UploadedFile;


class PhotoController extends Controller {

	public function actionOverview() {

		return $this->render('overview', ['photos' => []]);

	}


	public function actionCreate() {

		$photo = new Photo(); 


		if ($photo->load(Yii::$app->request->post(), 'Photo')

			&& ($photo->image = UploadedFile::getInstance($photo, 'image'))

			&& $photo->validate()) {


        	$photo->save();


            // $photo->image->saveAs('uploads/' . $photo->id . '.' . $photo->image->extension);


			return $this->render('uploaded', ['model' => $photo]);

		} else {

			return $this->render('create', ['model' => $photo]);

		}

	}

}

I have a create form for uploading:


use yii\helpers\Html;

use yii\widgets\ActiveForm;


$form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);


?>

<?= $form->field($model, 'image')->fileInput() ?>

<?= $form->field($model, 'category') ?>


<div class="form-group">

    <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>

</div>


<?php ActiveForm::end(); ?>



Thanks for your help! Greets Oliver

Try this :




public function actionCreate() 

{

  $photo = new Photo(); 


  //Check if is posted and set all the attributes

  if ($photo->load(Yii::$app->request->post())

  {

    //Set the image attribute

    $photo->image = UploadedFile::getInstance($photo, 'image')

    //Validate and save next

    if($photo->save()) {

      return $this->render('uploaded', ['model' => $photo]);

    }

  }

  return $this->render('create', ['model' => $photo]);

}



If it doesn’t work, check after load() if the attributes are setted :


var_dump($image->getAttributes());die;


I use this behavior to save images : https://github.com/yii-dream-team/yii2-upload-behavior

I recommand it ;)

Hi Timmy,

your Code doesn’t work. When I var_dump the $photo after load, I got the following:




array(3) { ["id"]=> NULL ["category"]=> string(3) "XXX" ["filename"]=> NULL }

Everything seems fine. But the category issn’t saved…

Yes I didn’t see “filename” :




...

$photo->image = UploadedFile::getInstance($photo, 'image');

$photo->filename = $photo->image->baseName;

...



Try to remove the declaration of “category” in your model and test. It’s not necessary to declare it.

If category is not saved but present in the model attributes, the problem may be the database (the type of the column). Try to insert it directly in phpmyadmin

That’s it. Thank you.

Learning: If I declare a field in the database, I may not declare it in the model.

You should use Gii to generate the model and the CRUD : http://www.yiiframework.com/doc-2.0/guide-start-gii.html

It’s a nice way to learn.

I didn’t asked my self about it.

In fact it is not clear in the doc : http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#accessing-column-data