Dependant datepickers - yii2

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?

Related

Update data in Kartik Detailview is not working

I've detail showed using Kartik Detail View. This widget has Edit inline function by clicking pencil icon button in top right side like this.
But then the table doesn't be editable :
And nothing happen, my data still the same, my update not success. It's possible to solve my problem? Thanks.
I have read the official guide and it looks identical:
https://demos.krajee.com/detail-view
This is my view code:
<?php echo DetailView::widget([
'model' => $modelAnagrafiche,
'responsive' => true,
'mode' => 'edit',
'enableEditMode' => true,
'buttons1' => '{update}',
'panel' => [
'type' => 'primary',
'heading' => 'Contratto' . ' : ' . $modelAnagrafiche >cognome_ragione_sociale . ' ' . $modelAnagrafiche->nome
],
'attributes' => [
[
'group'=>true,
'label'=>'Sezione Anagrafica',
'rowOptions'=>['class'=>'table-primary']
],
[
'columns' => [
[
'attribute' => 'cognome_ragione_sociale',
'displayOnly' => true,
'valueColOptions' => ['style' => 'width:30%']
],
[
'attribute' => 'nome',
'format' => 'raw',
'valueColOptions' => ['style' => 'width:30%'],
'displayOnly' => true,
'type' => DetailView::INPUT_TEXT,
],
],
],
[
'columns' => [
[
'attribute' => 'codice_fiscale',
'displayOnly' => true,
'valueColOptions' => ['style' => 'width:30%']
],
[
'attribute' => 'partita_iva',
'format' => 'raw',
'valueColOptions' => ['style' => 'width:30%'],
'displayOnly' => true
],
],
],
[
'columns' => [
[
'attribute' => 'tipo_documento',
'displayOnly' => true,
'valueColOptions' => ['style' => 'width:30%'],
'format' => 'raw',
'value' => $modelAnagrafiche->tipoDocumento,
],
[
'attribute' => 'numero_documento',
'format' => 'raw',
'valueColOptions' => ['style' => 'width:30%'],
'displayOnly' => true
],
],
],
[
'columns' => [
[
'attribute' => 'data_nascita',
'displayOnly' => true,
'format' => 'date',
'type' => DetailView::INPUT_DATE,
'widgetOptions' => [
'pluginOptions' => ['format' => 'yyyy-mm-dd']
],
],
[
'attribute' => 'id_provincia_nascita',
'displayOnly' => true,
'valueColOptions' => ['style' => 'width:30%'],
'format' => 'raw',
'value' => $modelAnagrafiche->provinciaNascitaNome,
'label' => 'Provincia Nascita'
],
],
],
[
'columns' => [
[
'attribute' => 'id_comune_nascita',
'displayOnly' => true,
'format' => 'raw',
'value' => $modelAnagrafiche->comuneNascitaNome,
'label' => 'Comune Nascita'
],
],
],
],
]);
?>
This is the action in my controller:
public function actionUpdateAnagrafica()
{
$post = Yii::$app->request->post();
if (empty($post['Anagrafiche']['id'])) {
throw new NotFoundHttpException('Non esiste nessuna anagrafica.');
}
$modelAnagrafiche = Anagrafiche::findOne($post['Anagrafiche']['id']);
if ($modelAnagrafiche->load($post) && $modelAnagrafiche->save()) {
return $this->redirect(['view', 'id' => $modelAnagrafiche->id]);
} else {
return $this->render('update-anagrafica', [
'modelAnagrafiche' => $modelAnagrafiche,
]);
}
}
You have to remove all the displayOnly attributes.
According to the official guide:
displayOnly: boolean|Closure, if the input is to be set to as display
only in edit mode. If set to true, no editable form input will be
displayed, instead this will display the formatted attribute value.

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!

How to add error messages for DateValidation?

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'),
]
]) ?>

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}; }'),
],
],
]),
],

Yii2 kartik typeahead - get number of suggestions

I'm using kartik's typeahead widget for Yii2 in a view:
echo \kartik\typeahead\Typeahead::widget([
'name' => 'serial_product',
'options' => [
'placeholder' => 'Filter as you type ...',
'autofocus' => "autofocus"
],
'scrollable' => TRUE,
'pluginOptions' => [
'highlight' => TRUE,
'minLength' => 3
],
'dataset' => [
[
'remote' => Url::to(['transfers/ajaxgetinventoryitemsnew']) . '?search=%QUERY',
'limit' => 10
]
],
'pluginEvents' => [
"typeahead:selected" => "function(obj, item) { add_item(item.id); return false;}",
],
]);
How can i get the number of loaded suggestions after the remote dataset is retrieved to execute a javascript function like:
displaynumber(NUMBEROFSUGGESTIONS);
After checking through the source of kartiks widget i came up with the following solution:
echo \kartik\typeahead\Typeahead::widget([
'name' => 'serial_product',
'options' => [
'placeholder' => 'Filter as you type ...',
'autofocus' => "autofocus",
'id' => 'serial_product'
],
'scrollable' => TRUE,
'pluginOptions' => [
'highlight' => TRUE,
'minLength' => 3
],
'dataset' => [
[
'remote' => [
'url' => Url::to(['transfers/ajaxgetinventoryitemsnew']) . '?search=%QUERY',
'ajax' => ['complete' => new JsExpression("function(response)
{
jQuery('#serial_product').removeClass('loading');
checkresult(response.responseText);
}")]
],
'limit' => 10
]
],
'pluginEvents' => [
"typeahead:selected" => "function(obj, item) { checkresult2(item); return false;}",
],
]);
where response.responseText is containing the response from server (json).
function checkresult(response) {
var arr = $.parseJSON(response);
console.log(arr.length);
}
With this function i can get then count of suggestions delivered from server.