M
M
monday_suicide2020-07-15 21:20:04
Yii
monday_suicide, 2020-07-15 21:20:04

Is this implementation correct?

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;
    }
    
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2020-07-17
@dcc

Taking it out of the controller is the right thing to do. But it's not right that you dragged all the logic there. Flash messages. Form processing. You can see an example of how this is done.
Example 1
Example 2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question