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