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!
Related
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.
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?
I have dropDownList in Yii2 project
<?= $form->field($model, 'license', ['options' =>['onchange'=>'getSalutationValue()'] )->dropDownList(['y' => 'Yes', 'n' => 'No']) ?>
i want hide some block if user seleckted value 'n'
I tried this function
function getSalutationValue() {
var label = this.value;
if(label == 'n' ) {
document.getElementById('driver').style.display='none';
}}
What am i doing wrong? Please help me
You are not passing object of input field, so that you can use its value,
try this
<?= $form->field($model, 'license', ['options' =>['onchange'=>'getSalutationValue(this)'] )->dropDownList(['y' => 'Yes', 'n' => 'No']) ?>
in script
function getSalutationValue(obj) {
var label = obj.value;
if(label == 'n' ) {
document.getElementById('driver').style.display='none';
}}
Updated:
<?= $form->field($model, 'license')->dropDownList(['y' => 'Yes', 'n' => 'No'],['onchange'=>'getSalutationValue(this)']) ?>
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
]);
?>
On main page I've got a button which call bootstrap modal with activeform. On submit this form adds new row in my db. But I dont look a success message neither in this modal nor on the main page. Instead I get to page mysite.ru/category/create with white screen and text of dialog message on it ("Dialog contents here..."). How not to redirect user on other page? Just close modal and/or redirect on main page and show here flashmessage about successful adding row.
my button in views/site/index.php:
<?= Html::button(
'create',
['value' => Url::to(['category/create']),
'id' => 'modalButton'
]) ?>
<?php
Modal::begin([
'id' => 'modal'
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
my controller SiteController has:
public function actionIndex()
{
return $this->render('index');
}
CategoryController has
public function actionCreate()
{
$model = new Category;
if ($model->load(Yii::$app->request->post()) && Yii::$app->request->isAjax) {
$model->refresh();
Yii::$app->response->format = 'json';
return ActiveForm::validate($model);
} elseif ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->session->setFlash('contactFormSubmitted');
//$model->refresh();
$this->refresh();
Dialog::begin([
'clientOptions' => [
'modal' => true,
],
]);
echo 'Dialog contents here...';
Dialog::end();
//$this->redirect('category/create');
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
views/category/create.php:
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model app\models\Category */
$this->title = 'Create Category';
$this->params['breadcrumbs'][] = ['label' => 'Categories', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="category-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
and views/category/_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\jui\Dialog;
/* #var $this yii\web\View */
/* #var $model app\models\Category */
/* #var $form yii\widgets\ActiveForm */
?>
<?php
$this->registerJsFile(Yii::getAlias('/scripts/main.js'));
?>
<?php if (Yii::$app->session->hasFlash('contactFormSubmitted')): ?>
<div class="alert alert-success">
Thank you for contacting us. We will respond to you as soon as possible.
</div>
<?php endif; ?>
<div class="category-form">
<?php $form = ActiveForm::begin([
'id' => $model->formName(),
//'enableAjaxValidation'=>true,
'validateOnSubmit'=>true,
//'action' => '/site/index'
]); ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
scripts/main.js:
// listen click, open modal and .load content
$('#modalButton').click(function (){
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
// serialize form, render response and close modal
function submitForm($form) {
$.post(
$form.attr("action"), // serialize Yii2 form
$form.serialize()
)
.done(function(result) {
form.parent().replaceWith(result);
//$form.parent().html(result.message);
//$('#modal').modal('hide');
})
.fail(function() {
console.log("server error");
$form.replaceWith('<button class="newType">Fail</button>').fadeOut()
});
return false;
}
You have to prevent your form from being submited and use ajax.
$(your_form)
.on('beforeSubmit', function(event){
event.preventDefault();
submitForm($(your_form));
return false;
})
.on('submit', function(event){
event.preventDefault();
});