Commit de4b99aa authored by Shakarim Sapa's avatar Shakarim Sapa

- Изменили логику подписки

parent e689c350
...@@ -5,6 +5,7 @@ namespace common\modules\cases\controllers; ...@@ -5,6 +5,7 @@ namespace common\modules\cases\controllers;
use Yii; use Yii;
use common\components\BaseController; use common\components\BaseController;
use common\modules\cases\models\CasesBids; use common\modules\cases\models\CasesBids;
use yii\helpers\Json;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\web\Response; use yii\web\Response;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
...@@ -31,20 +32,24 @@ class DefaultController extends BaseController ...@@ -31,20 +32,24 @@ class DefaultController extends BaseController
} }
/** /**
* @return array * @param $email
* @throws NotFoundHttpException * @throws \yii\web\NotFoundHttpException
* @throws \Exception
*/ */
public function actionAdd(){ public function actionAdd($email){
Yii::$app->response->format = Response::FORMAT_JSON; Yii::$app->response->format = Response::FORMAT_JSON;
// Получили дату // Получили дату
$date = new \DateTime(); $date = new \DateTime();
// Создали модель // Создали модель
$model = new CasesBids(); $model = new CasesBids();
// Результирующий массив
$result = [
'result' => false
];
// Получили и переопределили данные из формы // Получили и переопределили данные из формы
if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) { if(Yii::$app->request->isAjax) {
// Переопределили дату // Переопределили дату
$model->date = $date->format('Y-m-d H:i:s'); $model->date = $date->format('Y-m-d H:i:s');
$model->email = $email;
// Открыли транзакцию // Открыли транзакцию
$transaction = Yii::$app->db->beginTransaction(); $transaction = Yii::$app->db->beginTransaction();
// Пытаемся сохранить запись в базе // Пытаемся сохранить запись в базе
...@@ -54,16 +59,17 @@ class DefaultController extends BaseController ...@@ -54,16 +59,17 @@ class DefaultController extends BaseController
// Коммитим транзакцию // Коммитим транзакцию
$transaction->commit(); $transaction->commit();
// Возвращаем результат // Возвращаем результат
return ['success' => true]; $result['result'] = true;
} else { } else {
// В противном случае возвращаем форму с ошибками // В противном случае возвращаем форму с ошибками
return ActiveForm::validate($model); $result['error'] = current(current($model->getErrors()));
} }
} catch (\Exception $e) { } catch (\Exception $e) {
// Обрабатываем исключение // Обрабатываем исключение
$transaction->rollBack(); $transaction->rollBack();
throw $e; $result['error'] = $e->getMessage();
} }
echo Json::encode($result);
} else { } else {
// Если это не ajax запрос, возвращаем ошибку // Если это не ajax запрос, возвращаем ошибку
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested page does not exist.');
......
...@@ -42,10 +42,10 @@ if ($cacheEmail!==false && CasesBids::find()->where(['email' => $cacheEmail])->e ...@@ -42,10 +42,10 @@ if ($cacheEmail!==false && CasesBids::find()->where(['email' => $cacheEmail])->e
'template' => '<div class="row"><div class="col-sm-4">{input}</div></div>', 'template' => '<div class="row"><div class="col-sm-4">{input}</div></div>',
'errorOptions' => [] 'errorOptions' => []
])->textInput([ ])->textInput([
'placeholder' => 'E-mail*' 'placeholder' => 'E-mail*',
]); ?> ]); ?>
<?php echo Html::submitButton(\Yii::t('form', 'Subscribe'), ['class' => 'save-button']); ?> <?php echo Html::button(\Yii::t('form', 'Subscribe'), ['class' => 'save-button']); ?>
</div> </div>
...@@ -55,31 +55,18 @@ if ($cacheEmail!==false && CasesBids::find()->where(['email' => $cacheEmail])->e ...@@ -55,31 +55,18 @@ if ($cacheEmail!==false && CasesBids::find()->where(['email' => $cacheEmail])->e
</div> </div>
<script type='text/javascript'> <script type='text/javascript'>
$('form.keys_mail_form').on('beforeSubmit', function(e) { $('.save-button').on('click', function() {
var form = $(this), xhr = new XMLHttpRequest, filebool = false, file, data = new FormData(); var form = $(this).closest('form');
var email = form.children('input[name="CasesBids[email]"]').val();
form.find('input, textarea').each(function(){ $.ajax({
data.append($(this).attr('name'), $(this).val()); url: form.attr('action'),
}); data: {
email: email
xhr.open("POST", form.attr('action'), true); },
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); method: 'GET',
success: function(response) {
xhr.send(data); var result = JSON.parse(response);
if (result.result==true) {
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4){
try {
var response = JSON.parse(xhr.responseText);
} catch(e) {
var response = xhr.responseText;
}
form.find('.has-error').removeClass('has-error');
if(response.success) {
if(form.find('.message-box.send_secce').length > 0) {
form.find('.message-box.send_secce').fadeIn('fast'); form.find('.message-box.send_secce').fadeIn('fast');
form.find('.content').css('visibility','hidden'); form.find('.content').css('visibility','hidden');
...@@ -87,54 +74,16 @@ if ($cacheEmail!==false && CasesBids::find()->where(['email' => $cacheEmail])->e ...@@ -87,54 +74,16 @@ if ($cacheEmail!==false && CasesBids::find()->where(['email' => $cacheEmail])->e
form.find('.message-box.send_secce').fadeOut('fast'); form.find('.message-box.send_secce').fadeOut('fast');
form.find('.content').css('visibility','visible'); form.find('.content').css('visibility','visible');
}, 2000); }, 2000);
} } else {
form.find('.message-box.send_err').html(result.error);
form.find('input:not(.not_clear), textarea').val('');
form.find('#files-zone').html('');
$('.dz-preview.dz-processing').remove();
dataLayer.push({
'event': 'UA_event',
'Catagory': form.data('tag'),
'Action': form.data('title'),
'Label': 'Успешно'
});
setInterval(function() {
form.parent('div').fadeOut(500);
}, 1600);
}
else {
var errors = [];
$.each(response, function(key, value) {
form.find('.field-'+key).addClass('has-error');
errors = errors.concat(value);
});
console.log(errors);
if(form.find('.message-box.send_err').length > 0)
{
form.find('.message-box.send_err').html(errors[0]);
form.find('.message-box.send_err').fadeIn('fast'); form.find('.message-box.send_err').fadeIn('fast');
setTimeout(function(){ setTimeout(function(){
form.find('.message-box.send_err').fadeOut('fast'); form.find('.message-box.send_err').fadeOut('fast');
}, 2000); }, 2000);
} }
dataLayer.push({
'event': 'UA_event',
'Catagory': 'Ошибки',
'Action': form.data('form'),
'Label': errors
});
}
} }
} });
}).on('submit', function(e){
return false;
}); });
</script> </script>
<?php endif; ?> <?php endif; ?>
\ No newline at end of file
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