yiibooster wizard validation - javascript

I have done a yiibooster wizard form, everything works perfectly BUT i want to force the customer to click in a TbExtendedGridView before he can do the next step.
In the form there are 2 TbExtendedGridView and 2 date fields.
Here is some code of the form:
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'zf-contratos-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
'htmlOptions'=>array('class'=>'well'),
'action' => array( '/ZfContratos/create' ),
)); ?>
<div id="wizard-bar" class="progress progress-striped active">
<div class="bar"></div>
</div>
<?php $this->widget(
'bootstrap.widgets.TbWizard',
array(
'type' => 'tabs', // 'tabs' or 'pills'
'pagerContent' => '<div style="float:right">
<input type="button" class="btn button-next" name="next" value="Siguiente" />
</div>
<div style="float:left">
<input type="button" class="btn button-previous" name="previous" value="AtrĂ¡s" />
</div>
<br /><br />',
'options' => array(
'nextSelector' => '.button-next',
'previousSelector' => '.button-previous',
'onTabShow' => 'js:function(tab, navigation, index) {
var $total = navigation.find("li").length;
var $current = index+1;
var $percent = ($current/$total) * 100;
$("#wizard-bar > .bar").css({width:$percent+"%"});
}',
'onTabClick' => 'js:function(tab, navigation, index) {alert("Tab Click Disabled");return false;}',
),
'tabs' => array(
array(
'label' => 'Arrendatarios',
'content' => $this->renderPartial('//ZfContratos/_form_arrendatarios', array('model' => $model, 'form' => $form), true),
'active' => true
),
array('label' => 'Inmuebles', 'content' => $this->renderPartial('//ZfContratos/_form_inmuebles', array('model' => $model, 'form' => $form), true)),
array('label' => 'Fecha', 'content' => $this->renderPartial('//ZfContratos/_form_contratos', array('model' => $model, 'form' => $form), true)),
),
)
); ?>
<?php $this->endWidget(); ?>
The procedure would be, first step with "next" disable and when the customer clik on a row of the TbExtendedGridView "next" will be available and he can click on "next" to the next step.
Thank you so much.
CODE TESTED WORKING:
$cs = Yii::app()->getClientScript();
$cs->registerScript('hello', "
$(window).load(function()
{
alert('hello');
$('#next').attr('disabled',true);
});");
$cs->registerScript('button',"
$('#arrendatario').click(function()
{
$('#next').attr('disabled',false);
});");

You can do this in Jquery. First you have to set Id of TbExtendedGridView. Next Button contains class next Then you do like this
<script type="text/javascript">
window.onload=function(){
$('.next').attr('disabled',true);
}
$(document).ready(
function()
{
$('.grid-view').click(function()
{
$('.next').attr('disabled',false);
});
}
);
</script>
I have used class as selector but u can use use ID as selector as "#selector". You can also use jquery on child elements of grid-view. Above is just an example.
Here is some info about jquery selectors
http://www.w3schools.com/jquery/jquery_ref_selectors.asp
EDIT:
try
<?php $cs = Yii::app()->getClientScript();
$cs->registerScript('hello', "
$(window).load(function()
{
alert('hello');
}
)");
?>
If this works then copy the whole code in this script.

Related

I'm using YII2, I'm displaying a list of inactive users. I'm using the checkbox to select the user. I'm going to send an email to the user I tagged

$user
id
name
001
user 1
002
User 2
<ul>
<?php foreach($user as $user( { ?>
<input class="is-selected" type="checkbox" value="<?= $value->user->id ?>" />
<?php } ?>
</ul>
<button type="submit" class="btn is-primary">Send Reminder</button>
I'm using YII2, I'm displaying a list of inactive users. I'm using the checkbox to select the user. I'm going to send an email to the user I tagged.
how can i get id value from that checkbox and send data to controller?
I try to use javascript/jquery but i can't solved yet, i need some help from you guys
The above screenshot and your implementation is like you are talking 2 different things.
You would just be required a Grid View with CheckboxColumn
<?php
use yii\bootstrap\ActiveForm;
use yii\grid\GridView;
use yii\helpers\Html;
$form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
'id' => 'user_form',
'options' => ['class' => 'lfp-listing']
]);
echo Html::submitButton('Send Reminder', ['class' => 'btn is-primary', 'name' => 'action', 'value' => 'send_reminder']);
echo GridView::widget([
'dataProvider' => $dataprovider,
'columns' => [
'id',
'name',
'email',
[
'class' => 'yii\grid\CheckboxColumn',
'checkboxOptions' =>
function ($model) {
return ['value' => $model->id, 'class' => '', 'id' => 'checkbox'];
}
],
]
]);
ActiveForm::end();
Considering your Action is actionIndex()
public function actionIndex()
{
if (isset($_REQUEST['action']) && isset($_REQUEST['selection']) && 'send_reminder' == $_REQUEST['action'] ) {
foreach ($_REQUEST['selection'] as $userIds) {
//write down the email code here....
}
}

Display WordPress search results based on the selected Sub-Category

I'm trying to create a search using dropdowns in WordPress.
I've got two dropdowns, 1 - Parent Category and 1 - Sub-category.
The Sub-category will show automatically based on the selected Parent category.
My goal is to have the 2 dropdowns with a submit button and have it act as a search, displaying the selected sub-category's posts on the results page.
I've got this far using research but I'm completely lost and struggling as you can see.
Below is my functions.php code used for the search:
// FUNCTIONS.PHP
// Drop-down Ajax call
add_action('wp_ajax_my_special_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_special_action', 'my_action_callback');
function my_action_callback() {
if(isset($_POST['main_catid'])) {
$categories = get_categories('child_of='.$_POST['main_catid'].'&hide_empty=0');
foreach ($categories as $cat) {
$option .= '<option value="'.$cat->term_id.'">';
$option .= $cat->cat_name;
$option .= ' ('.$cat->category_count.')';
$option .= '</option>';
}
echo '<option value="-1" selected="selected">Search...</option>'.$option;
die();
} // end if
}
// Define search for sub-category
function search_filter( $query ) {
// only modify your custom search query.
if ( $query->is_search && $_post['my_search'] == "c_search") {
$args = array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => array( $_post['main_cat']),
'operator' => 'IN'
),
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => array( $_post['sub_cat']),
'operator' => 'IN'
)
);
$query->set( 'tax_query', $args);
}
return $query;
}
// The hook needed to search_filter
add_filter( 'the_search_query','search_filter');
This is the HTML & JS code used for the form and Ajax call for the sub-categories:
<!-- BODY HTML CODE -->
<div id="content">
<!-- Search form-->
<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
<div>
<input type="text" value="<?php the_search_query(); ?>" name="s" id="s" />
<?php
wp_dropdown_categories('show_count=0&selected=-1&hierarchical=1&depth=1&hide_empty=0&exclude=1&show_option_none=Main Categories&name=main_cat');
?>
<select name="sub_cat" id="sub_cat" enabled="disabled"></select>
<input type="hidden" id="my_search" name="my_search" value="c_search" />
<input type="submit" id="searchsubmit" value="search" />
</div>
</form>
<!-- Dropdown Ajax call script -->
<script type="text/javascript">
jQuery(function() {
jQuery('#main_cat').change(function() {
var $mainCat = jQuery('#main_cat').val();
// call ajax
jQuery("#sub_cat").empty();
jQuery.ajax({
url: "wp-admin/admin-ajax.php",
type: 'POST',
data: 'action=my_special_action&main_catid=' + $mainCat,
success: function(results) {
// alert(results);
jQuery("#sub_cat").removeAttr("disabled");
jQuery("#sub_cat").append(results);
}
});
});
});
</script>
</div>
the_search_query filter is not for that purpose. Use pre_get_posts filter instead.
Try this code:
// Define search for sub-category
function search_filter( $query ) {
// only modify your custom search query.
if ( $query->is_search && !is_admin() && $_post['my_search'] == "c_search" ) {
$args = array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => array( $_post['main_cat']),
'operator' => 'IN'
),
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => array( $_post['sub_cat']),
'operator' => 'IN'
)
);
$query->set( 'tax_query', $args);
}
return $query;
}
add_filter( 'pre_get_posts', 'search_filter' );

Yii2 - yii\grid\CheckboxColumn - Bulk Update and insert selected rows into another table

I have a table with these fields:
aca_class_subjects:
class_subject_id, class_subject_subject_id,
class_subject_class_group_id, class_subject_class_id
class_subject_id is the Primary Key and it is auto_increment.
class_subject_class_id and class_subject_class_group_id form a dependent dropdownlist.
class_subject_subject_id is from a table called aca_subjects and it will form the checkbox.
Controller: AcaClassSubjectsController
public function actionCreate()
{
$model = new AcaClassSubjects();
$searchModel = new AcaSubjectsSearch();
$searchModel->is_status = 0 ;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('create', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model'=> $model,
]);
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->class_subject_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
Model: AcaClassSubjects
public function attributeLabels()
{
return [
'class_subject_id' => Yii::t('aca', 'ID'),
'class_subject_subject_id' => Yii::t('aca', 'Subject'),
'class_subject_class_id' => Yii::t('aca', 'Class'),
'class_subject_class_group_id' => Yii::t('aca', 'Class Group'),
];
}
AcaSubjectsSearch
public function search($params)
{
$query = AcaSubjects::find()->where(['<>', 'is_status', 2]);
$dataProvider = new ActiveDataProvider([
'query' => $query, 'sort'=> ['defaultOrder' => ['subject_id'=>SORT_DESC]],
'pagination' => [ 'pageSize' => 5 ]
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'subject_id' => $this->subject_id,
]);
$query->andFilterWhere(['like', 'subject_name', $this->subject_name])
->andFilterWhere(['like', 'subject_code', $this->subject_code]);
return $dataProvider;
}
View
<div class="col-xs-12" style="padding-top: 10px;">
<div class="box">
<?php $form = ActiveForm::begin([
'id' => 'academic-level-form',
'enableAjaxValidation' => false,
'fieldConfig' => [
'template' => "{label}{input}{error}",
],
]); ?>
<div class="col-xs-12 col-lg-12 no-padding">
<div class="col-xs-12 col-sm-6 col-lg-6">
<?= $form->field($model, 'class_subject_class_group_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassGroups::find()->where(['is_status' => 0])->all(),'class_group_id','class_group_name'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Class Group ---',
'onchange'=>'
$.get( "'.Url::toRoute('dependent/getclassmaster').'", { id: $(this).val() } )
.done(function( data ) {
$( "#'.Html::getInputId($model, 'class_subject_class_id').'" ).html( data );
}
);'
],
// 'disabled'=>'true',
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
<div class="col-xs-12 col-sm-6 col-lg-6">
<?= $form->field($model, 'class_subject_class_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassMaster::findAll(['class_id' => $model->class_subject_class_id]),'class_id','class_name'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Class ---'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
</div>
<div class="box-body table-responsive">
<h4><strong><u>Select Subject(s)</u></strong></h4>
<div class="course-master-index">
<?= GridView::widget([
'id'=>'grid',
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
[
'class' => 'yii\grid\CheckboxColumn',
'header' => Html::checkBox('selection_all', false, [
'class' => 'select-on-check-all',
'label' => 'All',
]),
'visible'=> true,
'contentOptions' =>['style' => 'vertical-align:middle;width:30px'],
'checkboxOptions' => function($model, $key, $index, $column) {
return ['value' => $model->subject_id];
}
],
['class' => 'yii\grid\SerialColumn'],
// 'id',
'subject_name',
],
]); ?>
<?= Html::input('hidden','keylists',$value='', $options=['id'=>'keylist']) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' =>'btn btn-success btn-block btn-lg','id'=>"button123"]) ?>
</div>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
My questions are
After selecting particular rows (subject_id) using checkboxes from Table aca_subjects, and also select the dropdownlist as shown in the diagram
How do I insert them (class_subject_subject_id,class_subject_class_id, class_subject_class_group_id) to the Table aca_class_subjects?
How do I update them (class_subject_subject_id,class_subject_class_id, class_subject_class_group_id) to the Table aca_class_subjects?
How do I display a dialogue box when nothing is selected?
Note: class_subject_subject_id (checkbox in gridview),class_subject_class_id (dropdownlist), class_subject_class_group_id (dropdownlist)
When I clicked on submit, nothing goes to the database
Well, the question is a bit broad as you haven't shown any code related to solving your problem specifically so my wild guess is that you have a basic showstopper for collecting the class_subject_subject_id from the gridview. so i will suggest the javascript part in my answer where it submits the form with ajax.
But before i suggest you a solution you have a basic problem that you are wrapping the gridview with the form you are using to insert the subjects in the aca_class_subjects
Why?
Because if you wrap the Gridview with a form along with the gridview filters the GridView does not create its own hidden form that it uses for submitting the filter inputs for search in the GridView, and hence when you will try search by typing in the GridView filter input it would submit it to the action specified in your outer form that can have a different action like in your case.
So if you still want to use the ActiveForm do not wrap the Gridview inside the form keep it separate, and close it before you call the GridView::widget() but you have the button placed in the end of the Gridview and you dont want to change the design so change the code for the button from Html::submitButton() to Html::button() and keep it outside the ActiveForm that you have created. You can submit the form with javascript.
So your view code should look like below
<div class="col-xs-12" style="padding-top: 10px;">
<div class="box">
<?php
$form = ActiveForm::begin([
'id' => 'academic-level-form',
'enableAjaxValidation' => false,
'action'=>\yii\helpers\Url::to(['assign-subjects'])
'fieldConfig' => [
'template' => "{label}{input}{error}",
],
]);
?>
<div class="col-xs-12 col-lg-12 no-padding">
<div class="col-xs-12 col-sm-6 col-lg-6">
<?=
$form->field($model, 'class_subject_class_group_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassGroups::find()->where(['is_status' => 0])->all(), 'class_group_id', 'class_group_name'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Class Group ---',
'onchange' => '
$.get( "' . Url::toRoute('dependent/getclassmaster') . '", { id: $(this).val() } )
.done(function( data ) {
$( "#' . Html::getInputId($model, 'class_subject_class_id') . '" ).html( data );
}
);'
],
// 'disabled'=>'true',
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
<div class="col-xs-12 col-sm-6 col-lg-6">
<?=
$form->field($model, 'class_subject_class_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassMaster::findAll(['class_id' => $model->class_subject_class_id]), 'class_id', 'class_name'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Class ---'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
</div>
<?=Html::input('hidden', 'keylists', $value = '', $options = ['id' => 'keylist']) ?>
<?php ActiveForm::end(); ?>
<div class="box-body table-responsive">
<h4><strong><u>Select Subject(s)</u></strong></h4>
<div class="course-master-index">
<?=
GridView::widget([
'id' => 'grid',
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
[
'class' => 'yii\grid\CheckboxColumn',
'header' => Html::checkBox('selection_all', false, [
'class' => 'select-on-check-all',
'label' => 'All',
]),
'visible' => true,
'contentOptions' => ['style' => 'vertical-align:middle;width:30px'],
'checkboxOptions' => function($model, $key, $index, $column){
return ['value' => $model->subject_id];
}
],
['class' => 'yii\grid\SerialColumn'],
// 'id',
'subject_name',
],
]);
?>
<div class="form-group">
<?=Html::button('Submit', ['class' => 'btn btn-success btn-block btn-lg', 'id' => "button123"]) ?>
</div>
</div>
</div>
</div>
</div>
Now about the saving of the records.
You can get all the selected subjects that are in the grid view by using the following javascript code where you select all the checked checkboxes which have the name selection[]. Add the below code on top of your view
$reflect = new ReflectionClass($model);
$subjectId = $reflect->getShortName() . '[class_subject_subject_id][]';
$js = <<<JS
$("#button123").on('click',function(e){
e.preventDefault();
$("#academic-level-form").yiiActiveForm('submitForm');
});
$("#academic-level-form").on('beforeSubmit',function(e){
e.preventDefault();
// yii.getCsrfParam(),yii.getCsrfToken(),
let subjects=$("input[name='selection[]']:checked");
let subjectsSelected=subjects.length;
if(!subjectsSelected){
alert('select some subjects first');
}else{
let data=$(this).serializeArray();
$.each(subjects,function(index,elem){
data.push({name:"$subjectId",value:$(elem).val()})
});
let url=$(this).attr('action');
$.ajax({
url:url,
data:data,
type:'POST',
}).done(function(data){
alert(data);
}).fail(function(jqxhr,text,error){
alert(error);
});
}
return false;
});
JS;
$this->registerJs($js, \yii\web\View::POS_READY);
Now if you have print_r(Yii::$app->request->post()) inside the actionAssignSubjects() in your controller where the form is submitting you can see the output of the posted variables and your subjects will be under the same model array that you are using for populating the dropdowns with the name class_subject_subject_id and all the selected subjects would be under this array. You can loop over them to save to your desired model.
I leave the rest of the work on you to do by your self and if you run into any problems you should post a separate question with the targetted code.

Disable button on click but still process form

I want to disable my register button on click to prevent spam, but I don't want to prevent the form the button submits from submitting.
I'm able to disable the button on click, but can't figure out why the form still won't submit...
button:
<?= form_open("course/registerCourse", "method='post'") ?>
<input type="hidden" name="session" value="<?= $session["id"] ?>">
<button type="submit" class="btn-sm btn btn-success register">REGISTER</button>
<?= form_close() ?>
jQuery:
$('.register').on('click',function() {
$(this).prop("disabled",true);
$("form").submit();
});
register function:
public function registerCourse()
{
$user = $this->users_model->userAccountTP();
$appParticipant = $user[0]["id"];
$author_id = $this->session->userdata("ci_user_id");
$appSession = $this->input->post('session');
$this->ci_channel_entry_model->save_multiple(array(
"channel_id" => 11,
"title" => date("Y-m-d h:i:s"),
"author_id" => $author_id,
"status_id" => 7,
"date" => date("Y-m-d h:i:s"),
"data" => array(
array(
// application-session
"field_id" => 28,
"content" => $appSession
),
array(
// application-participant
"field_id" => 29,
"content" => $appParticipant
)
),
"hook" => FALSE
));
redirect($this->agent->referrer());
}
I think you might have a typo, because I dont see where you are declaring $form, so maybe this helps:
$('.register').on('click',function() {
$(this).prop("disabled",true);
$("form").submit();
});
Ended up reworking my form to align with this answer and everything worked:
https://stackoverflow.com/a/5691065/4141833

get all IDs of selected checkbox in Yii using javascript

I am trying to get the IDs of all the selected check boxes in yii using JAVASCRIPT. Now i am able to get only the first element ID. Can anyone please suggest the correct code to get all the check box ID.
My View:
<input type="button" value="Multiple Host Date Entries" onclick="act();" />
<div id="grid"></div>
<?php
//zii.widgets.grid.CGridView bootstrap.widgets.TbExtendedGridView
$obj=$this->widget('bootstrap.widgets.TbExtendedGridView', array(
'id'=>'host_grid',
'dataProvider'=>$dataProvider,
'type' => 'striped bordered',
//'filter' => $model,
//'type' => 'striped bordered condensed',
//'summaryText' => false,
////'afterAjaxUpdate'=>'\'changeTRColor()\'',
//'itemView'=>'_view',
'columns'=>array(
array(
'id' => 'selectedIds',
'class' => 'CCheckBoxColumn',
'selectableRows'=>2,
'value' => '$data->host_id',
'checkBoxHtmlOptions' => array('name' => 'idList[]'),
),
array( // display 'create_time' using an expression
'name'=>'host_name',
'value'=>'$data->host_name',
),
array(
'name'=>'host_serviceid',
'value'=>'$data->host_serviceid',
),
array(
'name'=>'status',
'value'=>'$data->status',
),
array(
'class'=>'CButtonColumn',
'template'=>'{edit_date}{update}{delete}',
'htmlOptions'=>array('width'=>'95px'),
'buttons' => array(
'update'=> array(
'label' => 'Update',
'imageUrl' => Yii::app()->baseUrl.'/images/icons/a.png',
),
'delete'=> array(
'label' => 'Delete',
'imageUrl' => Yii::app()->baseUrl.'/images/icons/d.png',
),
'edit_date' => array( //the name {reply} must be same
'label' => 'Add Date', // text label of the button
'url' => 'Yii::app()->createAbsoluteUrl("NimsoftHostsDetails/View", array("id"=>$data->host_id))', //Your URL According to your wish
'imageUrl' => Yii::app()->baseUrl.'/images/icons/m.png', // image URL of the button. If not set or false, a text link is used, The image must be 16X16 pixels
),
),)
),
))
;
?>
I must select some check boxes and click on multiple host date entries button to go to the specific controller.
My JavaScript:
function act()
{
var idList=$("input[type=checkbox]:checked").serializeArray();
var jsonStr = JSON.stringify(idList);
/* Object.keys(idList).forEach(function(key) {
console.log(key, idList[key]);
alert(idList[key]);
});*/
var a=$("input[type=checkbox]:checked").val();
alert(a);
if(idList!="")
{
if(confirm("Add Dates for multiple hosts?"))
{
var url='<?php echo $this->createUrl('Nimsoft/Date_all',array('idList'=>'val_idList')); ?>';
url=url.replace('val_idList',jsonStr);
//url=url.replace('val_idList',json_encode(idList));
//alert(url);
window.open(url);
/*$.post('Date_all',idList,function(response)
{
$.fn.yiiGridView.update("host_grid");
});*/
}
}
else
{
alert("Please Select atleast one host");
}
}
I need to pass the IDs to NIMSOFT controller so that I can have a for loop to process each one of those.
you can retrieve the checked column in client side (javasctipt):
var idArray = $(gridID).yiiGridView('getChecked', columnID);
// or
$.fn.yiiGridView.getSelection(gridID);
For all checked row ids we use this
var id = $.fn.yiiGridView.getChecked("your-grid-id", "selectedIds"); // array of seleted id's from grid

Categories

Resources