3161 - Важно - Не работает форма подписки на кейс

parent 2d65c043
......@@ -53,31 +53,44 @@ class BlogBidController extends BaseController {
}
}
public function actionAdd(){
Yii::$app->response->format = Response::FORMAT_JSON;
$date = new \DateTime();
$model = new BlogBids();
$model->scenario = Yii::$app->request->post('scenario');
$model->date = $date->format('Y-m-d H:i:s');
if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
public function actionAdd($email, $name = null)
{
// Результирующий массив
$result = [
'result' => false
];
// Получили и переопределили данные из формы
if(Yii::$app->request->isAjax) {
$model = BlogBids::find()->where(['email' => $email])->one();
if(!$model) {
$model = new BlogBids();
$date = new \DateTime();
$model->date = $date->format('Y-m-d H:i:s');
$model->email = $email;
}
if(empty($model->name) || (!empty($name) && $model->name != $name)) {
$model->name = $name;
}
$transaction = Yii::$app->db->beginTransaction();
try {
// Если запись успешна
if($model->save()) {
// $model->send();
// Коммитим транзакцию
$transaction->commit();
return ['success' => true];
// Возвращаем результат
$result['result'] = true;
} else {
return ActiveForm::validate($model);
// В противном случае возвращаем форму с ошибками
$result['error'] = current(current($model->getErrors()));
}
} catch (\Exception $e) {
// Обрабатываем исключение
$transaction->rollBack();
throw $e;
$result['error'] = $e->getMessage();
}
return $this->asJson($result);
} else {
// Если это не ajax запрос, возвращаем ошибку
throw new NotFoundHttpException('The requested page does not exist.');
}
}
......
<?php
use common\modules\cases\models\CasesBids;
return [
'activeForm' => [
'id' => 'trigger-form'
......@@ -7,6 +10,15 @@ return [
'email' => [
'type' => 'text',
'class' => 'form-control',
],
'name' => [
'type' => 'text',
'class' => 'form-control',
],
'gender' => [
'type' => 'dropdownlist',
'class' => 'form-control',
'items' => CasesBids::$genderTitles
]
],
'buttons' => [
......
......@@ -13,9 +13,24 @@ use \common\components\ActiveRecordModel;
*
* @property integer $id
* @property string $email
* @property string $name
* @property integer $gender
* @property string $date
*/
class BlogBids extends ActiveRecordModel {
class BlogBids extends ActiveRecordModel
{
const GENDER_MALE = 1;
const GENDER_FEMALE = 2;
/**
* @var array
*/
public static $genderTitles = [
null => 'Не известно',
self::GENDER_MALE => 'Мужской',
self::GENDER_FEMALE => 'Женский',
];
/**
* @inheritdoc
*/
......@@ -41,6 +56,8 @@ class BlogBids extends ActiveRecordModel {
[['email'], 'required', 'message' => \Yii::t('blog', 'Please enter your e-mail')],
[['email'], 'unique', 'message' => \Yii::t('blog', 'You already subscribed to Art Project blog news')],
[['date'], 'safe'],
[['gender'], 'integer'],
[['name'], 'string', 'max' => 100],
[['email'], 'string', 'max' => 255],
];
}
......@@ -53,6 +70,8 @@ class BlogBids extends ActiveRecordModel {
return [
'id' => 'ID',
'email' => 'Email',
'name' => 'Имя',
'gender' => 'Пол',
'date' => 'Дата подписки',
];
}
......
<?php
use common\modules\blog\models\BlogBids;
use yii\helpers\Html;
use yii\grid\GridView;
......@@ -15,10 +17,15 @@ use yii\grid\GridView;
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'email',
'name',
[
'attribute' => 'gender',
'value' => function($model) {
/** @var BlogBids $model */
return BlogBids::$genderTitles[$model->gender];
}
],
'date:datetime',
[
'class' => 'yii\grid\ActionColumn',
......
......@@ -28,24 +28,39 @@ if ($cacheEmail!==false && BlogBids::find()->where(['email' => $cacheEmail])->ex
],
]); ?>
<div class="message-box send_secce">Теперь вы подписаны на обновления блога.</div>
<div class="message-box send_err" style="color:red; left: 26%; top: 44%;">Теперь вы подписаны на обновления блога.</div>
<div class="content">
<?php echo Html::hiddenInput('scenario', $model->scenario, ['class' => 'not_clear']); ?>
<?php //echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?>
<?php echo $form->field($model, 'email', [
'template' => '<div class="row"><div class="col-sm-4">{input}</div></div>',
'errorOptions' => []
])->textInput([
'placeholder' => 'E-mail*'
]); ?>
<?php echo Html::submitButton(\Yii::t('form', 'Subscribe'), ['class' => 'save-button']); ?>
<div class="case-subscribe-email">
<div class="subsc_block_txt"><?=\Yii::t('form', 'When we will prepare new interesting case – we will send you a detailed letter. Subscribe here!')?></div>
<?php echo $form->field($model, 'email', [
'template' => '<div class="row"><div class="col-sm-4">{input}</div></div>',
'errorOptions' => []
])->textInput([
'placeholder' => 'E-mail*'
]); ?>
</div>
<div class="case-subscribe-name case-subscribe-hide">
<div class="subsc_block_txt"><?=\Yii::t('form', 'You have successfully subscribed to the update notification.')?></div>
<div class="subsc_block_txt2"><strong><?=\Yii::t('form', 'Please enter your name.')?></strong></div>
<?php echo $form->field($model, 'name', [
'template' => '<div class="row"><div class="col-sm-12">{input}</div></div>',
'errorOptions' => []
])->textInput([
'placeholder' => 'Имя'
]); ?>
</div>
<div class="case-subscribe-success case-subscribe-hide">
<div class="subsc_block_txt"><?=\Yii::t('form', 'Thank you very much for showing interest!')?></div>
<img src="/images/thanks.png" alt="">
</div>
<?php echo Html::submitButton(\Yii::t('form', 'Subscribe'), ['class' => 'blog-subscribe-button']); ?>
</div>
......
......@@ -58,7 +58,7 @@ class CasesBidsAdminController extends AdminController{
'manage'
]);
}
$form = new \common\components\BaseForm('/common/modules/blog/forms/BidForm', $model);
$form = new \common\components\BaseForm('/common/modules/cases/forms/BidForm', $model);
return $this->render(
'create',
[
......@@ -82,7 +82,7 @@ class CasesBidsAdminController extends AdminController{
'manage'
]);
} else {
$form = new \common\components\BaseForm('/common/modules/blog/forms/BidForm', $model);
$form = new \common\components\BaseForm('/common/modules/cases/forms/BidForm', $model);
return $this->render(
'update',
[
......
......@@ -32,25 +32,29 @@ class DefaultController extends BaseController
}
/**
* @throws \yii\web\NotFoundHttpException
* @param $email
* @param null $name
* @return Response
* @throws NotFoundHttpException
*/
public function actionAdd($email){
public function actionAdd($email, $name = null){
// Результирующий массив
$result = [
'result' => false
];
// Получили и переопределили данные из формы
if(Yii::$app->request->isAjax) {
// Создали модель
$model = new CasesBids();
// Получили дату
$date = new \DateTime();
// Переопределили дату
$model->date = $date->format('Y-m-d H:i:s');
$model->email = $email;
// Открыли транзакцию
$model = CasesBids::find()->where(['email' => $email])->one();
if(!$model) {
$model = new CasesBids();
$date = new \DateTime();
$model->date = $date->format('Y-m-d H:i:s');
$model->email = $email;
}
if(empty($model->name) || (!empty($name) && $model->name != $name)) {
$model->name = $name;
}
$transaction = Yii::$app->db->beginTransaction();
// Пытаемся сохранить запись в базе
try {
// Если запись успешна
if($model->save()) {
......@@ -67,7 +71,7 @@ class DefaultController extends BaseController
$transaction->rollBack();
$result['error'] = $e->getMessage();
}
echo Json::encode($result);
return $this->asJson($result);
} else {
// Если это не ajax запрос, возвращаем ошибку
throw new NotFoundHttpException('The requested page does not exist.');
......
<?php
use common\modules\cases\models\CasesBids;
return [
'activeForm' => [
'id' => 'trigger-form'
......@@ -7,6 +10,15 @@ return [
'email' => [
'type' => 'text',
'class' => 'form-control',
],
'name' => [
'type' => 'text',
'class' => 'form-control',
],
'gender' => [
'type' => 'dropdownlist',
'class' => 'form-control',
'items' => CasesBids::$genderTitles
]
],
'buttons' => [
......
......@@ -12,10 +12,24 @@ use common\modules\users\models\User;
*
* @property integer $id
* @property string $email
* @property string $name
* @property integer $gender
* @property string $date
*/
class CasesBids extends ActiveRecordModel
{
const GENDER_MALE = 1;
const GENDER_FEMALE = 2;
/**
* @var array
*/
public static $genderTitles = [
null => 'Не известно',
self::GENDER_MALE => 'Мужской',
self::GENDER_FEMALE => 'Женский',
];
/**
* @inheritdoc
*/
......@@ -39,8 +53,11 @@ class CasesBids extends ActiveRecordModel
return [
[['email', 'date'], 'required'],
[['email'], 'unique', 'message' => 'Вы уже подписаны на рассылки по кейсам'],
[['date'], 'safe'],
[['date', 'name', 'gender'], 'safe'],
[['gender'], 'integer'],
[['email'], 'string', 'max' => 255],
[['name'], 'string', 'max' => 100],
[['name'], 'default', 'value' => null],
];
}
......@@ -92,6 +109,8 @@ class CasesBids extends ActiveRecordModel
return [
'id' => 'ID',
'email' => 'Email',
'name' => 'Имя',
'gender' => 'Пол',
'date' => 'Дата подписки',
];
}
......
<?php
use common\modules\cases\models\CasesBids;
use yii\helpers\Html;
use yii\grid\GridView;
......@@ -15,10 +17,15 @@ use yii\grid\GridView;
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'email',
'name',
[
'attribute' => 'gender',
'value' => function($model) {
/** @var CasesBids $model */
return CasesBids::$genderTitles[$model->gender];
}
],
'date:datetime',
[
'class' => 'yii\grid\ActionColumn',
......
<?php
use yii\db\Migration;
/**
* Class m190416_160300_fix_case_bids
*/
class m190416_160300_fix_case_bids extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->addColumn('cases_bids', 'name', $this->string(100)->after('email'));
$this->addColumn('cases_bids', 'gender', $this->smallInteger(1)->after('name'));
$this->addColumn('blog_bids', 'name', $this->string(100)->after('email'));
$this->addColumn('blog_bids', 'gender', $this->smallInteger(1)->after('name'));
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
$this->dropColumn('cases_bids', 'name');
$this->dropColumn('cases_bids', 'gender');
$this->dropColumn('blog_bids', 'name');
$this->dropColumn('blog_bids', 'gender');
}
}
......@@ -58,13 +58,13 @@ return [
'cache' => [
'class' => 'yii\caching\FileCache',
],
'view' => [
'class' => 'rmrevin\yii\minify\View',
'base_path' => '@app/web',
'minify_path' => '@app/web/minify',
'force_charset' => 'UTF-8',
'expand_imports' => true,
],
// 'view' => [
// 'class' => 'rmrevin\yii\minify\View',
// 'base_path' => '@app/web',
// 'minify_path' => '@app/web/minify',
// 'force_charset' => 'UTF-8',
// 'expand_imports' => true,
// ],
'user' => [
'identityClass' => 'common\modules\users\models\User',
'identityCookie' => [
......
......@@ -16,5 +16,8 @@ return [
'Liked? Subscribe up for updates!' => 'Понравилось? Подпишись на обновления!',
'We will try to publish this section only useful and unique content for the market. Subscription allow to be the first to get notification about fresh articles.' => 'Мы страемся публиковать в данном разделе только полезный и уникальный контент для рынка. По этому подпишись и ты будешь первым, кто получит уведомление о свежей публикации',
'Subscribe' => 'Подписаться',
'Write here summary of your article or send a short offer.' => 'Напишите краткие тезисы статьи или опишите интересующий вопрос.'
'Write here summary of your article or send a short offer.' => 'Напишите краткие тезисы статьи или опишите интересующий вопрос.',
'You have successfully subscribed to the update notification.' => 'Вы успешно подписались на уведомление об обновлениях.',
'Please enter your name.' => 'Пожалуйста, укажите своё имя:',
'Thank you very much for showing interest!' => 'Нам очень приятно, что вы проявили интерес!'
];
\ No newline at end of file
......@@ -56,7 +56,6 @@ $more = CaseContent::find()
<div class="col-md-6 col-xs-6 col-sm-12">
<div class="subsc_block">
<h2 class="subsc_block_title"><?=\Yii::t('form', 'Subscribe for cases updates')?></h2>
<div class="subsc_block_txt"><?=\Yii::t('form', 'When we will prepare new interesting case – we will send you a detailed letter. Subscribe here!')?></div>
<?php
$model = new CasesBids();
......@@ -70,9 +69,6 @@ $more = CaseContent::find()
],
]);
?>
<div class="message-box send_secce">Теперь вы подписаны на обновления кейсов.</div>
<div class="message-box send_err" style="color:red; left: 38%; top: 67%;"></div>
<div class="content">
......@@ -81,57 +77,39 @@ $more = CaseContent::find()
<?php //echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?>
<?php echo $form->field($model, 'email', [
'template' => '<div class="row"><div class="col-sm-12">{input}</div></div>',
'errorOptions' => []
])->textInput([
'placeholder' => 'E-mail*',
<div class="case-subscribe-email">
<div class="subsc_block_txt"><?=\Yii::t('form', 'When we will prepare new interesting case – we will send you a detailed letter. Subscribe here!')?></div>
<?php echo $form->field($model, 'email', [
'template' => '<div class="row"><div class="col-sm-12">{input}</div></div>',
'errorOptions' => []
])->textInput([
'placeholder' => 'E-mail*'
]); ?>
</div>
<div class="case-subscribe-name case-subscribe-hide">
<div class="subsc_block_txt"><?=\Yii::t('form', 'You have successfully subscribed to the update notification.')?></div>
<div class="subsc_block_txt2"><strong><?=\Yii::t('form', 'Please enter your name.')?></strong></div>
<?php echo $form->field($model, 'name', [
'template' => '<div class="row"><div class="col-sm-12">{input}</div></div>',
'errorOptions' => []
])->textInput([
'placeholder' => 'Имя'
]); ?>
</div>
<?php echo Html::button(\Yii::t('form', 'Subscribe'), ['class' => 'save-button']); ?>
<div class="case-subscribe-success case-subscribe-hide">
<div class="subsc_block_txt"><?=\Yii::t('form', 'Thank you very much for showing interest!')?></div>
<img src="/images/thanks.png" alt="">
</div>
<?php echo Html::button(\Yii::t('form', 'Subscribe'), ['class' => 'case-subscribe-button']); ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
<script type='text/javascript'>
$('.save-button').on('click', function() {
var form = $(this).closest('form');
var email = form.find('input[name="CasesBids[email]"]').val();
$.ajax({
url: form.attr('action'),
data: {
email: email
},
method: 'GET',
success: function(response) {
var result = JSON.parse(response);
if (result.result==true) {
form.find('.message-box.send_secce').fadeIn('fast');
form.find('.content').css('visibility','hidden');
setTimeout(function(){
form.find('.message-box.send_secce').fadeOut('fast');
form.find('.content').css('visibility','visible');
}, 2000);
setInterval(function() {
form.closest('.row').fadeOut(500);
}, 1600);
} else {
form.find('.message-box.send_err').html(result.error);
form.find('.message-box.send_err').fadeIn('fast');
setTimeout(function(){
form.find('.message-box.send_err').fadeOut('fast');
}, 2000);
}
}
});
});
</script>
<?php endif; ?>
</div>
<!-- </div>
......
......@@ -53,41 +53,4 @@ if ($cacheEmail!==false && CasesBids::find()->where(['email' => $cacheEmail])->e
</div>
</div>
</div>
<script type='text/javascript'>
$('.save-button').on('click', function() {
var form = $(this).closest('form');
var email = form.find('input[name="CasesBids[email]"]').val();
$.ajax({
url: form.attr('action'),
data: {
email: email
},
method: 'GET',
success: function(response) {
var result = JSON.parse(response);
if (result.result==true) {
form.find('.message-box.send_secce').fadeIn('fast');
form.find('.content').css('visibility','hidden');
setTimeout(function(){
form.find('.message-box.send_secce').fadeOut('fast');
form.find('.content').css('visibility','visible');
}, 2000);
setInterval(function() {
form.closest('.row').fadeOut(500);
}, 1600);
} else {
form.find('.message-box.send_err').html(result.error);
form.find('.message-box.send_err').fadeIn('fast');
setTimeout(function(){
form.find('.message-box.send_err').fadeOut('fast');
}, 2000);
}
}
});
});
</script>
<?php endif; ?>
\ No newline at end of file
......@@ -436,6 +436,14 @@ html {overflow-x: hidden;}
right: -340px;
}
.case-subscribe-hide {
display: none;
}
.case-subscribe-name .form-group,
.case-subscribe-name input {
margin-bottom: 0;
}
#footer {
background: url(../images/taskon_1/footer_bg.png) no-repeat center center;
-webkit-background-size: cover;
......
......@@ -39,4 +39,72 @@ $(document).ready(function () {
$(this).replaceWith(iframe);
});
});
$('.save-button').on('click', function() {
var form = $(this).closest('form');
var email = form.find('input[name="CasesBids[email]"]').val();
$.ajax({
url: form.attr('action'),
data: {
email: email
},
method: 'GET',
success: function(result) {
if (result.result==true) {
form.find('.message-box.send_secce').fadeIn('fast');
form.find('.content').css('visibility','hidden');
setTimeout(function(){
form.find('.message-box.send_secce').fadeOut('fast');
form.find('.content').css('visibility','visible');
}, 2000);
setInterval(function() {
form.closest('.row').fadeOut(500);
}, 1600);
} else {
form.find('.message-box.send_err').html(result.error);
form.find('.message-box.send_err').fadeIn('fast');
setTimeout(function(){
form.find('.message-box.send_err').fadeOut('fast');
}, 2000);
}
}
});
});
$('.case-subscribe-button, .blog-subscribe-button').on('click', function() {
var form = $(this).closest('form');
var $email = form.find('.case-subscribe-email input'),
$name = form.find('.case-subscribe-name input');
$.ajax({
url: form.attr('action'),
data: {
email: $email.val(),
name: $name.val()
},
method: 'GET',
success: function(result) {
if (result.result==true) {
if(!$('.case-subscribe-email').hasClass('case-subscribe-hide')) {
$('.case-subscribe-email').addClass('case-subscribe-hide');
$('.case-subscribe-name').removeClass('case-subscribe-hide');
} else {
$('.case-subscribe-name').addClass('case-subscribe-hide');
$('.case-subscribe-button').hide();
$('.case-subscribe-success').removeClass('case-subscribe-hide');
}
} else {
form.find('.message-box.send_err').html(result.error);
form.find('.message-box.send_err').fadeIn('fast');
setTimeout(function(){
form.find('.message-box.send_err').fadeOut('fast');
}, 2000);
}
}
});
return false;
});
});
\ 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