Jquery SELECT2 is not loading - javascript

This is my index file.
<?php
use yii\helpers\Url;
use yii\helpers\Html;
use yii\bootstrap\Modal;
use kartik\grid\GridView;
use johnitvn\ajaxcrud\CrudAsset;
use johnitvn\ajaxcrud\BulkButtonWidget;
CrudAsset::register($this);
$this->registerJs($this->render('script2.js'), \yii\web\VIEW::POS_READY);
?>
<div class="op-transaction-listing-index">
<div id="ajaxCrudDatatable">
<?=GridView::widget([
'id'=>'crud-datatable2',
'dataProvider' => $listing,
//'filterModel' => $searchModel,
'pjax'=>true,
'columns' => require(__DIR__.'/_columns.php'),
'toolbar'=> [
],
'striped' => true,
'condensed' => true,
'responsive' => true,
'resizableColumns'=>true,
'persistResize'=>true,
'bordered'=> true,
'panel' => [
'type' => 'primary',
'heading' => '<i class="glyphicon glyphicon-list"></i> Op Transaction Listings listing',
])?>
</div>
</div>
<?= Html::a('Create',false,['id'=>'test','class'=>'btn btn-success pull-right'])?>
<?php Modal::begin([
"id"=>"ajaxCrudModal",
"footer"=>"",// always need it for jquery plugin
])?>
<?php Modal::end(); ?>
What I do is click on the table cell it will remove the text within and append a select2 dropdown.
$(document).ready(function(){
$('#crud-datatable2-container > table > tbody > tr:nth-child(1) > td:nth-child(2)').on('click',function(){
$(this).text('');
$(this).append('<select name="testing" class="form-control" id="testing"></select>');
$('select#testing').select2();
});
});
But then it keep showing Uncaught TypeError: $(...).select2 is not a function..this type of error. I have only 1 script inside. Where did I did wrong?

Related

how will I append data I am selecting from a dropdown list to the next input field in yii2

I want to select courses from the course field, then let it show in my courses field and submit the courses to the database. or if someone can help me so my courses can appear has a checkbox and once i tick a checkbox, it appears in the courses field
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($model, 'student_id') ?>
<?=
$form->field($model, 'faculty_id')->dropDownList(
ArrayHelper::map(Faculties::find()->asArray()->all(), 'faculty_id', 'faculty_name'), [
'prompt' => 'Select Faculty',
'onchange' => '$.post("' . Yii::$app->urlManager->createUrl('/departments/lists?id=') . '"+$(this).val(), function(data) {
$("select#registrations-department_id").html (data);
});'
]
);
?>
<?=
$form->field($model, 'department_id')->dropDownList(
ArrayHelper::map(Departments::find()->asArray()->all(), 'department_id', 'department_name'), [
'id' => 'registrations-department_id',
'prompt' => 'Select Department',
'onchange' => '$.post("' . Yii::$app->urlManager->createUrl('/courses/lists?id=') . '"+$(this).val(), function(data) {
$("select#registrations-course_id").html (data);
});'
]);
?>
<?=
$form->field($model, 'course_id')->dropDownList(
ArrayHelper::map(Courses::find()->asArray()->all(), 'course_id', 'course_name'), [
'id' => 'registrations-course_id',
'prompt' => 'Select Course',
'onchange' => '$.post("(selected:)."+$(this).val(), function(data){
$("#registrations-courses").append(data)
});'
]);
?>
<!-- <?//= $form->field($model, 'courses')->checkBoxList([]) ?> -->
<?=$form->field($model, 'courses') ?>
<?=$form->field($model, 'comment') ?>
<?=$form->field($model, 'status') ?>
<?=$form->field($model, 'created_at') ?>
<?=$form->field($model, 'updated_at') ?>
<div class="form-group">
<?=Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
EDIT
this is my controller how do I save the courses in the database in the same column?
public function actionCreate()
{
$model = new Registrations();
if ($model->load(Yii::$app->request->post())) {
if ($model->validate()) {
// form inputs are valid, do something here
$model->student_id = Yii::$app->user->identity->id;
$model->faculty_id = 1 ;
$model->department_id = null ;
$model->course_id = 1;
$model->save();
return $this->redirect('../site/profile');
}
}
return $this->render('create', [
'model' => $model,
]);
}
You can use the checkBoxList() to create the list of checkboxes based on the courses list.
Change your course_id field to the following
$form->field($model, 'course_id')->checkboxList(yii\helpers\ArrayHelper::map(Courses::find()->asArray()->all(), 'course_id', 'course_name'), [
'inline' => true,
'unselect'=>null,
'item' => function($index, $label, $name, $checked, $value){
$checked = $checked ? 'checked' : '';
return "<input type='checkbox' class='my-courses' name='{$name}' value='{$value}' {$checked} data-label='{$label}'> <label>{$label}</label>";
}]);
add an id attribute to your courses field like below
$form->field($model, 'courses', ['inputOptions' => ['id' => 'courses']]);
and then add this javascript code to the top of your page
$js = <<< JS
$(".my-courses").on('click',function(e){
let course_name=$(this).data('label');
let course_field=$("#courses");
if($(this).is(":checked")){
$("#courses").val()==''?course_field.val(course_name):course_field.val(course_field.val()+', '+ course_name);
}else{
let regex=new RegExp(',{0,1}\\\s{0,1}('+course_name+')','g');
course_field.val(course_field.val().replace(regex,''));
}
})
JS;
$this->registerJs($js, \yii\web\View::POS_READY);
Now if you select the checkbox the name of the course would be copied to the input field and when you submit your form you can get the fields in your $_POST array under your specific model index like below.
[course_id] => Array
(
[0] => 1
[1] => 2
)
[courses] => asdas, shugal, spoon
You can verify by adding a print_r(Yii::$app->request->post()) in your controller action inside the check
if($model->load(Yii::$app->request->post())){
print_r(Yii::$app->request->post());
You can iterate on the course_id to save all of the course_id that were selected as checkboxes.

Yii2 pjax.reload not working for gridview records update

I have developed rows per page functionality for grid-view. With a Drop-down having options like 5,10,25,50,100. On-change any of the drop-down option I need to show selected number of rows for grid-view. For That I have created a Pjax container having my grid-view like :
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
$this->title = 'Test Cards';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="row">
<div class="test-card-index">
<?= $this->render('_search', [ 'model' => $searchModel ]) ?>
</div>
</div>
<?php Pjax::begin(['id' => 'test_grid_pjax', 'enablePushState' => false, 'timeout' => 1000000]); ?>
<div class="row">
<?= GridView::widget([
'dataProvider' => $dataProvider,
'class' => 'table table-bordered responsive',
'id' => 'test_grid',
'summary' => "<div class='summary'><label>Showing {begin} - {end} of {totalCount} items.</label></div> <div class='col-sm-6 pageDropdown'> <label>Records per page</label> ".Html::dropDownList('pageSize', (int) Yii::$app->session->get('pageSize', Yii::$app->params['defaultPageSize']), Yii::$app->params['rowPerPage'], ['id' => 'pageSize', 'class' => 'form-control', 'onchange' => 'return reloadGrid("test_grid_pjax",this.value)']) . "</div>",
'layout' => '{summary}{items}<div class="pager">{pager}</div>',
'options' => ['class' => 'main-grid grid-view full-table'],
'columns' => [
'cc_amount',
'cc_number',
'cc_type',
'cc_status'
],
]);
?>
</div>
<?php Pjax::end(); ?>
_search.php looks like :
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<div class="test-card-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
'options' => ['data-pjax' => true , 'class'=>'search_form form-horizontal' ]
]); ?>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<?= Html::activeLabel($model, 'cc_number',['class'=>'control-label col-sm-5']); ?>
<div class="col-sm-6">
<?= Html::activeTextInput($model, 'cc_number', ['class'=>'form-control col-sm-5','autofocus'=>true]); ?>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<?= Html::activeLabel($model, 'cc_type',['class'=>'control-label col-sm-5']); ?>
<div class="col-sm-6">
<?= Html::activeDropDownList($model, 'cc_type',[ "RESTRICTED" => Yii::t('app','RESTRICTED'), "UNRESTRICTED" => Yii::t('app','UNRESTRICTED')],['prompt' => Yii::t('app','All Types'), 'class'=>'form-control col-sm-5']); ?>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-5"></div>
<div class="col-md-3">
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-blue']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-primary','id'=>'resetButton','onclick'=>"location.href = '".Yii::$app->urlManager->createUrl('testcard/index')."';"]) ?>
</div>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
action in Controller looks like:
public function actionIndex()
{
if (Yii::$app->request->get('pageSize')) {
Yii::$app->session->set('pageSize', (int) Yii::$app->request->get('pageSize'));
}
// to set the selected page number of the grid
if (Yii::$app->request->get('page')) {
Yii::$app->session->set('page',(int)Yii::$app->request->get('page'));
} else {
Yii::$app->session->set('page',1);
}
$searchModel = new TestCardSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
function reloadGrid() is like:
<script type='text/javascript'>
function reloadGrid(id, value, url) {
$.pjax.reload({
container: "#" + id,
data: $('#search_form').serialize() + "&pageSize=" + value,
url: url,
push: false,
replace: false,
timeout: 1000000
});
}
</script>
On Searching thru any of the fields its reloads entire page and also sets search parameters in url.
Another problem is that on changing 'pageSize' dropdown it works fine for first time only, on every other attempts it shows error in console like:
Uncaught TypeError: Cannot read property 'reload' of undefined
at reloadGrid (index:53)
at HTMLSelectElement.onchange (index:1)
Is it a problem of JS conflicts?
I have tried many solutions by googling it, but not get it worked.
I ran into a similar issue that pjax was not parsing all the search fields in a grid filter. My solution/workaround/hack was to trigger a change event of a grid filter field, instead of calling pjax reload directly.
$('.date-range-filter').trigger('change'); // this works
/* // this didn't parse all the values from my form
$.pjax.reload({
container: "#grid-pjax"
});
*/
It has to do with the way gridView collects the form values for submission. It actually builds a new dummy form for the grid column filters because there is no actual form for the header filters of gridview
In your case you should also inspect the source and make sure the form is id'd correctly
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
'id'=> 'myFormId' // <---- try giving the form an id
'options' => ['data-pjax' => true , 'class'=>'search_form form-horizontal' ]
]); ?>
You can also try using the pjax widget form selector attribute-
instead of pjax begin and end. This will let pjax get all the input fields in that form automatically.
<?php
Pjax::widget([
'id' => 'search-form',
'enablePushState' => false,
'enableReplaceState' => false,
'formSelector' => '#myFormId', // <-- the form to submit with pjax
// 'submitEvent' => 'change', /// whatever you want
]);
?>

Retrieve data from modal without refreshing

I have an h4 tag and a button. The button opens a modal with a GridView whose action column contains a button in order to select the row.
What I need the row button to do is closing the modal and populate the h4 tag with "Row 3 was selected", for instance. But I don't want the page to be reladed.
This is the parent page tag and button:
<h4>*</h4>
<?
echo Html::button('Explotación', [
'value' => Url::to('/explotaciones/seleccionar'),
'class' => 'btn btn-primary',
'id' => 'modalButton'
]);
Modal::begin([
'header' => 'Seleccionar Explotación',
'id' => 'modal',
'size' => 'modal-md'
]);
echo "<div id= 'modalContent'></div>";
Modal::end();
?>
The action column in the modal:
[
'class' => 'yii\grid\ActionColumn',
'template' => '{seleccionado}',
'buttons' => [
'seleccionado' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-chevron-right"></span>', '#', [
'id' => 'seleccionado_' . $model->exp_id,
'class' => 'seleccionado',
'data-fila' => $model->exp_id
]);
}
]
]
Registering the javascript in the modal:
<?
$assets_js = Yii::$app->assetManager->publish(__DIR__ . '/js');
$this->registerJsFile($assets_js[1] . '/seleccion.js', [
'depends' => [
'app\assets\AppAsset'
]
]);
?>
And the javascript itself:
(function($){
$(document).ready(function() {
$('.seleccionado').click(function(evento) {
var value = 'HELLO';
alert(value);
value = $(this).data("fila");
alert(value);
$('h4').html(value);
$('#modal').modal('hide');
});
});
})(jQuery);
The code prints the HELLO alert but it does not print the second one nor poupulates the h4 tag nor closes the modal.
Which is the right way to make this work?
Erasing the cache in order to reload javascript changes correctly did the trick. Thanks anyway.

X editable - get dropdown option from mysql

I have a list of packages in my database. User need to select what package he wants to use. I want to use the xeditable dropdown bootsrap but the list isn't showing. Always "error when loading list".
I have an example in package.php
function get_package(){
$data = Array (
array('value' => 1, 'text' => 'package1'),
array('value' => 2, 'text' => 'package2'),
array('value' => 3, 'text' => 'package3')
);
echo json_encode($data);
}
And below is my js file.
$('#kitname').editable({
value:1,
source: 'package.php'
});
And my html file.
<a href="#"
id="kitname"
data-type="select"
data-name="kitname"
data-pk="1"
data-value="5"
data-original-title="Select Package"
">
Select Package
</a>
I need this week some time for the same problem, but the solution is very simple. ;) The array contains only: value => text:
function get_package(){
$data = Array (
array('1' => 'package1'),
array('2' => 'package2'),
array('3' => 'package3')
);
echo json_encode($data);
}

how to unhidden field base on the field validation in yii2

i have some field that set to hidden and i want to unhidden the field based on the other field validation. how can i do this using jquery??
here is my code:
<?php $form = ActiveForm::begin([
'id' => 'assign-form',
'enableAjaxValidation' => true,
]); ?>
<?= $form->field($volunteeringin, 'acId', [
'template' => '{label} <div class="row"><div class="col-md-5">{input}{error}{hint}</div></div>',
])->dropDownList($model->getActivitySearch(),['prompt'=>'בחר פעילות לשיבוץ המתנדב'])->label('פעילויות לשיבוץ')?>
<?= $form->field($volunteeringin, 'passedTraining')->radioList([0=>'לא',1=>'כן'] ,['separator' => '</br>','class'=>'hidden','id'=>'demo'])->label('האם המתנדב עבר הכשרה?'); ?>
<div class="form-group">
<?= Html::submitButton( 'שבץ מתנדב' ,['class' => 'btn btn-success' ]) ?>
</div>
<?php ActiveForm::end(); ?>
i want to set the field "passedTraining" to unhidden base on the the above field validation.
i try to use this function:
$('#fieldID').on('afterValidateAttribute', function(event, attribute, messages) {
if(messages.length == 0){
$('#demo').removeClass('hidden');
}
});
thanks
eli
I tested your code, and you have just a small error:
<?php $form = ActiveForm::begin([
'id' => 'assign-form',
'enableAjaxValidation' => true,
'enableClientValidation' => true, // enable this!
]); ?>
Hope this helps!

Categories