Update.php 1.93 KB
<?php
    
    namespace backend\actions;
    
    use artbox\core\admin\actions\Save;
    use artbox\core\models\Language;
    use function call_user_func_array;
    use yii\base\Model;
    
    class Update extends Save
    {
        /**
         * @var string
         */
        public $viewPath = '@abackend/actions/views/update';
        
        /**
         * Updates existing model with langs, aliases and gallery
         *
         * @param $id
         *
         * @return string|\yii\web\Response
         */
        public function run($id)
        {
            $model = call_user_func_array(
                [
                    $this->controller,
                    'findModel',
                ],
                [ $id ]
            );
            $languages = Language::getActive();
            $post = \Yii::$app->request->post();
            
            if (!empty($this->languageFields)) {
                Model::loadMultiple($model->getVariationModels(), $post);
            }
            
            if ($model->load($post) && $model->save()) {
                if ($this->hasAlias) {
                    /**
                     * @var \artbox\core\models\Alias[] $aliases
                     */
                    $aliases = $model->loadAliases();
                    Model::loadMultiple($aliases, $post);
                    foreach ($aliases as $alias) {
                        $alias->save();
                    }
                }
                
                if ($this->hasGallery) {
                    $model->saveImages($post);
                }
                
                return $this->controller->redirect([ 'index' ]);
            }
            
            return $this->controller->render(
                $this->viewPath,
                [
                    'action'    => $this,
                    'model'     => $model,
                    'languages' => $languages,
                ]
            );
        }
    }