Related
$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....
}
}
I just updated my JQuery.js to version 3.6.0 and all of a sudden some of my functions stopped working, eg my modal close buttons don't work anymore. I am using Yii2 ver2.0.45. I was previously using JQuery 3.4.4 which was working very well. Any suggestions/solutions will be appreciated. Here is my modal code block.
<?php
Modal::begin([
'title' => '<h4></h4>',
'id' => 'modal',
'titleOptions' => [
'style' => 'background: rgba(0, 0, 0, 0.5)',
],
'closeButton' => [
'class' => 'btn btn-danger btn-xs pull-right',
],
'options' => [
'tabindex' => false // important for Select2 to work properly
],
'size' => 'modal-lg',
// keeps from closing modal with esc key or by clicking out of the modal
// user must click cancel or X to close
'clientOptions' => ['backdrop' => 'static', 'keyboard' => false],
]);
$contentDiv = "<div id='content'></div>";
echo $contentDiv;
Modal::end();
?>
I did a simple gridview table with filters on yii2, seems to be working great, but I noticed the javascript functions doesn't work after I apply any filter on the gridview table, i think its refreshing the whole page instead only refresh the table.
I did the $.pjax.reload method but it didn't work, this is how i applied the pjax reload method:
//inventariosearch-amb_id is the ID of one of my filterselects on the gridview
$("#inventariosearch-amb_id").on("pjax:end", function() {
$.pjax.reload({container:"#inventario_lista"}); //Reload GridView
});
Let me know if i applied wrong the method.
well, as I said I think the pjax is refreshing the whole page cause it changes my page title from this:
To this:
That's how I notice the changes and the javascript doesn't work properly anymore.
What can I do?.
My view index.php:
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\grid\GridView;
use yii\grid\ActionColumn;
use yii\widgets\Pjax;
use yii\bootstrap4\Modal;
use app\models\Ambiente;
use app\models\TipoServicio;
use app\models\Empresa;
/* #var $this yii\web\View */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->registerJsFile("#web/js/inventario.js",[
'depends' => [
\yii\web\JqueryAsset::className()
]
]);
$this->title = 'Servidores';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="inventario-index">
<?php $this->beginBlock('bloque_titulo'); ?>
<div class="page-title-icon">
<i class="fa fa-archive icon-gradient bg-arielle-smile">
</i>
</div>
<div>
<?= Html::encode($this->title) ?>
<div class="page-title-subheading">
Lista de servidores
</div>
</div>
<?php $this->endBlock(); ?>
<p>
<?= Html::a('<i class="fa fa-plus"></i> Añadir nuevo', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(['id'=>'inventario_lista','timeout'=> false,'clientOptions' => ['method' => 'POST','registerClientScript' => 'alert("lol")']]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $model,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'amb_id',
'value' => 'amb.amb_desc',
'filter' => Html::activeDropDownList($model, 'amb_id', ArrayHelper::map(Ambiente::find()->asArray()->all(), 'amb_id', 'amb_desc'), [
'class' => 'form-control',
'prompt' => '--- Seleccione ---'
])
],
'inv_plataforma',
'inv_host_computername',
[
'attribute' => 'tise_id',
'value' => 'tise.tise_desc',
'filter' => Html::activeDropDownList($model, 'tise_id',ArrayHelper::map(TipoServicio::find()->orderby(['tise_desc'=>SORT_ASC])->asArray()->all(), 'tise_id', 'tise_desc'), [
'class' => 'form-control',
'prompt' => '--- Seleccione ---'
])
],
[
'attribute' => 'emp_id',
'value' => 'emp.emp_desc',
'filter' => Html::activeDropDownList($model, 'emp_id',ArrayHelper::map(Empresa::find()->orderby(['emp_desc'=>SORT_ASC])->asArray()->all(), 'emp_id', 'emp_desc'), [
'class' => 'form-control',
'prompt' => '--- Seleccione ---'
])
],
//'inv_servicio',
//'inv_ip_admin',
//'inv_ip_servicio',
//'inv_ip_nfs',
//'sad_id',
//'usu_id_responsable_sistema',
//'usu_id_2doresponsable_sistema',
//'inv_modelo_servidor',
//'prov_id',
//'inv_serial_equipo',
//'inv_codigo_remedy',
//'inv_serial_dispositivo',
//'sop_id',
//'inv_version_so',
//'inv_alta_disponibilidad',
//'inv_ubicacion',
//'inv_ala',
//'inv_fila',
//'inv_rack',
//'inv_cpu_core',
//'inv_cpu_modelo',
//'inv_cpu_velocidad',
//'inv_gb_memoria',
//'hat_id',
//'inv_tipo_contrato_proveedor',
//'inv_responsable_funcional',
//'spa_id',
//'fv_id',
//'pr_id',
//'inv_observaciones',
//'inv_performance_review',
//'inv_performance_management',
//'inv_obsoleto',
//'inv_motivo_obsoleto',
//'inv_arbol',
//'inv_arbol_1er_nivel',
//'inv_fin_venta',
//'inv_fin_partes',
//'inv_fin_soporte',
//'inv_fecha_cons_obsoleto',
['class' => 'yii\grid\ActionColumn',
'buttons'=>[
'view'=>
function($url,$model,$key){
$btn = Html::button("<i class='fa fa-eye'></i>",[
'value'=>Yii::$app->urlManager->createUrl('inventario/view/'.$key),
'class'=>'serverview grid-action btn btn-info',
'title'=>'Ver datos del servidor',
'data-toggle'=> 'modal',
'data-target'=> '#modalviewserver',
]);
return $btn;
},
'update'=>function ($url,$model,$key) {
return Html::a('<i class="fa fa-edit"></i>', ['/inventario/update/'.$key], ['class'=>'btn btn-success grid-button']);
},
],
],
],
]); ?>
<?php Pjax::end(); ?>
</div>
<?php
Modal::begin([
'title' => '<h4>Ver servidor</h4>',
'id' => 'modalviewserver',
'size' => 'modal-lg',
]);
echo "<div id='viewservercontent'></div>";
Modal::end();
?>
My action controller:
public function actionIndex()
{
$model = new InventarioSearch();
$dataProvider = $model->search(Yii::$app->request->post());
return $this->render('index', [
'dataProvider' => $dataProvider,
'model' => $model
]);
}
And my JS (just in case):
$(document).ready(function ()
{
// $("#inventariosearch-amb_id").on("pjax:end", function() {
// $.pjax.reload({container:"#inventario_lista"}); //Reload GridView
// });
$('.serverview').click(function()
{
$('#modalviewserver').appendTo("body").modal('show')
.find('#viewservercontent')
.load($(this).attr('value'));
});
});
If you want your link to refresh whole page you have to remove your pjax.
Other way, try to set your javascript in pjax:success like this:
$(document).on('ready pjax:success', function(){
//your javascript here
$('.serverview').click(function()
{
$('#modalviewserver').appendTo("body").modal('show')
.find('#viewservercontent')
.load($(this).attr('value'));
});
})
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.
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.