Yii2 captcha always incorrect - yii2

Whan I add 'on' => 'create' in my rule my captcha always incorrect
Off that work good why?
I try to let it to other controller support/captcha but still incorrect
MyView
<?= Captcha::widget([
'id' => 'captcha',
'model' => $model,
'attribute' => 'verifyCode',
'options' => ['class' => 'form-control',
'data-v-rule' => '',
'captchaAction' => 'support/captcha',
'data-v-msg' => $i18n->t('please.input.verify.code'),
'placeholder' => $i18n->t('please.input.verify.code', '', false)]
]); ?>
Myrule
...
[['verifyCode'], 'captcha', 'message' => $i18n->t('error.verifyCode'),'captchaAction' => 'support/captcha' , 'on' => 'create'],
...
I get seesion
$_SESSION = [
'__flash' => [],
'__captcha/site/captcha' => 'nnbioo',
'__captcha/site/captchacount' => 1,
'__captcha/support/captcha' => 'cacijq',
'__captcha/support/captchacount' => 1,
];
Mycontroller
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => CaptchaAction::className(),
],
];
}

$customerServiceModel->load($post) is not working, because attribute verifyCode is not safe in this case. Your rule is specified with 'on' => 'create' - so it means, it's save on scenario create. You didn't assigned this scenario to the model so there's 2 solutions:
Remove 'on' => 'create' from rule
Assign create scenario to model by $customerServiceModel->scenario = 'create'; before using load().

Related

Listview pagination and GET parameters on the next page

I have this UrlManager rule:
'<pageSlug>-pa<pageId:\d+>' => 'page/page',
Then I have page with url like this domain.com/blog-pa54
In this example I have
pageSlug = blog and pageId = 54
In my view I have ListView with my blog posts.
I set my dataprovider like this:
$dataProvider = new ActiveDataProvider([
'query' => BlogPost::find()
->where([
'active' => 1
]),
'pagination' => [
'defaultPageSize' => 3,
//'params' => [], when I set this, it only shows get param "page"
'pageParam' => 'page',
'route' => $pageURL, // this variable is equal to "blog-pa54"
],
]);
My route is current url slug - blog-pa54
When I go to next page I recieve this url: blog-pa54?pageSlug=blog&pageId=54&page=2
How can I remove $_GET params pageSlug and pageId from url?
I try to set pagination > params = [] and it remove this get param, but when I go to other page it doesn't change items in my ListView
Here is also my ListView and LinkPager
<div class="blog-post-wrapper">
<?= ListView::widget([
'dataProvider' => $blogPostsDataprovider,
'itemOptions' => ['tag' => null],
'options' => [
'tag' => false,
],
'layout' => "{summary}<div class='row'>{items}</div>",
'itemView' => function ($model, $key, $index, $widget) use ($page) {
return $this->render('//blog-post/_blogPostList', [
'page' => $page,
'model' => $model
]);
},
]); ?>
</div>
<?= \yii\widgets\LinkPager::widget([
'pagination' => $blogPostsDataprovider->pagination,
'linkContainerOptions' => [
'class' => 'page-item',
],
'linkOptions' => [
'class' => 'page-link',
],
]); ?>
Okay, I figured it out.
params attribute must not be empty.
You can set it like this:
'params' => [
'page' => isset($_GET['page']) ? $_GET['page'] : 1,
]
Or if you have another get params like get filters:
$getParams = [];
if(isset($_GET)){
foreach($_GET as $getKey => $getValue){
if(in_array($getKey, ['pageSlug', 'pageId'])){ //here I skip my params from UrlManager rule
continue;
}
$getParams[$getKey] = $getValue;
}
}
.....
'params' => $getParams

Is there a way to dynamically change maximumSelectionLength on kartik/select2 in yii2?

I am trying to update through javascript the maximumSelectionLength parameter of a select2 field (listeProduits) based on the value of a second select2 (nom_id) when it is changed.
I'm first storing the maxChildren values in a js table before loading the form so that I can access it on the client side when a new nom_id is selected.
The below approach doesn't work though as it messes up the listeProduits select2.
<script>
var nomMaxChildren = <?= json_encode(ArrayHelper::map(Nom::find()->asArray()->where(['type' => 'Boite'])->all(), 'id', 'max_children')); ?>;
alert(nomMaxChildren[1]);
</script>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'nom_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Nom::find()->asArray()->where(['type' => 'Boite'])->all(), 'id', 'nom'),
'options' => ['placeholder' => Yii::t('app','Select a name...')],
'pluginEvents' => [
"select2:select" => "function() {
$('select[name =\"listeProduits[]\"]').select2({
maximumSelectionLength: nomMaxChildren[\$(this).val()]
});
}",
]
]);?>
<label class="control-label"><?= Yii::t('app', 'Produits')?></label>';
<?= Select2::widget([
'attribute' => 'listeProduits',
'name' => 'listeProduits',
'data' => ArrayHelper::map(Produit::find()->asArray()->where(['statut_id' => 2])->andWhere(['boite_id' => null])->orWhere(['boite_id' => $model->id])->all(), 'id', 'numero_de_serie'),
'value' => (is_null($model->id)) ? null : ArrayHelper::map(Produit::find()->asArray()->where(['boite_id' => $model->id])->all(), 'id', 'id'),
'options' => ['placeholder' => Yii::t('app','Select products')],
'pluginOptions' => [
'allowClear' => true,
'multiple' => true,
'maximumSelectionLength' => (isset($model->nom)) ? $model->nom->max_children : null,
],
'showToggleAll' => false,
]);?>
Also if you have any idea on how to validate the fact that the maximumSelectionLength is ok on client side, it would be great :D
set maximumSelectionLength property dynamically :
$('#demo-select').select2({ maximumSelectionLength: 1 });

Yii2 sort object defaultOrder

I have a table of policies that belong to chapters. When I view the policies in my grid view I want the default order be policy title within chapter title. I see how to set up sort attributes to enable this, but I can't figure out how to set the defaultOrder to be based on chapter title and then policy title. When ever I try to set policy.title as an attribute in the defaultOrder setting I get an error.
If Policy is model class of policy table that has a relation with chapter table named 'chapter' and linked by chapter_id field, such as:
public function getChapter()
{
return $this->hasOne(Chapter::className(), ['chapter_id' => 'chapter_id']);
}
Now you build query object with policy joined with chapter:
$query = Policy::find()
->joinWith(['chapter']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['chapter.title'=>SORT_ASC, 'policy.title' => SORT_ASC]]
]);
I could not get Fabrizio's answer to work, because my chapter table is policy_chapter, not just chapter and so is not the same as the relation name. When I tried to use the relation name, I got errors. I finally figured out in the sort, you have to use the names of the related tables, not the relations, and add them as attributes. e.g.:
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => ['pageSize' => 50],
'sort' => [
'defaultOrder' => ['policy_chapter.sort' => SORT_ASC,'policy_chapter.title' => SORT_ASC],
'enableMultiSort' => true,
'attributes' => [
'id' => [
'asc' => ['policy.id' => SORT_ASC],
'desc' => ['policy.id' => SORT_DESC],
'default' => SORT_ASC
],
'chapter_id' => [
'asc' => ['policy_chapter.sort' => SORT_ASC,'policy_chapter.title' => SORT_ASC],
'desc' => ['policy_chapter.sort' => SORT_DESC,'policy_chapter.title' => SORT_DESC],
'default' => SORT_ASC,
],
'reference' => [
'asc' => ['reference' => SORT_ASC],
'desc' => ['reference' => SORT_DESC],
'default' => SORT_ASC
],
'title' => [
'asc' => ['policy.title' => SORT_ASC],
'desc' => ['policy.title' => SORT_DESC],
'default' => SORT_ASC
],
'policy_chapter.sort',
'policy_chapter.title',
],
],
]);
Use the relation name or leave out the attributes and you get errors. Before I was writing
'defaultOrder' => ['policy_chapter.sort' => SORT_ASC,'policy_chapter.title' => SORT_ASC],
and Yii was not happy

Capcha always show incorrect

I have used capcha in one of my forms. It always give verification code incorrect error.
Below is my code:
SchoolsController.php
public function actions() {
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fontFile' => '#yii/captcha/SpicyRice.ttf',
'padding' => '0',
]
];
}
Model:
['verifyCode', 'captcha', 'captchaAction' => 'schools/captcha'],
View:
echo $form->field($modelSchoolRequestEarlyAccess, 'verifyCode')->widget(Captcha::className(), [
'options' => [
'placeholder' => 'Enter characters in the image',
'autocomplete' => 'off',
'maxlength' => 20
],
'captchaAction' => 'schools/captcha',
'template' => "<div class='field'><span><strong>*</strong>".Yii::t('frontend/quicksignup','VerifyCodeLabel').":</span></span>\n<div>{image}{input}<i class='refresh-code-icn' id='get-new-code'></i></div></div>"
])->label(false);
I have specified the captcha action as schools/captcha in model as well as view. But it always show verification incorrect.
What am I doing wrong??
You wrote SchoolController.php and your route is to schools. So you probably need to adjust your route to school/captcha
Did you add the rules?
public function rules()
{
$rules = parent::rules();
$rules[] = ['captcha', 'required'];
$rules[] = ['captcha', 'captcha'];
return $rules;
}

Yii2 DateControl: How to set default value (date)

I have in views/example/_form.php the following date field:
use yii\widgets\ActiveForm;
use kartik\datecontrol\DateControl;
...
$form = ActiveForm::begin();
...
echo $form->field($model, 'date')->widget(DateControl::className(), [
'type' => DateControl::FORMAT_DATE,
// 'value' => date('Y-m-d'),
// 'value' => date('d.m.Y'),
// 'value' => time(),
// 'value' => '02.12.2015',
// 'value' => '2015-12-02',
// 'value' => '2015-12-02 00:00:00 0000',
// 'value' => date('Y-M-d'),
// 'value' => date('d.M.Y'),
// 'value' => date('dd.MM.yyyy'),
]);
...
ActiveForm::end();
None of my attempts to set the default date was successfull (see the commented lines above). I have always received no error message and no default value. The resulting HTML input field looks always the same (the 'value' is empty):
<input type="text" id="yiiversion-date-disp" class="form-control" name="date-yiiversion-date" value="" data-krajee-datecontrol="datecontrol_1e107159" data-datepicker-source="yiiversion- date-disp-kvdate" data-datepicker-type="2" data-krajee-kvdatepicker="kvDatepicker_0aa71c62">
Configuration in config/main.php looks like this:
'modules' => [
'datecontrol' => [
'class' => 'kartik\datecontrol\Module',
'autoWidget' => true,
'autoWidgetSettings' => [
'date' => [
'pluginOptions' => [
'autoclose' => true,
'todayHighlight' => true,
'todayBtn' => true,
],
],
],
],
],
The dates are displayed as 01.01.2015 ('dd.MM.yyyy') and saved as 2015-01-01 ('Y-M-d') - MySQL datatype DATE.
More information:
https://github.com/kartik-v/yii2-datecontrol
http://demos.krajee.com/datecontrol
As suggested by InsaneSkull the solution is quite simple. I had to add to the correspondig controller only: $model->date = date('Y-m-d');
The resulting action could look e.g. like this:
public function actionCreate()
{
$model = new YiiTask();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
$model->date = date('Y-m-d');
return $this->render('create', [
'model' => $model,
]);
}
}