I need to use bootstrap modal to load form , how I can call bootstrap modal with parameters via link ?
View:
<?php echo CHtml::link(Yii::t('app','addaction'),'#myModal',array('class'=>'btn btn-primary','data-toggle'=>'modal')) ;?>
<br/><br/><br/>
<!-- Bootstrap modal dialog -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><?php echo Yii::t('app','AddAction'); ?></h4>
</div>
<div class="modal-body">
<?php echo $this->renderPartial('_form', array('model'=>$model,'productId'=>$productId)); // I need $productId to by dynamic related to link
?>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
Controller :
public function actionCreate()
{
$model=new Actions;
$productId=intval($_GET['productId']);
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['Actions']))
{
$model->attributes=$_POST['Actions'];
$model->product_id=$productId;
if($model->validate()){
$model->save(false);
$message=Email::setJavaMessage('success',Yii::t('app','sm'),Yii::t('app','actionWasAdded'));
echo CJSON::encode(array('status' => 'success','message'=>$message));
Yii::app()->end();
}else{
$error = CActiveForm::validate($model);
if($error!='[]')
echo $error;
Yii::app()->end();
}
}
if(Yii::app()->request->getIsAjaxRequest())
echo $this->renderPartial('_form',array('model'=>$model,'productId'=>$productId),false,true);//This will bring out the view along with its script.
else
$this->render('create',array(
'model'=>$model,'productId'=>$productId));
}
So with above code form is work with validation also, the problem if I need to add dynamic parameters to link how to ?
For example : use it in CRGidview via update function then the $product_id will change for every row related to values in database .
I don't know if you already found a solution but here is how I would do it:
In your link add a parameter like "data-productId" (for example: CHtml::link('Addaction','#myModal',array('id'=>'link','data-toggle' => 'modal','data-productId'=>$id, 'class' => 'link'))).
Bind a javascript function to the click event on your link like this:
$("a#link").click(function()
{
var productId = $(this).data('productId');
//you can change the value of a form component like this
//in the below example I have a hidden input field whose val I want to change to be submitted with the form
$("input#FormId_idHiddenInput").val(productId);
$('#myModal').modal('show');
});
For this example to work you would have to move your form from the partial to your dialog file.
Let me know if this helps you or if there are other problems you encounter.
Related
I have a modal in bootstrap 5 that i'm trying to populate with custom data from a mysql database depending on the option i'm selecting.
So I have a table that is populated with some data using PHP and MYSQL. The last column of the table is a button called "Actions" and I want to have a modal opened when I press this button that is filled with the information from the row where I pressed the button (every row contains this button as the last column).
As you can see in the below code, I have the exact same code as I found out in the sollution in this question: Pass PHP variable to bootstrap modal
Here is my code:
In the main index file:
...
...
<tbody>
<?php $categories = Category::find_all();
foreach ($categories as $category) { ?>
<tr>
<th scope="row"><?php echo $category->id; ?></th>
<td><?php echo $category->cat_name; ?></td>
<td><?php echo $category->cat_creation_date; ?></td>
<td><?php echo $category->cat_created_by; ?></td>
<td><a type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#bsMyModal" data-id="<?php echo $category->id; ?>">Actions</a></td>
</tr>
<?php } ?>
</tbody>
...
...
Modal code (in the same file as the above table):
<div class="modal fade" id="bsMyModal" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit Data</h4>
</div>
<div class="modal-body">
<div class="fetched-data"></div> //Here Will show the Data
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS code (just below the end of body in the same file)
</body>
<script>
$(document).ready(function(){
$('#bsMyModal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).data('id');
$.ajax({
type : 'post',
url : 'fetch_record.php', //Here you will fetch records
data : 'rowid='+ rowid, //Pass $id
success : function(data){
$('.fetched-data').html(data);//Show fetched data from database
}
});
});
});
</script>
Also the fetch_record.php file which is a basic file just to have this working:
<?php
require_once "backend/init.php";
if($_POST['rowid']) {
$id = $_POST['rowid']; //escape string
echo $id;
}
?>
Now the problem.. nothing happens
The modal openes when I press the Actions button, but I don't get any information (in this specific case I should be getting the category id printed out before the "//Here Will show the Data" text in the modal code.
I looked at the console and I've seen this message:
ajax:681 Uncaught ReferenceError: $ is not defined
at ajax:681:1
(anonymous) # ajax:681
If i click the link at # ajax:681, it points me to this:
enter image description here
What am I doing wrong?...
Thank you!
Stupid mistake...
I tought about searching for the console error and come upon this:
Uncaught ReferenceError: $ is not defined?
And yes.. I was using the script before referencing the jQuery.. I moved it after the jQuery include and now it works.
Dumb
I'm using Contact Form 7 in Wordpress, What I want to do is to call a specific JavaScript function when the form I created is submited show popup successful. and this my code
add_action('wpcf7_mail_sent', function ($cf7) {
// Run code after the email has been sent
$wpcf = WPCF7_ContactForm::get_current();
$wpccfid=$wpcf->id;
// if you wanna check the ID of the Form $wpcf->id
if ( '3854' == $wpccfid ) { // Change 123 to the ID of the form
echo '
<div class="modal" id="myModal2" role="dialog" style="display:block;" tabindex="-1">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content no_pad text-center">
<button type="button" class="close" data-dismiss="modal">×</button>
<div class="modal-header heading">
<h3 class="modal-title">Message Sent!</b></h3>
</div>
<div class="modal-body">
<div class="thanku_outer define_float text-center">
<h3>Thank you for getting in touch!</h3>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
';
}
});
I have an error and I don't know how to fix it
The wpcf7_mail_sent function is called in Ajax and the system expects the Ajax reply to be a JSON. So when you directly echo some HTML, that breaks the JSON and the Javascript can not parse it.
I wasn't able to find any example of usage of wpcf7_mail_sent that allowed custom HTML code, so it might not be possible to do so. The issue is that the code returns a message JSON variable and I think this should be plain text, not HTML.
Alternative 1: Edit DOM in Javascript
An alternative I've seen working is to use Javascript instead of PHP with a listener on the wpcf7mailsent event.
See example below:
<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
// Your code to edit the HTML goes here
}, false );
</script>
You can find a bit more info on how to use this and how to get for example the form_id in this other answer: https://stackoverflow.com/a/46977796/1529324
Alternative 2: Redirect
Alternatively, you can redirect the user to a custom page, instead of showing the Ajax confirmation
<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
if ( 'FORMID' === event.detail.contactFormId ) {
location = 'REDIRECTURL';
}
}, false );
</script>
I know there have been tons of questions about setting a PHP session from JQuery and then returning it to JQuery. And I have looked at all of them and still cannot figure out why my code doesn't work. I am trying to use a modal to set a PHP session variable on a back end PHP page and then display it in another modal using jquery, but nothing gets returned.
Here is my sending modal:
<div id="sendingModal" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-md" role="document">
<div class="modal-content">
<div class="modal-body">
<button id="testSession" type="button" class="btn btn-secondary">Session Test</button>
</div>
</div>
</div>
and here is my back end php:
<?php
session_start();
$_SESSION['testInput'] = $_POST['inputData'];
?>
and here is my receiving modal:
<div id="receivingModal" class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-md" role="document">
<div class="modal-content">
<div class="modal-body">
<div id="testDiv"></div>
</div>
</div>
</div>
Here is my JQuery:
$(document).ready(function() {
$('#testSession').on('click',function(e){
var testData = 'testing 123';
$.post("backendSession.php", {"inputData": testData});
$('#testSession').html(<?=$_SESSION['testInput']?>);
$('#testModal').modal('show');
});
});
What am I doing wrong?
You only have a small issue here, and its a simple fix based on the code you provided. You MUST return the new data back during the ajax call, or you will not be able to use it (not until, that is, a whole new page refresh).
First up, add to your backendSession.php:
<?php
session_start();
$_SESSION['testInput'] = $_POST['inputData'];
echo htmlspecialchars( $_SESSION['testInput'] );// new bit
?>
Then adjust your .post usage as follows:
$(document).ready(function() {
$('#testSession').on('click',function(e){
var testData = 'testing 123';
$.post("backendSession.php",
{"inputData": testData},
function( rawdata ) { // add return handler callback
$('#testDiv').html( rawdata ); // use the return data
$('#testModal').modal('show'); // show the modal
}
);
});
});
Now that is the basic change to make what you were wanting to do. However you may want to deal with JSON return data in the future, if you plan on needing more than just an echo of the input. An example of that will go beyond the question though ;)
As another side: You probably will want to sanitize that post input. I know what you provided was a minimal example, but I just wanted to mention it. As simply echoing out the raw user input, back into a page, can open up some XSS attack vectors.
i need some help, i have already read a lot of articles but haven't found de solution to my problem.
As you can see in the picture my modal button is in a table but when i click de edit button it shows de modal with the edit form but it closes inmmediately
These is my code of my button, im using php and bootstrap:
echo "<td><a href='consultar_usuario.php?id_trabajador=$arreglo[0]&idactualizar=3'><img src='../imagenes/Iconos/actualiza.png' class='img-rounded' data-toggle='modal' data-target='#myModal'></td>";
and these is the code of my modal:
echo'
<div class="control-group modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Modificar Empleado</h3>
</div>
<form action="../validar_form/valida_actualizacion.php" method="post" class="form-horizontal modal-body">
all the divs and form are close in my proyect.
I really apreciate your help.
I have a suggestion hope this helps somehow.
this line:
echo "<td><a href='consultar_usuario.php?id_trabajador=$arreglo[0]&idactualizar=3'><img src='../imagenes/Iconos/actualiza.png' class='img-rounded' data-toggle='modal' data-target='#myModal'></td>";
can you change it to this:
echo "<td><a href='consultar_usuario.php?id_trabajador=$arreglo[0]&idactualizar=3'><img src='../imagenes/Iconos/actualiza.png' class='img-rounded modal_clicker'></td>";
and add this javascript:
<script>
$(".modal_clicker").on("click", function(){
$('#myModal').modal('show');
});
</script>
That way you can just echo the "modal_clicker" and not repeating the "data-toggle='modal' data-target='#myModal'" over and over again.
And for your question I hope this code helps:
<script>
$("#myModal").modal({
backdrop: 'static',
keyboard: false})
</script>
[ Fixed / Solution ]
I found what's causing it. Your are trying to open a new url everytime you click the link; here <a href='consultar_usuario.php?id_trabajador=$arreglo[0]&idactualizar=3'>
The fix for this is to change your href or link into this.
<a href='javascript:void(0);'>
If you want to access these: id_trabajador=$arreglo[0]&idactualizar='3'
try adding this to your link as data-*. See example below.
<a href='javascript:void(0);' class="modal_clicker" data-id_trabajador='".$arreglo[0]."' data-idactualizar=3'>
You can then access those data-* using the javascript below:
$(".modal_clicker").on("click", function(){
var ele = $(this);
var id_trabajador = ele.attr("data-id_trabajador");
var idactualizar= ele.attr("data-idactualizar");
$('#myModal').modal('show');
});
I need to pass a variable through the link when calling a pop up window. When adding a variable like I normally would the names don't match up with the pop up window.
This is what I have:
<a data-toggle="modal" href="#allMessages?id=<?php echo $job['job_id']; ?>" class="btn btn-warning btn-sm btn-icon">
<i class="fa fa-unlock-alt"></i>View All Messages
</a>
<div class="modal fade" id="allMessages" tabindex="-1" role="dialog" aria-labelledby="allMessages" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header success">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="fa fa-times"></i></button>
<h4 class="modal-title">Reply</h4>
</div>
<?php
$getMessages = mysqli_query($mysqli,
"SELECT *
FROM messages
WHERE messages.job_id = $GET['id']
"
);
$messages = array();
while($message = mysqli_fetch_assoc($getMessages)) {
$messages[] = $message;
}
The problem is when I add the variable at the end of the button link #allMessages?id= it no longer calls the pop-up window.
Javascript:
$("[data-toggle='popover']").popover();
});
function load_page() {
var selected_page = document.getElementById("selected_page").value;
if (selected_page != "") {
window.location.href = selected_page
//Please note that the value recived,
//in this case selected_page,
//should be a valid url!
//Therefore the value of the
//<option> tag should be itself
//a url !
//ex.: <option value="page.php"> is valid
//<option value="page_1"> is not valid
}
I can't see this working.
The modal is already on the page, just invisible so any PHP queries would be done when the page is rendered, not when the modal is activated.
Personally I'd send the ID over in a data attribute, do the processing in an AJAX request and then push the results into the modal box.