Dependent dropdown is not working in Yii2 - php

How to add id in select2 dropdownlist kartik. The goal I want when I choose value "success" in dropdown, so value in the other dropdownlist example2 and example3 disabled is false. Before it, for dropdownlist example2 and example3 with value "yes" is false.
I've created code JavaScript but it is not working. What can I try next?
This my code :
<?php
echo $form->field($model, 'example')->widget(Select2::classname(), [
'model' => $model,
'hideSearch' => true,
'data' => ['success' => 'Success', 'fail' => "Fail"],
'language' => 'id',
'options' => [
'placeholder' => 'Pilih',
'options' => [
['id' => 'example'],
]
],
'pluginOptions' => [
'allowClear' => true,
'width' => '350px',
],
])->label('Example');
?>
<?php
echo $form->field($model, 'example2')->widget(Select2::classname(), [
'model' => $model,
'hideSearch' => true,
'data' => ['yes' => "Yes", 'no' => "No"],
'language' => 'id',
'options' => [
'placeholder' => 'Pilih',
'options' => [
'yes' => ['disabled' => true],
['id' => 'example2'],
]
],
'pluginOptions' => [
'allowClear' => true,
'width' => '350px',
],
])->label('Example 2');
?>
<?php
echo $form->field($model, 'example3')->widget(Select2::classname(), [
'model' => $model,
'hideSearch' => true,
'data' => ['yes' => "Yes", 'no' => "No"],
'language' => 'id',
'options' => [
'placeholder' => 'Pilih',
'options' => [
'yes' => ['disabled' => true],
['id' => 'example3'],
]
],
'pluginOptions' => [
'allowClear' => true,
'width' => '350px',
],
])->label('Example 3');
?>
This JavaScript code :
<?php
$this->registerJs('
$("input[type=dropdown]").change(function() {
var isi = this.value;
if(isi == "success") {
$("#example2").attr("disabled",false);
$("#example3").attr("disabled",false);
}
});
')
?>

May be this is what you want.
Add option to first select element (#example):
'pluginEvents' => [
"change" => "function() {
var value = $(this).val();
if(value == 'success')
{
$('#demo-example2').val('yes');
$('#demo-example2').trigger('change');
$('#demo-example3').val('yes');
$('#demo-example3').trigger('change');
}
}",
]

Related

how to save kartik editable yii2

I have a problem with editable kartik, how can I make editable kartik stored in the database? sometimes BAD REQUEST notifications appear
My Controller
public function actions()
{
return ArrayHelper::merge ( parent::actions () , [
'editable' => [
'class' => EditableColumn::className() ,
'modelClass' => AssetMasterRequest::className() ,
'forceCreate'=> false,
]
]);
}
My View
<?php
$gridColumns = [
'assetMaster.asset_name',
'request_date',
[
'class' => 'kartik\grid\EditableColumn',
'attribute' => 'requested_by',
'pageSummary' => 'Total',
'vAlign' => 'middle',
'width' => '210px',
'editableOptions' => function ($model, $key, $index) use ($ambildata) {
return [
'header' => 'Request By',
'formOptions' => ['action'=>'pru'] ,
'size' => 'md',
'afterInput' => function ($form, $widget) use ($model, $index) {
return $form->field($model, "request_notes");
}
];
}
],
[
'class' => 'kartik\grid\EditableColumn',
'attribute' => 'request_notes',
'vAlign' => 'middle',
'width' => '210px',
'editableOptions' =>[
'formOptions'=>[
'action'=>'editable'
],
]
],
'requested_by',
];?>
Please help. Have spent two days on this. Thanks!
You must return a JSON encoded response in the array format specified above with output and message values. This is important for the AJAX request to be processed and completed successfully.
Here is a grid view configuration with editable column
echo GridView::widget([
'id' => 'kv-grid-demo',
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumns, // check the configuration for grid columns by clicking button above
'containerOptions' => ['style' => 'overflow: auto'], // only set when $responsive = false
'headerRowOptions' => ['class' => 'kartik-sheet-style'],
'filterRowOptions' => ['class' => 'kartik-sheet-style'],
'pjax' => true, // pjax is set to always true for this demo
// set your toolbar
'toolbar' => [
[
'content' =>
Html::button('<i class="fas fa-plus"></i>', [
'class' => 'btn btn-success',
'title' => Yii::t('kvgrid', 'Add Book'),
'onclick' => 'alert("This will launch the book creation form.\n\nDisabled for this demo!");'
]) . ' '.
Html::a('<i class="fas fa-redo"></i>', ['grid-demo'], [
'class' => 'btn btn-outline-secondary',
'title'=>Yii::t('kvgrid', 'Reset Grid'),
'data-pjax' => 0,
]),
'options' => ['class' => 'btn-group mr-2']
],
'{export}',
'{toggleData}',
],
'toggleDataContainer' => ['class' => 'btn-group mr-2'],
// set export properties
'export' => [
'fontAwesome' => true
],
// parameters from the demo form
'bordered' => $bordered,
'striped' => $striped,
'condensed' => $condensed,
'responsive' => $responsive,
'hover' => $hover,
'showPageSummary' => $pageSummary,
'panel' => [
'type' => GridView::TYPE_PRIMARY,
'heading' => $heading,
],
'persistResize' => false,
'toggleDataOptions' => ['minCount' => 10],
'exportConfig' => $exportConfig,
'itemLabelSingle' => 'book',
'itemLabelPlural' => 'books'
]);

How to use onSelect event in Kartik datePicker?

I am using kartik datePicker in my site but whenever I try to use onSelect event the doesn't triggered I don't know what is the problem. I searched a lot but didn't find any solution.
This is my code:
<?php
echo DatePicker::widget([
'name' => 'check_issue_date',
'type' => DatePicker::TYPE_INLINE,
'options' => ['placeholder' => 'Select issue date ...', 'id' => 'date-picker'],
'pluginOptions' => [
'format' => 'dd-M-yyyy',
'todayHighlight' => false,
'onSelect' => 'function(dateText, inst) {
alert("hello");
}'
]
]);
?>
Look at pluginEvents on this page http://demos.krajee.com/widget-details/datepicker#settings
<?php echo DatePicker::widget([
'id'=>'scheduleProject',
'name' => 'scheduleProject',
'type' => DatePicker::TYPE_INLINE,
'language' => 'en',
'pluginOptions' => [
'format' => 'M-dd-yyyy',
'startDate' => date(\Yii::$app->params['viewDateFormat']),
'todayHighlight' => true,
'todayBtn' => true,
],
'pluginEvents' =>[
"changeDate" => "function(e) { alert(123)}",
]
]);?>
echo DatePicker::widget([
'name' => 'check_issue_date',
'type' => DatePicker::TYPE_INLINE,
'options' => ['placeholder' => 'Select issue date ...', 'id' => 'date-picker'],
'pluginOptions' => [
'format' => 'dd-M-yyyy',
'todayHighlight' => false,
'onSelect' => 'function(dateText, inst) {
alert("hello");
}'
],
'pluginEvents' => [
'onChange' => 'function(event) {
console.log(event.date);
}'
]
]);
?>

How to create a dynamic checkbox list based on dropdown list

I want to generate a dynamic checkbox list based on the drop down in yii2. The fields are as follows.
<?= $form->field($model, 'country')->dropDownList(Countries::getCountries(),
['id' => 'country_id', 'prompt' => 'Select countries'])
?>
<?= $form->field($model, 'state')->widget(DepDrop::classname(), [
//'data' => Regions::getRegions($model->country),
'options' => ['id' => 'region_id', 'prompt' => 'Choose a country first'],
'pluginOptions' => [
'depends' => ['country_id'],
'placeholder' => 'Select a state',
'url' => Url::to(['/regions/regions'])
]
]) ?>
<?= $form->field($model, 'city')->widget(DepDrop::classname(), [
//'data' => Cities::getCities($model->country),
'options' => ['id' => 'city_id', 'prompt' => 'Select a state'],
'pluginOptions' => [
'depends' => ['country_id','region_id'],
'placeholder' => 'Select',
'url' => Url::to(['/cities/cities'])
]
]) ?>
<?= $form->field($model, 'publisher_name')->widget(DepDrop::classname(), [
//'data' => Cities::getCities($model->country),
'options' => ['id' => 'user_id', 'prompt' => 'Choose a publisher'],
'pluginOptions' => [
'depends' => ['country_id','region_id','city_id'],
'placeholder' => 'Select',
'url' => Url::to(['/publisher/publishers'])
]
]) ?>
When I drop all the drop downs it is correctly returning a JSON which is as follows but now instead of drop down I want to create checkboxes how can I do that the JSON which is being returned is as follows
{"output":[{"user_id":"109","name":"user1"},{"user_id":"114","name":"user2"}],"selected":""}
Controller
public function actionPublishers() {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
if (isset(Yii::$app->request->post()['depdrop_parents'])) {
$parents = Yii::$app->request->post('depdrop_parents');
if ($parents != null) {
$countryID = $parents[0];
$stateID = $parents[1];
$cityId = $parents[2];
return [
'output' => publisher::getPublishers($countryID,$stateID,$cityId, true),
'selected' => '',
];
}
}
return ['output' => '', 'selected' => ''];
}

Yii2: Combining Kartik's FileInput & Kartik's DetailView

I'm trying single-file uploads using Kartik's FileInput.
Things go fine when doing this through standard create form as the following returns non-null:
$filedata = UploadedFile::getInstance($model, 'filedata');
However it always returns null when going into Kartik's DetailView in edit mode and trying to update the file.
In view.php I have:
[
'attribute' => 'filedata',
'visible' => Yii::$app->user->can('doIt'),
'type' => DetailView::INPUT_FILEINPUT,
'rowOptions' => ['class' => 'kv-view-hidden'],
'widgetOptions' => ['options' => ['accept' => 'application/pdf'],
'pluginOptions' => [
'showUpload' => false,
'allowedFileExtensions' => ['pdf'],
'initialCaption' => $model->filename,
],
'pluginEvents' => [
'filecleared' => <whatever>,
'fileloaded' => <whatever>,
],
],
],
while in _form.php (which does work):
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'filedata')->widget(FileInput::classname(), [
'options' => ['accept' => 'application/pdf'],
'pluginOptions' => [
'showUpload' => false,
'allowedFileExtensions' => ['pdf'],
'initialCaption' => $model->getOldAttribute('filename'),
],
'pluginEvents' => [
'filecleared' => <whatever>,
'fileloaded' => <whatever>,
],
])
?>
Any ideas? (BTW, don't know whether 'multipart/form-data' is needed somehow in view.php as it is in _form.php, so anyone confirming this and giving some details should be welcome).
Of course, multipart/form-data is needed both in _form.php and view.php as well, as follows:
'formOptions' => ['options' => ['enctype' => 'multipart/form-data']],
'attributes' => [
...
[
'attribute' => 'filedata',
'visible' => Yii::$app->user->can('doIt'),
'type' => DetailView::INPUT_FILEINPUT,
'rowOptions' => ['class' => 'kv-view-hidden'],
'widgetOptions' => ['options' => ['accept' => 'application/pdf'],
'pluginOptions' => [
'showUpload' => false,
'allowedFileExtensions' => ['pdf'],
'initialCaption' => $model->filename,
],
'pluginEvents' => [
'filecleared' => <whatever>,
'fileloaded' => <whatever>,
],
],
],
....
]

Select2 after setting initial value, adding an another value changes the text of first value

I'm rendering select2 using karthik yii2 widget. I'm using the updated version.
I tried to set initial value using initSelection, it works fine. But when i try to add an another value it changes the pre selected value to ID which was set through initSelection.
<?php
$initScript = <<< SCRIPT
function (element, callback) {
var id = \$(element).val();
if (id !== "") {
var url = "{$url}";
\$.ajax(url.replace('idreplace', id), {dataType: "json"}).done(
function(data) {
callback(data.results);
});
}
}
SCRIPT;
echo Select2::widget([
'language' => 'en',
'name' => 'to',
'value' => ['1'],
'options' => [
'placeholder' => 'Choose...',
'id' => "to",
'multiple' => true,
'data-validation'=>'required',
],
'pluginOptions' => [
'language' => [
'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
],
'allowClear' => true,
'minimumInputLength' => 3,
'multiple' => true,
'ajax' => [
'url' => $url,
'dataType' => 'json',
'tags' => true,
'data' => new JsExpression('function(params) { return {search:params.term}; }'),
'results' => new JsExpression('function(data,page) {return { results:data.results }; }'),
],
'initSelection' => new JsExpression($initScript)
],
]);
?>
Finally i resolved my issue. initselection is deprecated in select2 4.0 . i tried to set the initial value using "initValueText"
echo Select2::widget([
'language' => 'en',
'initValueText' => ['intialvaluetext'],//text of initial value
'name' => 'to',
'value' => ['1'],//matching id for initial value text
'options' => [
'placeholder' => 'Choose...',
'id' => "to",
'multiple' => true,
'data-validation'=>'required',
],
'pluginOptions' => [
'language' => [
'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
],
'allowClear' => true,
'minimumInputLength' => 3,
'multiple' => true,
'ajax' => [
'url' => $url,
'dataType' => 'json',
'tags' => true,
'data' => new JsExpression('function(params) { return {search:params.term}; }'),
'results' => new JsExpression('function(data,page) {return { results:data.results }; }'),
],
],
]);
?>

Categories