public function actionUpdate($id)
{
$product = $this->findModel($id);
if (!$updateProduct = Yii::createObject(ProductUpdate::class, [$product, Yii::$app->request->post()])->execute()) {
return $this->redirect(['/product/view', 'id' => $model->getId()]);
}
return $this->render('update', [
'product' => $product,
'model' => $updateProduct,
]);
}
//
class ProductUpdate
{
protected $product;
protected $post;
public function __construct(\app\models\Product $product, array $post)
{
$this->product = $product;
$this->post = $post;
}
protected function createUpdateForm()
{
$productForm = new ProductForm($this->product);
$productForm->attributes = $this->product->attributes;
if (empty($this->post)) {
return $productForm;
}
$productForm->load($this->post);
Yii::$app->session->setFlash('success', 'Вы успешно изменили товар!');
$productForm->save();
return $productForm;
}
protected function checkStatus()
{
if ($this->product->status == $this->product::STATUS_SOLD_OUT || $this->product->status == $this->product::STATUS_PARTIAL_SALE) {
Yii::$app->session->setFlash('error', 'Вы не можете изменить этот товар, т.к. он уже продан, либо частично продан!');
return false;
}
return true;
}
public function execute()
{
if ($this->checkStatus()) {
return $this->createUpdateForm ();
}
return false;
}
}