yii2-upload-behavior
yii2-upload-behavior copied to clipboard
How to use with separate FormModel?
I don`t clearly understand, what we shold do, if there are separate FormModel, with the help of which the main ActiveRecord model is manipulated. Can i see some example? Thanks
Any news? This extention is very helpfull(
I don
t clearly understand, what we shold do, if there are separate FormModel, with the help of which the main ActiveRecord model is manipulated. Can i see some example? Thanks My example
namespace common\modules\catalog\models;
use yii\base\Model; use yii\web\UploadedFile;
class PhotosForm extends Model { /** * @var UploadedFile[] */ public $files;
public function rules(): array
{
return [
[['files'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, jpeg, JPG, JPEG', 'maxFiles' => 10],
];
}
public function beforeValidate(): bool
{
if (parent::beforeValidate()) {
$this->files = UploadedFile::getInstances($this, 'files');
return true;
}
return false;
}
public function upload($product_id)
{
if ($this->validate()) {
foreach ($this->files as $file) {
$modelPic = new Pic(['file'=>$file]);
$modelPic->product_id = $product_id;
try {
$modelPic->save();
} catch (\DomainException $e) {
\Yii::$app->errorHandler->logException($e);
\Yii::$app->session->setFlash('error', $e->getMessage());
}
}
return true;
} else {
return false;
}
}
}`
I don
t clearly understand, what we shold do, if there are separate FormModel, with the help of which the main ActiveRecord model is manipulated. Can i see some example? Thanks My example
namespace common\modules\catalog\models;
use yii\base\Model; use yii\web\UploadedFile;
class PhotosForm extends Model { /**
- @var UploadedFile[] */ public $files;
public function rules(): array { return [ [['files'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, jpeg, JPG, JPEG', 'maxFiles' => 10], ]; } public function beforeValidate(): bool { if (parent::beforeValidate()) { $this->files = UploadedFile::getInstances($this, 'files'); return true; } return false; } public function upload($product_id) { if ($this->validate()) { foreach ($this->files as $file) { $modelPic = new Pic(['file'=>$file]); $modelPic->product_id = $product_id; try { $modelPic->save(); } catch (\DomainException $e) { \Yii::$app->errorHandler->logException($e); \Yii::$app->session->setFlash('error', $e->getMessage()); } } return true; } else { return false; } }
}`
And using this behavior?
Figured this out. Just attach behavior to the ActiveRecord model ("User", for example), then in UserForm model BEFORE saving User model with new data perform this:
$this->user->image = UploadedFile::getInstance($this, 'image');
Then save User as usual.