Edit:
I discovered that if i do a clean install, the modal works, and it's after adding hail812/yii2-adminlte3 that the modal system won't work anymore... but i don't find what create this,
original:
little question, does any of you use yii/boostrap5/modal and succeed to render ajax form in a modal ? Because my code used with the older bootstrap won't work.. and i don't find how the new yii/bootstrap5/modal works...
here is my code
<?php
yii\bootstrap5\Modal::begin([
'id' => 'modal',
'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' => TRUE]
]);
echo '<div id="modalContent"></div>';
yii\bootstrap5\Modal::end();
?>
<?php
$this->registerJs( <<< EOT_JS_CODE
$(function(){
// changed id to class
$('.modalButton').click(function (e){
e.preventDefault();
$.get($(this).attr('href'), function(data) {
$('#modal').modal('show').find('#modalContent').html(data)
});
document.getElementById('modalHeader').innerHTML = '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h4>' + $(this).attr('title') + '</h4>';
return false;
});
});
EOT_JS_CODE
);
?>
the link i use to open the modal:
<?= Html::a(Yii::t('app', 'Ajouter'), ['create-categorie'], ['class' => 'btn btn-success modalButton','title'=>'Nouvelle catégorie']) ?>
And my code in my controller
public function actionCreateCategorie()
{
$model = new Categorie();
if ($model->load(Yii::$app->request->post())) {
$model->created_at = strtotime('now');
$model->updated_at = strtotime('now');
if( $model->save()){
return 'success';
}else{
return 'error';
}
}
return $this->renderAjax('create-categorie', [
'model' => $model,
],false, true);
}
my console with a strange error i don't get
Related
I've success create modal form, but I can't submit it with ajax. Everytime i click submit button it not stay in the index page but instead show echo 1 from my Controller.
My controller
public function actionCreate()
{
$model = new Testing();
if ($model->load(Yii::$app->request->post())) {
if($model->save()){
echo 1;
}else{
echo 0;
}
}else{
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
My form
<div class="testing-form">
<?php $form = ActiveForm::begin(['id' => $model->formName()]); ?>
<?= $form->field($model, 'test')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$this->registerJS("
$('form#{$model->formName()}'.on('beforeSubmit', function(e)
{
var \$form = $(this);
$.post(
\$form.attr('action'),
\$form.serialize()
)
.done(function(result) {
if(result == 1)
{
$(\$form).trigger('reset');
$.pjax.reload({container:'#issuehrGrid'});
}else
{
$('#message').html(result.message);
}
}).fail(function()
{
console.log('server error');
})
return false;
});"
);
?>
My view
<div class="report">
<h3>HR Issues</h3>
<?= Html::a('<span class="glyphicon glyphicon-plus"></span> Add', ['create'], ['class' => 'btn btn-success modalButton']) ?>
<?php Pjax::begin(['id'=>'issuehrGrid']); ?>
<table class="table table-bordered table-hover">
<tbody>
<?php foreach ($dataProvider->models as $hr) {
?>
<tr>
<td><?=$hr->test;?></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php Pjax::end(); ?>
</div>
Please help me with this.
Thank you!
What I suspect is that it would be showing you the blank page with 1 displayed in it is because after the first submission your Pjax grid is reloaded via the statement
$.pjax.reload({container:'#issuehrGrid'});
and once reloaded your beforeSubmit event is not bound again to the form as the form Html is reloaded again and when you submit the form second time it just makes a simple form submit and displays the blank page with 1, you need to use the pjax:complete event for the pjax, so that one the grid is reloaded your script binds the beforeSubmit event to the form again.
Also, you have a syntax error in your script which should be fixed. Change your script to the following
<?php
$formName = $model->formName();
$js = <<<JS
$(document).on("ready pjax:complete",function(){
$('form#{$formName}').on('beforeSubmit', function(e){
var \$form = $(this);
$.post(
\$form.attr('action'),
\$form.serialize()
).done(function(result) {
if(result == 1)
{
$(\$form).trigger('reset');
$.pjax.reload({container:'#issuehrGrid'});
}else
{
$('#message').html(result.message);
}
}).fail(function()
{
console.log('server error');
})
return false;
});
});
JS;
$this->registerJS(
$js,
\yii\web\View::POS_READY
);
?>
UPDATE
and dont forget to change the controller action code and change the echo 1 to return 1 and echo 0 to return 0
In my Update form, I have two submitform 'Save', 'Save & Submit'. each of them will update particular field.
The submit button looks like -
<?= Html::submitButton('Save',['name'=>'submit', 'value' => 'tello','class' => 'btn btn-primary']) ?>
<?= Html::submitButton('Save & Submit',['name'=>'submit', 'value' => 'hello','class' => 'btn btn-success']) ?>
The best possible Controller Action I got so far is -
if(Yii::$app->request->post('submit')==='tello'){
var_dump("Save is clicked");
die();
}
elseif(Yii::$app->request->post('submit')==='hello'){
var_dump("Submit is clicked");
die();
}
The problem with this is that, I have to click the button twice to submit it. I learned that I have to change the button name to anything but submit. I tried changing it anything else, but it didn't work. It's negelecting the code and proceeds to the next set of code.
I have this two button in create form as well
form
<?= Html::submitButton('Save',['name'=>'Save', 'value' => 'Save','class' => 'btn btn-primary']) ?>
<?= Html::submitButton('Save & Submit',['name'=>'Submit', 'value' => 'Submit','class' => 'btn btn-success']) ?>
Controller action
if ($model->load(Yii::$app->request->post())&& isset($_POST['Save'])){
//do my stuff
}
elseif ($model->load(Yii::$app->request->post())&& isset($_POST['Submit'])){
//do my stuff
}
As asked by scaiseEdge Create Controller Action
public function actionCreatenewworkbasic()
{
$model = new Workpermit();
//$model->wp_validfrom = date('Y-m-d H:i:s');
//$model->wp_validto = date('Y-m-d H:i:s');
$model->wp_timeissued = date('Y-m-d H:i:s');
if ($model->load(Yii::$app->request->post()) && isset($_POST['Save'])) {
//get the instance of the uploaded file
//$jhaName = $model->wp_no;
$model->wp_status = 'Saved';
$timenow = date('-Y-m-d-H-i-s');
$model->jha = UploadedFile::getInstance($model,'jha');
if (!empty($model->jha)) {
$model->jha->saveAs('uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension);
//save the path in the db
$model->wp_jhaattach = 'uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension;
}
$model->jha = null;
$model->save(false);
return $this->redirect(['availablework']);
}
elseif ($model->load(Yii::$app->request->post())&& isset($_POST['Submit']))
{
//get the instance of the uploaded file
//$jhaName = $model->wp_no;
$model->wp_status = 'Submitted';
$timenow = date('-Y-m-d-H-i-s');
$model->jha = UploadedFile::getInstance($model,'jha');
if (!empty($model->jha)) {
$model->jha->saveAs('uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension);
//save the path in the db
$model->wp_jhaattach = 'uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension;
}
$model->jha = null;
$model->save(false);
return $this->redirect(['availablework']);
}
else{
return $this->renderAjax('createnewworkbasic', [
'model' => $model,
]);
}
}
Action Update
public function actionUpdatenewwork($id)
{
$anotherchecklistitems = Anotherclreq::find()->select('acl_clname')->where(['acl_wpno'=>$id])->column();
$anotherpermitlistitems = Anotherpermitreq::find()->select('apr_apname')->where(['apr_wpno'=>$id])->column();
$model = $this->findModel($id);
//we have a relation between workpermit and anotherchecklist named anotherchecklistrel
$modelsAnotherchecklist = $model->anotherchecklistrel;
$modelsAnotherpermitlist = $model->anotherpermitlistrel;
if(isset($_POST['Workpermit']['anotherchecklist'])){
$oldIDs = ArrayHelper::map($modelsAnotherchecklist, 'acl_id', 'acl_id');
$oldIDstring = implode(",", $oldIDs);
// print_r($oldIDstring);
// die();
foreach ($oldIDs as $id) {
Anotherclreq::findOne($id)->delete();
}
//die();
$anotherChecklist = $_POST['Workpermit']['anotherchecklist'];
foreach ($anotherChecklist as $value) {
$anotherclreq = new Anotherclreq();
$anotherclreq->acl_wpno = $model->wp_no;
$anotherclreq->acl_clname = $value;
$anotherclreq->save();
}
}
if(isset($_POST['Workpermit']['anotherpermittype'])){
$oldAPs = ArrayHelper::map($modelsAnotherpermitlist, 'apr_id', 'apr_id');
$oldAPstring = implode(",", $oldAPs);
// print_r($oldIDstring);
// die();
foreach ($oldAPs as $id) {
Anotherpermitreq::findOne($id)->delete();
}
$anotherPermit = $_POST['Workpermit']['anotherpermittype'];
foreach ($anotherPermit as $value) {
$anotherpermitreq = new Anotherpermitreq();
$anotherpermitreq->apr_wpno = $model->wp_no;
$anotherpermitreq->apr_apname = $value;
$anotherpermitreq->save();
}
}
if(Yii::$app->request->post('submit')==='tello'){
var_dump("Save is clicked");
die();
}
elseif(Yii::$app->request->post('submit')==='hello'){
var_dump("Submit is clicked");
die();
}
if ($model->load(Yii::$app->request->post())) {
//$model->wp_nwopcheckliststatus = 'Submitted';
$model->save();
return $this->redirect(['viewall', 'id' => $model->wp_no]);
}
return $this->render('updatenewwork', [
'model' => $model,
'anotherchecklistitems' => $anotherchecklistitems,
'anotherpermitlistitems' => $anotherpermitlistitems,
]);
}
In the create form it works good. But for the update form it doesn't. Please help.
Some Observation -
I've changed the buttons like below -
<?= Html::submitButton('Save',['id' => 'savename','name'=>'savename', 'value' => 'savename','class' => 'btn btn-primary']) ?>
<?= Html::submitButton('Save & Submit',['id' => 'submitname','name'=>'submitname', 'value' => 'submitname','class' => 'btn btn-success']) ?>
Now If I use the following code in Controller action, the form is submitting as it should -
if (Yii::$app->request->isPost) {
if ($model->load(Yii::$app->request->post())) {
$model->wp_nwopcheckliststatus = 'Saved';
$model->save();
return $this->redirect(['viewall', 'id' => $model->wp_no]);
}
}
But as soon as I change $model->load(Yii::$app->request->post()) to $model->load(Yii::$app->request->post('savename')) it stops working.
If I were you, I would create a hidden text field.
and instead of directly submitting the form, I would have attached an event listener.
meaning by javascript, add on click event on the buttons and change the value of hidden text field to anything - 0 - 1 or anything. and then submit the form.
for example:
<input type="hidden" name="pressed" id="pressed" />
<script>
$('#save').click(function(){
$('pressed').val("save");
});
$('#save-and-submit').click(function(){
$('pressed').val("submit");
});
</script>
then check in $_POST['pressed'];
I'm using the code below to open a modal window (modal_top10), and now I need to pass a parameter ($manager) to this modal. How do I pass this parameter? Via URL?
<div class="modal fade" id="myModaltop10" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
<script>
function top10(){
$.ajax({
type:'GET',
url:'index.php?r=/client/base/modal_top10',
success: function(data)
{
$('#myModaltop10').html(data);
$('#myModaltop10').modal();
}
});
}
</script>
first create _modelview file in view folder with following code. Let url of this page is http://example.com/model/show
<?php
echo $data;
?>
note: you must render using renderAjax() method for this view file in controller model
public function actionShow($data)
{
return $this->renderAjax('_modelview', [
'data' => $data,
]);
}
You can render view file in model Where you want as
Modal::begin([
'header' => '<h4>Events</h4>',
'id' => 'events',
'size' => 'model-lg',
]);
echo "<div id='modelContent'></div>";
Modal::end();
then you can create jquery file to show data in model
$(document).ready(function(){
var eventUrl = "http://example.com/model/show";
var data = "data to be sent in this view url for your case $manager";
$.get(eventUrl, {'data': data}, function(data){
$('#events').modal('show')
.find('#modelContent')
.html(data);
});
I could not follow the posts. I did the following:
<?php
Modal::begin([
'header' => "<h4>Top 10</h4>",
'id' => 'top10',
'size' => 'model-lg',
'toggleButton' => [
'tag' => 'a',
'label' => '
<span style="cursor: pointer;">
Veja os associados TOP 10 e cadastre sua visita!
</span>',
]
]);
echo $this->render('_modaltop10', ['manager' => $manager]);
Modal::end();
?>
You can implement this without Ajax.
Modal::begin([
'header' => '<h2>Hello world</h2>',
'toggleButton' => ['label' => 'click me'],
]);
echo $manager;
Modal::end();
Or, for example, use a bootbox (http://bootboxjs.com/).
In controller:
public function actionModalContent(){
$maanager = /*...*/
return $this->asJson($this->renderAjax('modal_content_view', ['manager'=>$manager]));
}
I want to render view page as a modal for preview
<div>
<?php foreach($softs as $soft) { ?>
<a id="modalButton" href="<?=Url::to(['documents/view', 'id'=>$soft->id]); ?>"><h3><?=$soft->title; ?></h3></a>
<?php
Modal::begin([
'header' => 'Test',
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
<?php } ?>
</div>
My controller
public function actionIndex()
{
$query = Documents::find();
$softs = $query->where(['type_id' => 2])->all();
return $this->render('index', [
'softs' => $softs,
]);
}
public function actionView($id)
{
return $this->renderAjax('view', [
'model' => $this->findModel($id),
]);
}
My script
$(function(){
$('#modalButton').click(function (){
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('href'));
});
});
But when I click the link it open a viewpage with no CSS, not a pop-up modal.
Please help me with this. Thank you
You update your code as per below.
<div>
<?php foreach($softs as $soft) { ?>
<!-- updated id to class here -->
<a class="modalButton" href="<?=Url::to(['documents/view', 'id'=>$soft->id]); ?>"><h3><?=$soft->title; ?></h3></a>
<?php } ?>
<!-- We don't need to print modal popup multiple times -->
<?php
Modal::begin([
'header' => 'Test',
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
</div>
Update click event.
$(function(){
// changed id to class
$('.modalButton').click(function (){
$.get($(this).attr('href'), function(data) {
$('#modal').modal('show').find('#modalContent').html(data)
});
return false;
});
});
how to check a submit button value in controller (Yii2). I am working with multiple submit button.
I tried simple php code. but it is not working.
if(isset($_POST['next']) && $_POST['next']=='gotocartfive')
code in view is :
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'status')->checkbox(); ?>
</div>
<div class="form-group">
<?php echo Html::submitButton('NEXT',array('value'=>'gotocartfive','name' => 'next','id'=>'next_summary','class'=>'btn btn-primary pull-right')); ?>
<?php echo Html::submitButton('PREVIOUS',array('value'=>'previous_four','name' => 'cartfour','class'=>'btn btn-primary pull-left')); ?>
</div>
<?php ActiveForm::end(); ?>
<?= Html::submitButton('Submit 1', ['name' => 'action', 'value' => 'submit_1']) ?>
<?= Html::submitButton('Submit 2', ['name' => 'action', 'value' => 'submit_2']) ?>
PHP
If (\Yii::$app->request->isPost) {
switch (\Yii::$app->request->post('action')) {
case 'submit_1':
case 'submit_2':
}
}
When you submit form by pressing enter (without click any submit button), submit_1 will be default value.
You can try following code.
Code in view file.
<?= Html::submitButton(Yii::t('app', '<i class="fa fa-times"></i> Remove'), ['class' => 'btn red', 'name' => 'submit', 'value' => '0']) ?>
<?= Html::submitButton(Yii::t('app', '<i class="fa fa-check"></i> Save'), ['class' => 'btn blue', 'name' => 'submit', 'value' => '1']) ?>
Code in controller action
if (Yii::$app->request->post()) {
if (Yii::$app->request->post('submit') == 0) {
//Code for value 0
}
if (Yii::$app->request->post('submit') == 1) {
//Code for value 1
}
}
Please let me know if you've any questions.
Try This :
View File
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'status')->checkbox(); ?>
<div class="form-group">
<?= Html::submitButton('NEXT',[ 'name'=>'submit', 'value' => 'next', 'class' => 'btn btn-primary pull-right']) ?>
<?= Html::submitButton('PREVIOUS',[ 'name'=>'submit', 'value' => 'previous', 'class' => 'btn btn-primary pull-right') ?>
</div>
<?php ActiveForm::end(); ?>
Controller File
public function actionYourControllerName()
{
if(isset($_POST['submit') && $_POST['submit']=='next')
{
// your code
}
else if(isset($_POST['submit']) && $_POST['submit']=='previous')
{
// your code
}
}
Also you can add this little js snippet to your project and bind it to beforeSubmit event in yii.activeForm.js like this:
(function ($) {
var formId = !!yiiconfig.viewPolicyParams && yiiconfig.viewPolicyParams.formId && yiiconfig.viewPolicyParams.formId,
$form = formId && $("#" + formId);
/**
* Updates hidden field that represents clicked submit button.
* #param event event object triggered
*/
function updateHiddenButton (event) {
var $buttons = $form.find(':submit');
$buttons.length && $buttons.each(function (i,b) {
var $hiddenButton = $('input[type="hidden"][name="' + $(b).attr('name') + '"]', $form);
$hiddenButton.length && $hiddenButton.remove();
});
};
$form && $form.bind('beforeSubmit.' + formId, updateHiddenButton);
} (jQuery));
This code removes all hidden inputs which are being created by yii.activeForm before submitting.
Then after this inputs will be recreated by yii.activeForm.
hope this helps