#1032 - Доработка модуля bids drag and drop

parent d7069127
...@@ -10,6 +10,7 @@ use yii\web\Response; ...@@ -10,6 +10,7 @@ use yii\web\Response;
use yii\web\UploadedFile; use yii\web\UploadedFile;
use common\modules\bids\models\Bid; use common\modules\bids\models\Bid;
use common\modules\bids\models\BidFile;
/** /**
* BidAdminController implements the CRUD actions for Bid model. * BidAdminController implements the CRUD actions for Bid model.
...@@ -30,28 +31,35 @@ class BidController extends \common\components\BaseController ...@@ -30,28 +31,35 @@ class BidController extends \common\components\BaseController
*/ */
public function actionAdd() public function actionAdd()
{ {
Yii::$app->response->format = Response::FORMAT_JSON;
$model = new Bid; $model = new Bid;
$model->scenario = Yii::$app->request->post('scenario'); $model->scenario = Yii::$app->request->post('scenario');
if(Yii::$app->request->isAjax) if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))
{ {
$model->load(Yii::$app->request->post()); $transaction = Yii::$app->db->beginTransaction();
$model->file = UploadedFile::getInstance($model, 'file');
Yii::$app->response->format = Response::FORMAT_JSON; try
$model->filename = $_POST['file_name'];
if($model->validate())
{ {
/*if($model->file) if($model->save())
{ {
$model->upload();
$model->file = null;
}*/
// Yii::$app->user->identity->afterSubscribe(12); // Yii::$app->user->identity->afterSubscribe(12);
if($model->file)
{
foreach ($model->file as $filename)
{
$file = new BidFile;
$file->bid_id = $model->id;
$file->filename = $filename;
$file->save();
}
}
$model->save();
$model->send(); $model->send();
$transaction->commit();
return ['success' => true]; return ['success' => true];
} }
else else
...@@ -59,6 +67,12 @@ class BidController extends \common\components\BaseController ...@@ -59,6 +67,12 @@ class BidController extends \common\components\BaseController
return ActiveForm::validate($model); return ActiveForm::validate($model);
} }
} }
catch (Exception $e)
{
$transaction->rollBack();
throw $e;
}
}
else else
{ {
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested page does not exist.');
...@@ -68,16 +82,24 @@ class BidController extends \common\components\BaseController ...@@ -68,16 +82,24 @@ class BidController extends \common\components\BaseController
public function actionUploadFiles() public function actionUploadFiles()
{ {
$model = new Bid(); Yii::$app->response->format = Response::FORMAT_JSON;
if (!empty($_FILES)) {
$model = new BidFile;
$model->file = UploadedFile::getInstanceByName('file');
$tempFile = $_FILES['file']['tmp_name']; if($model->file)
{
if(!file_exists(BidFile::path()))
{
mkdir(BidFile::path(), 0777, true);
}
$targetPath = $model->getPath(); $model->filename = date('dmYHis-') . uniqid() . '.' . $model->file->extension;
$targetFile = $targetPath. $_FILES['file']['name']; $model->file->saveAs(BidFile::path() . $model->filename);
move_uploaded_file($tempFile,$targetFile); return [
return $_FILES['file']['name']; 'filename' => $model->filename
];
} }
} }
} }
...@@ -30,10 +30,6 @@ class Bid extends \common\components\ActiveRecordModel ...@@ -30,10 +30,6 @@ class Bid extends \common\components\ActiveRecordModel
const TAG_INVOLVEMENT = 'Вовлечение'; const TAG_INVOLVEMENT = 'Вовлечение';
const TAG_TREATMENT = 'Обращение'; const TAG_TREATMENT = 'Обращение';
const FILE_FOLDER = '/uploads/bids/';
public $file;
public static $form_titles = [ public static $form_titles = [
self::FORM_PROJECT => 'Расчитать проект', self::FORM_PROJECT => 'Расчитать проект',
self::FORM_CALLBACK => 'Обратный звонок', self::FORM_CALLBACK => 'Обратный звонок',
...@@ -46,6 +42,8 @@ class Bid extends \common\components\ActiveRecordModel ...@@ -46,6 +42,8 @@ class Bid extends \common\components\ActiveRecordModel
self::FORM_SUBSCRIBE => 'Ошибки', self::FORM_SUBSCRIBE => 'Ошибки',
]; ];
public $file;
/** /**
* @inheritdoc * @inheritdoc
*/ */
...@@ -81,12 +79,13 @@ class Bid extends \common\components\ActiveRecordModel ...@@ -81,12 +79,13 @@ class Bid extends \common\components\ActiveRecordModel
[['email'], 'required', 'on' => self::SCENARIO_SUBSCRIBE], [['email'], 'required', 'on' => self::SCENARIO_SUBSCRIBE],
[['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg, gif, xls, xlsx, doc, docx, pdf'],
[['text'], 'string'], [['text'], 'string'],
[['name'], 'string', 'max' => 100], [['name'], 'string', 'max' => 100],
[['phone'], 'string', 'max' => 30], [['phone'], 'string', 'max' => 30],
[['email'], 'string', 'max' => 70], [['email'], 'string', 'max' => 70],
[['filename', 'form'], 'string', 'max' => 50], [['form'], 'string', 'max' => 50],
[['file'], 'safe'],
]; ];
} }
...@@ -100,8 +99,6 @@ class Bid extends \common\components\ActiveRecordModel ...@@ -100,8 +99,6 @@ class Bid extends \common\components\ActiveRecordModel
'name' => 'Имя', 'name' => 'Имя',
'phone' => 'Телефон', 'phone' => 'Телефон',
'email' => 'Email', 'email' => 'Email',
'filename' => 'Прикрепленный файл',
'file' => 'Прикрепленный файл',
'text' => 'Сообщение', 'text' => 'Сообщение',
'form' => 'Форма отправки', 'form' => 'Форма отправки',
'created_at' => 'Дата добавления', 'created_at' => 'Дата добавления',
...@@ -109,25 +106,12 @@ class Bid extends \common\components\ActiveRecordModel ...@@ -109,25 +106,12 @@ class Bid extends \common\components\ActiveRecordModel
]; ];
} }
public function getUrl() /**
{ * @return \yii\db\ActiveQuery
return Yii::$app->params['frontUrl'] . self::FILE_FOLDER . $this->filename; */
} public function getFiles()
public function getPath()
{
return Yii::getAlias('@frontend/web') . self::FILE_FOLDER;
}
public function upload()
{
if(!file_exists($this->getPath()))
{ {
mkdir($this->getPath(), 0777, true); return $this->hasMany(BidFile::className(), ['bid_id' => 'id']);
}
$this->filename = date('dmYHis-') . uniqid() . '.' . $this->file->extension;
$this->file->saveAs($this->getPath() . $this->filename);
} }
public function send() public function send()
......
<?php
namespace common\modules\bids\models;
use Yii;
/**
* This is the model class for table "bids_files".
*
* @property integer $id
* @property integer $bid_id
* @property string $filename
*
* @property Bids $bid
*/
class BidFile extends \common\components\ActiveRecordModel
{
const FILE_FOLDER = '/uploads/bids/';
public $file;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'bids_files';
}
/**
* @inheritdoc
*/
public function name()
{
return 'Файл заявки';
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['bid_id'], 'required'],
[['bid_id'], 'integer'],
[['filename'], 'string', 'max' => 100],
[['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg, gif, xls, xlsx, doc, docx, pdf', 'maxFiles' => 4],
[['bid_id'], 'exist', 'skipOnError' => true, 'targetClass' => Bid::className(), 'targetAttribute' => ['bid_id' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'file' => 'Прикрепленный файл',
'bid_id' => 'Заявка',
'filename' => 'Файл',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getBid()
{
return $this->hasOne(Bid::className(), ['id' => 'bid_id']);
}
public function getUrl()
{
return Yii::$app->params['frontUrl'] . self::FILE_FOLDER . $this->filename;
}
public static function path()
{
return Yii::getAlias('@frontend/web') . self::FILE_FOLDER;
}
}
...@@ -19,7 +19,7 @@ class SearchBid extends Bid ...@@ -19,7 +19,7 @@ class SearchBid extends Bid
{ {
return [ return [
[['id'], 'integer'], [['id'], 'integer'],
[['name', 'phone', 'email', 'filename', 'text', 'created_at', 'form'], 'safe'], [['name', 'phone', 'email', 'text', 'created_at', 'form'], 'safe'],
]; ];
} }
...@@ -67,7 +67,6 @@ class SearchBid extends Bid ...@@ -67,7 +67,6 @@ class SearchBid extends Bid
$query->andFilterWhere(['like', 'name', $this->name]) $query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'phone', $this->phone]) ->andFilterWhere(['like', 'phone', $this->phone])
->andFilterWhere(['like', 'email', $this->email]) ->andFilterWhere(['like', 'email', $this->email])
->andFilterWhere(['like', 'filename', $this->filename])
->andFilterWhere(['like', 'text', $this->text]); ->andFilterWhere(['like', 'text', $this->text]);
return $dataProvider; return $dataProvider;
......
...@@ -26,11 +26,19 @@ $this->params['breadcrumbs'][] = $this->title; ...@@ -26,11 +26,19 @@ $this->params['breadcrumbs'][] = $this->title;
'phone', 'phone',
'email:email', 'email:email',
[ [
'attribute' => 'filename', 'header' => 'Файлы',
'format' => 'html', 'format' => 'html',
'value' => function($model) 'value' => function($model)
{ {
return ($model->filename?Html::a($model->filename, $model->getUrl()):null); $files = [];
if($model->files)
{
foreach ($model->files as $file)
{
$files[] = Html::a($file->filename, $file->getUrl());
}
}
return implode('<br>', $files);
} }
], ],
'text:ntext', 'text:ntext',
......
<?php <?php
use yii\helpers\Html; use yii\helpers\Html;
use common\modules\bids\models\Bid; use common\modules\bids\models\BidFile;
?> ?>
Имя: <?=$model->name?><br> Имя: <?=$model->name?><br>
...@@ -12,7 +12,15 @@ Email: <?=$model->email?><br> ...@@ -12,7 +12,15 @@ Email: <?=$model->email?><br>
Сообщение: <?=$model->text?><br> Сообщение: <?=$model->text?><br>
Файл: <?=($model->filename?Html::a($model->filename,\Yii::$app->params['frontUrl'].Bid::FILE_FOLDER.$model->filename):'')?><br> <?php if($model->files) : ?>
<hr>
Файлы:
<?php foreach ($model->files as $file)
{
echo Html::a($file->filename,\Yii::$app->params['frontUrl'].BidFile::FILE_FOLDER.$file->filename) . '<br>';
} ?>
<hr>
<?php endif; ?>
Дата добавления заявки: <?=date('d.m.Y H:i:s', $model->created_at)?><br> Дата добавления заявки: <?=date('d.m.Y H:i:s', $model->created_at)?><br>
......
<?php
use yii\db\Schema;
use yii\db\Migration;
class m160224_162315_upgrade_bids_files extends Migration
{
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
$this->createTable('bids_files', [
'id' => Schema::TYPE_PK,
'bid_id' => Schema::TYPE_INTEGER . '(11) NOT NULL',
'filename' => Schema::TYPE_STRING . '(100) DEFAULT NULL'
]);
$this->dropColumn('bids', 'filename');
$this->addForeignKey(
'fk_bids_files_bid_id_bids_id',
'bids_files', 'bid_id',
'bids', 'id'
);
}
public function safeDown()
{
$this->dropForeignKey('fk_bids_files_bid_id_bids_id', 'bids_files');
$this->dropTable('bids_files');
$this->addColumn('bids', 'filename', Schema::TYPE_STRING . '(50) DEFAULT NULL');
}
}
...@@ -75,9 +75,6 @@ FileUploadBundle::register($this); ...@@ -75,9 +75,6 @@ FileUploadBundle::register($this);
<div class="file_upload_bt"> <div class="file_upload_bt">
<div class="file-upload"> <div class="file-upload">
<label> <label>
<?php/* echo $form->field($model, 'file', [
'template' => '<div class="row"><div class="col-sm-4">{input}</div></div>'
])->fileInput();*/ ?>
<span>Выбрать файл</span> <span>Выбрать файл</span>
</label> </label>
</div> </div>
...@@ -85,7 +82,9 @@ FileUploadBundle::register($this); ...@@ -85,7 +82,9 @@ FileUploadBundle::register($this);
<div class="file_drop">Перетащите файл в данную область<br/> или выберите файл с компьютера</div> <div class="file_drop">Перетащите файл в данную область<br/> или выберите файл с компьютера</div>
</div> </div>
</div> </div>
<input type="hidden" name="file_name" id='file_name' value=""/> <div id="files-zone">
</div>
<?php echo Html::submitButton('Рассчитать проект', ['class' => 'btn-default save-button']); ?> <?php echo Html::submitButton('Рассчитать проект', ['class' => 'btn-default save-button']); ?>
<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>
......
...@@ -129,17 +129,15 @@ FileUploadBundle::register($this); ...@@ -129,17 +129,15 @@ FileUploadBundle::register($this);
<div class="file_upload_bt_cs"> <div class="file_upload_bt_cs">
<div class="file-upload_cs"> <div class="file-upload_cs">
<label> <label>
<?php /*echo $form->field($model, 'file', [
'template' => '<div class="row"><div class="col-sm-4">{input}</div></div>'
])->fileInput(); */?>
<span>Выбрать файл</span> <span>Выбрать файл</span>
</label> </label>
</div> </div>
<!--<input type="text" id="filename" class="filename_cs" disabled>-->
<div class="file_drop_cs">Перетащите файл в данную область<br/> или выберите файл с компьютера</div> <div class="file_drop_cs">Перетащите файл в данную область<br/> или выберите файл с компьютера</div>
</div> </div>
</div> </div>
<input type="hidden" name="file_name" id='file_name' value=""/> <div id="files-zone">
</div>
<?php echo Html::submitButton('Отправить', ['class' => 'btn-default save-button']); ?> <?php echo Html::submitButton('Отправить', ['class' => 'btn-default save-button']); ?>
......
...@@ -39,6 +39,9 @@ $('form.bids-form').on('beforeSubmit', function(e) { ...@@ -39,6 +39,9 @@ $('form.bids-form').on('beforeSubmit', function(e) {
form.find('input:not(.not_clear), textarea').val(''); form.find('input:not(.not_clear), textarea').val('');
$('.send_secce').show(); $('.send_secce').show();
form.find('#files-zone').html('');
$('.dz-preview.dz-processing').remove();
dataLayer.push({ dataLayer.push({
'event': 'UA_event', 'event': 'UA_event',
'Catagory': form.data('tag'), 'Catagory': form.data('tag'),
......
...@@ -6,15 +6,16 @@ $(document).ready(function() { ...@@ -6,15 +6,16 @@ $(document).ready(function() {
// var myDropzone = new Dropzone("div#block_upload", {url: "/bids/bid/upload-files", maxFiles: 1}); // var myDropzone = new Dropzone("div#block_upload", {url: "/bids/bid/upload-files", maxFiles: 1});
Dropzone.options.blockUpload = { Dropzone.options.blockUpload = {
url: "/bids/bid/upload-files", url: "/bids/bid/upload-files",
maxFiles: 1, maxFiles: 4,
addRemoveLinks: true, addRemoveLinks: true,
dictRemoveFile: 'Удалить', dictRemoveFile: 'Удалить',
/*accept: function(file, done) { /*accept: function(file, done) {
$('#file_name').val(file.name); $('#file_name').val(file.name);
done(); done();
},*/ },*/
success: function(first,response) { success: function(first, response)
$('#file_name').val(response); {
$('#files-zone').append('<input type="hidden" name="Bid[file][]" value="'+response.filename+'" />');
$('.file_drop').hide(); $('.file_drop').hide();
$('.file_drop_cs').hide(); $('.file_drop_cs').hide();
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment