2
我使用Yii2來創建簡單的上傳圖像並驗證圖像擴展。我已閱讀Yii2文檔,我不知道$model->validate()
總是返回false
。對我有什麼想法?在Yii2上傳圖像和驗證
在我的模型文件,我設置的規則imageFile
:
public function rules()
{
return [
[['name', 'price', 'description', 'image_path'], 'required'],
[['price'], 'integer'],
[['description'], 'string'],
[['name', 'image_path'], 'string', 'max' => 255],
[['imageFile'], 'image', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, jpeg'],
];
}
而且在控制器的我的行爲指標:
if ($model->load(Yii::$app->request->post())) {
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
if ($model->validate() && $model->save()) {
$model->imageFile->saveAs('uploads/' . Yii::$app->params['bonuslyRewards'] . '/' . $model->imageFile->baseName . '.' . $model->imageFile->extension);
$model->image_path = 'uploads/' . Yii::$app->params['bonuslyRewards'] . '/' . $model->imageFile->baseName . '.' . $model->imageFile->extension;
return $this->redirect(['view', 'id' => $model->id]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
因爲'image_path'是必需的。 –
add'if($ model-> save()){return $ this-> redirect(['view','id'=> $ model-> id]);在'$ model-> image_path'之後。 –
那是正確的,'image_path'是必需的。 – Francis