Answer the question
In order to leave comments, you need to log in
How to arrange file upload in a form?
There is a form that should be able to attach 5 photos. How to correctly organize the form and model, which would be extensible (10 photos will eventually be allowed) and with validation?
You can make the attributes file1, file2, ..., file5 in the model and render the fields separately in the form. I understand how to do validation, but it's not very extensible
. You can make an array $files => [file1, file2, ..., file5]. but then I have no idea how to validate.
Who implemented such forms, tell me
Answer the question
In order to leave comments, you need to log in
Hello! You did not fully disclose your question, but I will try to answer based on our projects on yii2.
If a mechanism is used in which files can be attached at the stage of creating a certain model (say Portfolio), and they are loaded by the server via an ajax request (for example https://github.com/hayageek/jquery-upload-file), then a situation arises that there is nothing to bind to (the object of the Portfolio class has not yet been saved), and the files are already on the server. In this case, we use the hash field, the value of which is unique, and files are linked using it. Those. when creating a new Portfolio object, we immediately generate a unique hash, pass it to the creation form, and load files with Ajax. If desired, you can hang up a cron task to remove files from the file system that are linked to a non-existent Portfolio.hash.
Next, the model itself. We take the official documentation:
https://github.com/yiisoft/yii2/blob/master/docs/g...
We expand it
as we please, for example like this:
class File extends \yii\db\ActiveRecord
{
public $file;
public function rules()
{
return [
[['file'], 'file'],
[['filename', 'parent_id'], 'required'],
[['parent_id'], 'integer'],
[['filename', 'path'], 'string', 'max' => 255],
[['description'], 'string']
];
}
$model = new File();
$model->file = UploadedFile::getInstance($model, 'file');
if ($model->file && $model->validate()) {
$model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
}
File[0][file], File[0][description], File[0][id];
File[1][file], File[1][description], File[1][id];
File[2][file], File[2][description], File[2][id];
foreach (Yii::$app->request->post('File') as $sn => $file){
$model = new File;
$model->fakeFormName = "File[{$sn}]";
$model->file = UploadedFile::getInstance($model, 'file');
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question