How to add error messages for DateValidation? - yii2

In my model I use DateValidation
['date_birthday', 'date', 'format' => 'd.m.yy', 'min' => '01.01.1900', 'max' => date('d.m.yy'), 'tooSmall'=>'The date is from past. Try another','tooBig' => 'The date is from future. Try another', 'message' => 'Try to input the date'],
In view I call the widget
<?php echo $form->field($modelForm, 'date_birthday')->widget(\kartik\date\DatePicker::classname(), [
'type' => \kartik\date\DatePicker::TYPE_COMPONENT_APPEND,
'pickerButton' => false,
'options' => [
'placeholder' => '',
],
'pluginOptions' => [
'format' => 'dd.mm.yyyy',
'autoclose' => true,
'showMeridian' => true,
'startView' => 2,
'minView' => 2,
]
]) ?>
It checks for min and max dates, but show no error message. I think its because of different date formats in model and view. How to fix it?

If you submit form you will see error messages. According to this issue https://github.com/yiisoft/yii2/issues/7745 yii2 have not client-side validations of date
You can enable ajax validation. Add in create and update action before if statement
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
And add use yii\widgets\ActiveForm; on the top of controller class. In your _form.php file enable ajax for whole form
<?php $form = ActiveForm::begin([
'enableAjaxValidation' => true,
]); ?>
, or for the field only
<?php echo $form->field($model, 'date_birthday', ['enableAjaxValidation' => true])->widget(\kartik\date\DatePicker::classname(), [
...
Also, you can add plugin options for limit date with startDate and endDate (https://bootstrap-datepicker.readthedocs.io/en/latest/options.html#startdate)
<?php echo $form->field($model, 'date_birthday', ['enableAjaxValidation' => true])->widget(\kartik\date\DatePicker::classname(), [
'type' => \kartik\date\DatePicker::TYPE_COMPONENT_APPEND,
'pickerButton' => false,
'options' => [
'placeholder' => '',
],
'pluginOptions' => [
'format' => 'dd.mm.yyyy',
'autoclose' => true,
'showMeridian' => true,
'startView' => 2,
'minView' => 2,
'startDate' => '01.01.1900',
'endDate' => date('d.m.Y'),
]
]) ?>

Related

yii2 kartik daterangepicker autoselect end date when start date is clicked

I want to set end date the same as start date :
<?php
echo $form->field($model, 'date_range', [
'options' => ['class' => 'drp-container form-group']
])->widget(DateRangePicker::classname(), [
'id' => 'dateRange',
'convertFormat' => true,
'pluginOptions' => [
'timePicker' => true,
'timePicker24Hour' => true,
'timePickerIncrement' => 1,
'autodate' => true,
'minDate' => (string) date('Y-m-d H:i:s', strtotime('- 1 month')),
'maxDate' => (string) date('Y-m-d H:i:s'),
'singleDatePicker' => false,
'autoApply' => false,
'locale' => ['format' => 'Y-m-d H:i:s']
],
'pluginEvents' => [
],
])
?>
When i try to select end date like this it is not functioning :
$(document).on('click', 'td.available', function (e) {
$('#dateRange').data('daterangepicker').setEndDate(date);
})
Is it possible to make it work like i want?
Regards!

Dependant datepickers

I have two date fields, the maximum date cannot be before the initial date, so I disabled the pickupMaxDate, and enabled it again in onChange(). Right there I need to set the startDate param to the value selected in the first DatePicker
This is what i've tried:
<?=
$form->field($shipment, 'pickupDate')->widget(
DatePicker::className(), [
'clientOptions' => [
'autoclose' => true,
'todayHighlight' => true,
'language' => 'es',
'startDate' => '0d',
'format' => 'dd-M-yyyy'
],
'clientEvents' => [
'change' => 'function (dateText, inst) {
//-> WORKING
$("#shipment-pickupdatemax").prop("disabled", false);
//-> NOT WORKING
var mindate = $(this).datepicker("getDate"); //-> PRINTS (Wed Sep 28 2016 00:00:00 GMT-0600 (CST))
$("#shipment-pickupdatemax").datepicker("option", "startDate", mindate);
}',
],
]);
?>
<?=
$form->field($shipment, 'pickupDateMax')->widget(
DatePicker::className(), [
'clientOptions' => [
'autoclose' => true,
'todayHighlight' => true,
'language' => 'es',
'startDate' => '0d',
'format' => 'dd-M-yyyy'
],
'options' => [
'disabled' => true
]
]);
?>
How do I achieve this?

Setting empty text in kartik dynagrid

Am using kartik dynagrid and i would like to setup a text that shows when the dataprovider returns empty
The grid
echo DynaGrid::widget([
'columns' => $columns,
'showPersonalize' => true,
'emptyText'=>'Sorry all pr have pritems',///-----------------This is what i had set
'options' => ['id' => 'assignsolic-grid'],
'gridOptions' => [
'options' => ['id' => 'grid'],
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'showPageSummary'=>false,
'pager' => [
'firstPageLabel' => 'First',
'lastPageLabel' => 'Last',
'maxButtonCount' => 10,
],
'panel' => [
'type' => GridView::TYPE_PRIMARY,
// 'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-book"></i> </h3>',
'before'=>'<i>Select the Prs to assign solicitation and then click the Assign Solicitation button</i>',
'after' =>
Html::button(' <i class=" glyphicon glyphicon-road "></i> Assign Solicitation ', ['value' => Url::to('assignsolc'),'class' => 'btn btn-danger', 'id' => 'assignsolic']),
'footer' => false
],
'toolbar' => [
['content' => '{dynagridFilter}{dynagridSort}{dynagrid}'],
'{export}',
'{toggleData}'
],
'pjax' => true,
'bordered' => false,
'striped' => true,
'condensed' => true,
'responsive' => true,
'responsiveWrap' => false,
'containerOptions'=>['style'=>'overflow:scroll'],
]
]) ;
This returs an error of Setting unknown property: kartik\dynagrid\DynaGrid::emptyText how can i set the empty text
You can define the value for null display directly in confi/main.php formatter component
'components' => [
.......
'formatter' => [
'class' => 'yii\i18n\Formatter',
'dateFormat' => 'dd.MM.yyyy',
'decimalSeparator' => ',',
'thousandSeparator' => ' ',
'currencyCode' => 'EUR',
'nullDisplay' => '', // **** this param
],
.....
Otherwise if the widget don't provide a proper attribute you can use an anonymous function for value
[
'attribute' => 'your_attribute',
'value' => function ($model) {
if ( $model->your_attribute == NULL) {
return 'Sorry all pr have pritems';
} else {
return $model->your_attribute;
}
},
],
Since am using $dataProvider i found out that i just have to check if the dataProvider is empty by
if (!$dataProvider->totalCount > 0) { pass in message to display }
else{?>
SHOW THE GRID HERE
<?php
}
?>
?>

Kartiv yii2 datepicker with model and custom id

I am using kartik datepicker extension http://demos.krajee.com/widget-details/datepicker in Yii2.
Issue :
If I use this with custom id for input it does not show show model validations
echo kartik\date\DatePicker::widget([
'model' => $objPatientModel,
'form'=>$objActiveForm,
'attribute' => 'date_of_birth',
'options' => ['placeholder' => 'Enter birth date ...', 'id' => 'patient_dob'], **// with id clientside validations for model does not work**
'pluginOptions' => [
'format' => 'dd-mm-yyyy',
'endDate' => date('d-m-Y'),
]
]);
While below code works
echo kartik\date\DatePicker::widget([
'model' => $objPatientModel,
'form'=>$objActiveForm,
'attribute' => 'date_of_birth',
'options' => ['placeholder' => 'Enter birth date ...'],**//id is not used here**
'pluginOptions' => [
'format' => 'dd-mm-yyyy',
'endDate' => date('d-m-Y'),
]
]);
But I want to use custom id .Any suggestions ?
You have to override the selectors, example:
$form->field($model, 'comment', ['selectors' => ['input' => '#myCustomId']])
->textarea(['id' => 'myCustomId']);?>
See https://github.com/yiisoft/yii2/issues/7627
<?=
$form->field($model, 'sales_date')->widget(DateControl::classname(), [
'name' => 'sales_date',
'value' => date('d-m-Y h:i:s'),
'type' => DateControl::FORMAT_DATETIME,
'autoWidget' => true,
'displayFormat' => 'php:d-m-Y h:i:s',
'saveFormat' => 'php:Y-m-d h:i:s',
'saveOptions' => [
'type' => 'hidden',
'form' => 'sales-form-red',
],
])
?>
by using the following option you can add extra form tag to input
'saveOptions' => [
'type' => 'hidden',
'form' => 'sales-form-red',
'class' => 'sales_date',
]
In my case out was
<input type="hidden" id="sales-sales_date" name="Sales[sales_date]" form="sales-form-red">
check by using link
Date Control Demo

Yii2: Select2, How to set initValueText in Gridview or Tabularform?

I need to set initValueText for Select2, which is in loop, like gridview or Tabularform. but I don't know how to set right value for each.
<?= TabularForm::widget([
'dataProvider' => $dataProvider,
'form' => $form,
'actionColumn' => false,
'checkboxColumn' => false,
'attributeDefaults' => [
'type' => TabularForm::INPUT_RAW,
],
'attributes' => [
'test' => [
'type' => Form::INPUT_WIDGET,
'widgetClass' => Select2::className(),
'options' => [
'name' => 'test',
'options' => [
'class' => 'test-to-select',
],
'pluginOptions' => [
'allowClear' => true,
'minimumResultsForSearch' => 'Infinity',
'ajax' => [
'url' => Url::to(['/test/get-list']),
'dataType' => 'json',
'data' => new JsExpression('function(term,page) {
return {term : term.term};
}'),
'results' => new JsExpression('function(data,page) {
return {results:data.results};
}'),
'cache' => true
]
],
'initValueText' => 'Selected Text' /// how can I set this in gridview or Tabularform?
],
],
]
]) ?>
Of course this is not working,
'initValueText' => function($model){
retur $model->textValue;
}
Any help would be appreciated.
Into tabularform if you want dynamic initValueText, you can use options closure in this manner:
'test' => [
'type' => Form::INPUT_WIDGET,
'widgetClass' => Select2::className(),
'options' => function($model, $key, $index, $widget) {
$initValueText = empty($model['textValue']) ? '' : $model['textValue'];
return [
'name' => 'test',
'options' => [
'class' => 'test-to-select',
],
'initValueText' => $initValueText,
'pluginOptions' => [
'allowClear' => true,
'minimumResultsForSearch' => 'Infinity',
'ajax' => [
'url' => Url::to(['/test/get-list']),
'dataType' => 'json',
'data' => new JsExpression('function(term,page) {
return {term : term.term};
}'),
'results' => new JsExpression('function(data,page) {
return {results:data.results};
}'),
'cache' => true
]
],
];
}
],
If for example attribute for city, so try this..
$cityDesc = empty($model->city) ? '' : City::findOne($model->city)->description;
'initValueText' => $cityDesc, // set the initial display text
For init value first assign value to $model attribute, if you should not assign so this attribute can take value.
Set the data parameter with the array including the option you want to show. For example for cities:
'options' => [
'data' => \yii\helpers\ArrayHelper::map(\app\models\City::find()->orderBy('id')->asArray()->all(), 'id', 'name'),
]
try to put inside the options instead ouside
'widgetClass' => Select2::className(),
'options' => [
'initValueText' => 'Selected Text'
Don't use isset it return error if more the one filter are use there.
[
'attribute' => 'ad_partner_id',
'value' => function ($model, $key, $index, $widget) {
return $model->partner->name;
},
'filter' => Select2::widget([
'model' => $searchModel,
'initValueText' => !empty($searchModel->ad_partner_id) ? $searchModel->partner->name : "",
'attribute' => 'ad_partner_id',
'options' => ['placeholder' => Yii::t('app', 'Search Partner ...')],
'pluginOptions' => ['allowClear' => true, 'autocomplete' => true,
'ajax' => ['url' => Url::base() . '/partner/get-partners',
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }'),
],
],
]),
],