diff --git a/backend/components/base/BaseActiveRecord.php b/backend/components/base/BaseActiveRecord.php index 9d4c19d..c13d9c5 100755 --- a/backend/components/base/BaseActiveRecord.php +++ b/backend/components/base/BaseActiveRecord.php @@ -9,12 +9,16 @@ namespace backend\components\base; -use yii\base\ErrorException; +use common\components\exceptions\OrdinaryActiveRecordException; class BaseActiveRecord extends \yii\db\ActiveRecord { + /** + * @param int $row + * @throws OrdinaryActiveRecordException + * выбрасывает специальное исключения, наполняя сообщение с массива ошибок модели (после попытки валидации) + */ public function throwStringErrorException($row = 0){ - $errors_str = ''; if ($row != 0) { $errors_str = "Ошибка в строке {$row} "; @@ -22,7 +26,9 @@ class BaseActiveRecord extends \yii\db\ActiveRecord { foreach ($this->getErrors() as $error) { $errors_str .= implode( array_values($error) ); } - throw new ErrorException( $errors_str ); + $ex = new OrdinaryActiveRecordException( $errors_str ); + $ex->active_record_name = static::formName(); + throw $ex; } } \ No newline at end of file diff --git a/backend/controllers/BrandsController.php b/backend/controllers/BrandsController.php index 520403a..4af9da2 100755 --- a/backend/controllers/BrandsController.php +++ b/backend/controllers/BrandsController.php @@ -9,6 +9,7 @@ use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use yii\filters\AccessControl; +use yii\web\UploadedFile; /** * BrandsController implements the CRUD actions for Brands model. @@ -82,14 +83,8 @@ class BrandsController extends Controller { $model = new Brands(); - if ($model->load(Yii::$app->request->post()) && $model->save()) { - //return $this->redirect(['view', 'id' => $model->BRAND]); - return $this->redirect(['index']); - } else { - return $this->render('create', [ - 'model' => $model, - ]); - } + return $this->saveIMG( $model, 'create' ); + } /** @@ -102,14 +97,8 @@ class BrandsController extends Controller { $model = $this->findModel($id); - if ($model->load(Yii::$app->request->post()) && $model->save()) { - //return $this->redirect(['view', 'id' => $model->BRAND]); - return $this->redirect(['index']); - } else { - return $this->render('update', [ - 'model' => $model, - ]); - } + return $this->saveIMG( $model, 'update' ); + } /** @@ -140,4 +129,31 @@ class BrandsController extends Controller throw new NotFoundHttpException('The requested page does not exist.'); } } + + /** + * @param $model + * @return string|\yii\web\Response + * сохраняет картинку и валидирует модель + * выбрасывает исключение в случае ошибки + */ + protected function saveIMG( $model, $action ){ + if( $model->load(Yii::$app->request->post()) ) { + $model->file = UploadedFile::getInstance($model, 'file'); + $model->IMG = $model->file->name; + // первый проход - валидируем, сохраняем файл, + if ( $model->validate() ) { + // сохраним файл + $model->file->saveAs( Yii::getAlias('@storage') . '/files/brands/' . $model->IMG ); + if ( $model->save() ) { + return $this->redirect(['index']); + } + } + $model->throwStringErrorException(); + } else { + return $this->render($action, [ + 'model' => $model, + ]); + } + + } } diff --git a/backend/controllers/ParserController.php b/backend/controllers/ParserController.php index 083b6d4..242b64f 100755 --- a/backend/controllers/ParserController.php +++ b/backend/controllers/ParserController.php @@ -3,6 +3,7 @@ namespace backend\controllers; use backend\models\Details; use common\components\exceptions\CrossParsingException; +use common\components\exceptions\OrdinaryActiveRecordException; use common\components\exceptions\PriceParsingException; use common\components\exceptions\RgParsingException; use common\components\ModelArrayValidator; @@ -76,6 +77,10 @@ class ParserController extends BaseController $action_name = ['results']; }elseif ( $exception instanceof RgParsingException ) { $action_name = ['rg-grup/results']; + }elseif ( $exception instanceof OrdinaryActiveRecordException ) { + // для обычной модели возвращаемся в index в качестве контроллера используем имя модели + $action_name = strtolower($exception->active_record_name); + $action_name = ["$action_name/index"]; } if ( $exception !== null ) { diff --git a/backend/views/brands/_form.php b/backend/views/brands/_form.php index c0449e3..3807320 100755 --- a/backend/views/brands/_form.php +++ b/backend/views/brands/_form.php @@ -17,14 +17,22 @@ use yii\widgets\ActiveForm; echo $form->field($model, 'BRAND')->textInput(['maxlength' => true])->label('Название') ?> - field($model, 'CONTENT')->textarea(['rows' => 6]) ?> + field($model, 'CONTENT')->widget(\mihaildev\ckeditor\CKEditor::className(),[ + 'editorOptions' => \mihaildev\elfinder\ElFinder::ckeditorOptions('elfinder',[ + 'preset' => 'full', //разработанны стандартные настройки basic, standard, full данную возможность не обязательно использовать + 'inline' => false, //по умолчанию false]), + // 'filebrowserUploadUrl'=>Yii::$app->getUrlManager()->createUrl('news/images-upload') + ] + ) + ]); ?> field($model, 'if_oem')->checkbox() ?> - field($model, 'IMG')->fileInput() ?> + field($model, 'file')->fileInput()->label(false)->hint('имя файла должно иметь только латинские символы и цифры',['tag'=>'span'])?>
isNewRecord ? 'Добавить' : 'Редактировать', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
+ 'btn btn-primary']) ?> diff --git a/common/components/exceptions/OrdinaryActiveRecordException.php b/common/components/exceptions/OrdinaryActiveRecordException.php new file mode 100644 index 0000000..0dc3eb6 --- /dev/null +++ b/common/components/exceptions/OrdinaryActiveRecordException.php @@ -0,0 +1,18 @@ + 100], [['tecdoc_logo'], 'string', 'max' => 50], - [['IMG'], 'string', 'max' => 255] + ['IMG', 'string', 'max' => 255], + ['IMG', 'match', 'pattern' => '/[a-zA-Z0-9]+\.[a-zA-Z]+/', 'message' => 'имя файла изображения должно иметь только латинские символы и цифры'], + [['file'], 'image' ] ]; } diff --git a/composer.lock b/composer.lock index a4cc919..f15164f 100644 --- a/composer.lock +++ b/composer.lock @@ -1891,28 +1891,28 @@ }, { "name": "sebastian/diff", - "version": "1.3.0", + "version": "1.4.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/diff.git", - "reference": "863df9687835c62aa423a22412d26fa2ebde3fd3" + "reference": "13edfd8706462032c2f52b4b862974dd46b71c9e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/863df9687835c62aa423a22412d26fa2ebde3fd3", - "reference": "863df9687835c62aa423a22412d26fa2ebde3fd3", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/13edfd8706462032c2f52b4b862974dd46b71c9e", + "reference": "13edfd8706462032c2f52b4b862974dd46b71c9e", "shasum": "" }, "require": { "php": ">=5.3.3" }, "require-dev": { - "phpunit/phpunit": "~4.2" + "phpunit/phpunit": "~4.8" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.3-dev" + "dev-master": "1.4-dev" } }, "autoload": { @@ -1935,11 +1935,11 @@ } ], "description": "Diff implementation", - "homepage": "http://www.github.com/sebastianbergmann/diff", + "homepage": "https://github.com/sebastianbergmann/diff", "keywords": [ "diff" ], - "time": "2015-02-22 15:13:53" + "time": "2015-12-08 07:14:41" }, { "name": "sebastian/environment", @@ -2110,16 +2110,16 @@ }, { "name": "sebastian/recursion-context", - "version": "1.0.1", + "version": "1.0.2", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/recursion-context.git", - "reference": "994d4a811bafe801fb06dccbee797863ba2792ba" + "reference": "913401df809e99e4f47b27cdd781f4a258d58791" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/994d4a811bafe801fb06dccbee797863ba2792ba", - "reference": "994d4a811bafe801fb06dccbee797863ba2792ba", + "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/913401df809e99e4f47b27cdd781f4a258d58791", + "reference": "913401df809e99e4f47b27cdd781f4a258d58791", "shasum": "" }, "require": { @@ -2159,7 +2159,7 @@ ], "description": "Provides functionality to recursively process PHP variables", "homepage": "http://www.github.com/sebastianbergmann/recursion-context", - "time": "2015-06-21 08:04:50" + "time": "2015-11-11 19:50:13" }, { "name": "sebastian/version", -- libgit2 0.21.4