i have an ActiveForm, and i want to add a field where the user can upload their photos. the problem is that i don't have an attribute for the image in the users table and every input field in 'yii' expects a model and an attribute as follows.
<?= $form->field($model, 'attribute')->input($platforms) ?>
i don't want to assign the image to any record nor i want to insert in in the database, i want it to be uploaded to a specific folder.
i have also checked the library kartik wrote, but also requires an attribute field.
give this code after your uploaded code
in your view
in your controller
Create a read only attribute for your model like
public $image
and proceed likeFollow the official documentation
https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md
Form Model
Form View
Controller
Now create the controller that connects form and model together:
Instead of
model->load(...)
we are usingUploadedFile::getInstance(...)
.[[\yii\web\UploadedFile|UploadedFile]]
does not run the model validation. It only provides information about the uploaded file. Therefore, you need to run validation manually via$model->validate()
. This triggers the[[yii\validators\FileValidator|FileValidator]]
that expects a file:If validation is successful, then we're saving the file:
If you're using "basic" application template then folder uploads should be created under web.
That's it. Load the page and try uploading. Uplaods should end up in basic/web/uploads.
I really like Yii2 Dropzone.
Installation:
Usage:
Controller:
If you have more than one file while uploading you must use foreach for that. And you should actual name of file in a column in table and a encrypted value of that name has to be stored to avoid duplicated in the directory.. Something like this..
Here a random string is generated and it will be assign with the name of the document, and it will be stored in the table. The UserDocs is the model name.