I have a Kartik fileInput in my form and here's how the code for making it looks like:
echo $form->field($model, 'images')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*','multiple' => true]
]);
I want to validate the input so that uploading images is required. For that I have the following line in my model:
[['images'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg,jpeg']
This is the code of my model:
<?php
namespace app\models;
use Yii;
use yii\web\UploadedFile;
/**
* LoginForm is the model behind the login form.
*
* @property User|null $user This property is read-only.
*
*/
class PhonesForm extends \yii\db\ActiveRecord
{
public $images;
public static function tableName()
{
return '{{phones}}';
}
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['name', 'price','model','description'], 'required'],
[['name','model'],'string', 'min' => 3],
[['description'],'string', 'min' => 25],
['price','integer'],
[['images'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg,jpeg']
];
}
public function upload()
{
if ($this->validate()) {
$this->images->saveAs('uploads/' . $this->images->baseName . '.' . $this->images->extension);
return true;
} else {
return false;
}
}
}
The problem is that is always gives me a validation error saying Please upload a file.
. How can I fix this problem? Thanks.
UPDATE
I have updated my controller method and my model.
Controller method:
public function actionAdd()
{
if (!Yii::$app->user->getIsGuest() && Yii::$app->user->identity->role == 'admin') {
$model = new PhonesForm();
if ($model->load(Yii::$app->request->post())) {
$model->images = UploadedFile::getInstances($model, 'images');
if ($model->upload()) {
echo "success";
}
else{
return $this->render('dashboardAdd',[
'model' => $model
]);
}
}
else{
return $this->render('dashboardAdd',[
'model' => $model
]);
}
}
else{
return $this->redirect(['site/index']);
}
}
Model:
<?php
namespace app\models;
use Yii;
/**
* LoginForm is the model behind the login form.
*
* @property User|null $user This property is read-only.
*
*/
class PhonesForm extends \yii\db\ActiveRecord
{
public $images;
public static function tableName()
{
return '{{phones}}';
}
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['name', 'price','model','description'], 'required'],
[['name','model'],'string', 'min' => 3],
[['description'],'string', 'min' => 25],
['price','integer'],
[['images'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg,jpeg']
];
}
public function upload()
{
if (!$this->validate()) {
return false;
}
foreach ($this->images as $image) {
$image->saveAs('uploads/' . $image->baseName . '.' . $image->extension);
}
return true;
}
}
I still have the same issue.