Answer the question
In order to leave comments, you need to log in
[[+content_image]]
File validation doesn't work, why?
Hey!
I upload the file to the server using Yii2.
Model:
public $attachment;
public function rules()
{
return [
[['sender_id', 'incoming_number', 'incoming_date', 'delivery_type_id', 'attachment'], 'required'],
[['sender_id', 'delivery_type_id', 'status_id'], 'integer'],
[['outgoing_date', 'incoming_date', 'status_id', 'created'], 'safe'],
[['attachment'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, xls, docx, pdf'],
[['comments'], 'string'],
[['outgoing_number', 'incoming_number', 'summary', 'attachment'], 'string', 'max' => 255],
[['status_id'], 'exist', 'skipOnError' => true, 'targetClass' => DocumentStatus::className(), 'targetAttribute' => ['status_id' => 'id']],
[['delivery_type_id'], 'exist', 'skipOnError' => true, 'targetClass' => DeliveryTypes::className(), 'targetAttribute' => ['delivery_type_id' => 'id']],
[['sender_id'], 'exist', 'skipOnError' => true, 'targetClass' => Senders::className(), 'targetAttribute' => ['sender_id' => 'id']],
];
}
$model = new Documents();
if($model->load(Yii::$app->request->post()) && $model->validate()) {
$newDoc = new Documents();
$newDoc->sender_id = $model->sender_id;
$model->attachment = UploadedFile::getInstance($model, 'attachment');
$model->attachment->saveAs('uploads/documents/'.$model->attachment->name."-".date('YmdHis').$model->attachment->extension);
$newDoc->attachment = "filezzz";
}
Answer the question
In order to leave comments, you need to log in
After all, the docks have everything: https://github.com/yiisoft/yii2/blob/master/docs/g...
you have a problem that you run validation before specifying the uploaded file, in the examples of the docks there is a normal implementation and controller actions and models. Remove all logic in the model. if the model is AR then inherit from it and implement this logic or raise a separate form model
because your attachment in rules is described first as a file, and then as a string and cannot be saved, because in attachment after
is an object, not a string. the solution is here, this is loading through an additional model
$imageModel = new UploadImageForm();
$imageModel->files = UploadedFile::getInstances($imageModel, 'files');
if ($imageModel->validate()) {
$imageModel->files //тут ваш скрипт чтобы сохранить файл
}
//ну и сама основная модель
if ($model->load(Yii::$app->request->post())) {
$model->save();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question