Pass datatable row value to modal - php

Dears,
I am trying to pass a column value in a row to a modal when I click on edit, but that is not working. I am not sure how to do that honestly.
When I click on edit, a modal should open. My goal is to display the current image name in a disabled field and let the admin enter the new name to rename it.
My admin template source => https://startbootstrap.com/theme/sb-admin-2
datatable code :
<tbody>
<?php
foreach ($imagesPath as $imageId=>$imagePath) {
echo "<tr>";
echo " <td> <img src=".$imagePath." border='0' height=200px width=200px /> </td>";
echo " <td name='imageName'>".substr($imagePath, 59)."</td>";
echo " <td>
<a href='#' class='btn btn-info btn-circle' data-toggle='modal' data-target='#editModal' data-val=".$imagesPath[$imageId].">
<i class='fas fa-edit'></i>
</a>
<a href='#' class='btn btn-danger btn-circle'>
<i class='fas fa-trash'></i>
</a>
</td>";
echo "</tr>";
}
?>
</tbody>
Modal Code:
<!-- Edit Modal-->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="renameModal"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="renameModal">Rename Image</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<label class="control-label" for="oldImageName">Old Image Name</label>
<input id="oldImageName" class="form-control form-control-user" disabled></input><br>
<label class="control-label" for="newImageName">New Image Name</label>
<input id="newImageName" class="form-control form-control-user" type="text" ></input>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
<a class="btn btn-primary" href="#">Rename</a>
</div>
</div>
</div>
</div>
js code:
<script>
$('#editModal').on('show.bs.modal', function(e) {
var oldImageValue = $(event.relatedTarget).data('val');
$(e.currentTarget).find('input[id="oldImageName"]').val(oldImageValue);
});
</script>
What I tried to implement is a solution mentioned in Passing data to a bootstrap modal . But it did not work. Can you please assist with the above?

In your HTML, you are using the following attribute:
data-val=".$imagesPath[$imageId]."
And then you appear to be trying to access it in your JavaScript using:
var oldImageValue = $(event.relatedTarget).data('val');
There are 3 problems with this:
(1) it's an attribute, not data
(2) its name is data-val not val
(3) your function refers to the event as e, not as event.
Therefore you need to use:
var oldImageValue = $(e.relatedTarget).attr('data-val');
After that, I suspect you will have some additional issues...
The above change will cause the value from .$imagesPath[$imageId]. to be populated in the modal - and I assume that is not what you want.
How you fix this depends on information outside of your question, but you could, for example, change your HTML to include additional attributes - for example, something like this:
data-image-id=".$imagesPath[$imageId]."
data-image-name=".$imagesPath[$imageName]."
... and whatever else you may need...
The above is just a suggestion - you may need to adapt it to your needs.
A demo using the above changes:
$(document).ready(function() {
var table = $('#example').DataTable();
$('#editModal').on('show.bs.modal', function(e) {
var oldPersonValue = $(e.relatedTarget).attr('data-name');
$(e.currentTarget).find('input[id="oldPersonName"]').val(oldPersonValue);
});
} );
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/dataTables.bootstrap4.css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.25/js/dataTables.bootstrap4.js"></script>
</head>
<body>
<div style="margin: 20px;">
<table id="example" class="display dataTable cell-border" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>
<a href="#"
class="btn btn-info btn-circle"
data-toggle="modal"
data-target="#editModal"
data-val="123"
data-name="Tiger Nixon">
<i class='fas fa-edit'></i>edit
</a>
</td>
</tr>
<tr>
<td>234</td>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>
<a href="#"
class="btn btn-info btn-circle"
data-toggle="modal"
data-target="#editModal"
data-id="234"
data-name="Garrett Winters">
<i class='fas fa-edit'></i>edit
</a>
</td>
</tr>
<tr>
<td>345</td>
<td>Ashton Cox</td>
<td>Junior "Technical" Author</td>
<td>San Francisco</td>
<td>
<a href="#"
class="btn btn-info btn-circle"
data-toggle="modal"
data-target="#editModal"
data-id="345"
data-name="Ashton Cox">
<i class='fas fa-edit'></i>edit
</a>
</td>
</tr>
</tbody>
</table>
<!-- Edit Modal-->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="renameModal"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="renameModal">Rename Person</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<label class="control-label" for="oldPersonName">Old Person Name</label>
<input id="oldPersonName" class="form-control form-control-user" disabled></input><br>
<label class="control-label" for="newPersonName">New Person Name</label>
<input id="newPersonName" class="form-control form-control-user" type="text" ></input>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
<a class="btn btn-primary" href="#">Rename</a>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
After that, a further problem may be that you want to actually save your changes and re-display the saved data. If that is the case, then that probably needs a new question where you can show the relevant code/attempt.

Related

Bootstrap modal doesn't get user ID

I have a problem with a bootstrap modal. I'm using PHP.
In an admin panel there is a table with the list of the users and the possibility to edit or delete a user's profile. For the delete I want to create a modal for the confirm of the delete but, when I click on "confirm" button inside the modal, the modal gets by default the user ID of the first user in the table and not the user ID of the selected user.
Here is the code:
<?php foreach ($utenti as $utente) { ?>
<tr>
<th scope="row"> <?php echo $utente['idUser']?> </th>
<td><?php echo $utente['nome']." ".$utente['cognome']?></td>
<?php if($_SESSION['role'] == 1) {?>
<td><?php echo $utente['az']?></td>
<?php } ?>
<td><?php echo $utente['email']?></td>
<td class="text-warning"><a
href="<?php echo 'editUser.php?user='.$utente['idUser']?>"><i
class="fas fa-edit text-warning"></i></a></td>
<!-- <td class="text-warning"><i class="fas fa-trash-alt text-danger"></i></td> -->
<td class="text-danger">
<button type="button" class="btn" data-toggle="modal"
data-target="#confirmDelete"><i
class="fas fa-trash-alt text-danger"></i><?php var_dump($utente['idUser']); ?>
</button>
</td>
<div class="modal" tabindex="-1" role="dialog" id="confirmDelete">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
Attenzione <?php var_dump($utente['idUser']); ?></h5>
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Continuando eliminerai l'utente in maniera irreversibile</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger "
><a
class="text-white btn-modal-confirm"
href="<?php echo '?action=delete&user='.$utente['idUser']?>"
>Elimina</a>
</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">
Indietro
</button>
</div>
</div>
</div>
</div>
</tr>
<?php }?>
If I make a var_dump of $utente['idUser'] before the modal, it gets the right user ID. If I make it inside the modal it gets by default the first ID, as I said.
Notice that every modal trigger button has a data-target attribute to define which modal will be opened.
In your case, the button of every row you used to triggered the modal have the same data-target, which is #confirmDelete. These modals behind also has the same id called #confirmDelete, so every time you hit the modal trigger button (all had the same data-target) then eventually it will shows up the very first modal element.
For a better understanding, compare my code to yours and see the differences.
<?php foreach ($utenti as $utente) { ?>
<tr>
<th scope="row"> <?php echo $utente['idUser']?> </th>
<td><?php echo $utente['nome']." ".$utente['cognome']?></td>
<?php if($_SESSION['role'] == 1) {?>
<td><?php echo $utente['az']?></td>
<?php } ?>
<td><?php echo $utente['email']?></td>
<td class="text-warning"><a
href="<?php echo 'editUser.php?user='.$utente['idUser']?>"><i
class="fas fa-edit text-warning"></i></a></td>
<!-- <td class="text-warning"><i class="fas fa-trash-alt text-danger"></i></td> -->
<td class="text-danger">
<button type="button" class="btn" data-toggle="modal"
data-target="#confirmDelete_<?php echo $utente['idUser']; ?>"><i
class="fas fa-trash-alt text-danger"></i><?php var_dump($utente['idUser']); ?>
</button>
</td>
<div class="modal" tabindex="-1" role="dialog" id="confirmDelete_<?php echo $utente['idUser']; ?>">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
Attenzione <?php echo $utente['idUser']; ?></h5>
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Continuando eliminerai l'utente in maniera irreversibile</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger "
><a
class="text-white btn-modal-confirm"
href="<?php echo '?action=delete&user='.$utente['idUser']?>"
>Elimina</a>
</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">
Indietro
</button>
</div>
</div>
</div>
</div>
</tr>
<?php }?>
In the above code, I gave every pair of modal elements (modal trigger button and modal ID) a unique data-target value and a unique element id.
...
<button type="button" class="btn" data-toggle="modal"
data-target="#confirmDelete_<?php echo $utente['idUser']; ?>">
...
<div class="modal" tabindex="-1" role="dialog" id="confirmDelete_<?php echo $utente['idUser']; ?>">
...
Now each pair of modal elements have their own ids and they should be working the way you wanted.

Codeigniter: Bootstrap Modal with table data

I have a table of data populated using a foreach loop like below:
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Keyboard Language</th>
<th scope="col">PC Spec</th>
<th scope="col">Desk Position</th>
<th scope="col">Price Per Hour</th>
<th scope="col">Hours</th>
<th scope="col">Total Price</th>
<th scope="col">Confirm</th>
</tr>
</thead>
<tbody>
<?php $increment =1; ?>
<!--print each item in a new row on the table -->
<?php foreach($bookingData as $booking_item) { ?>
<tr>
<td><?php echo $increment ?></td>
<td><?php echo $booking_item['item']; ?></td>
<td><?php echo $booking_item['item1']; ?></td>
<td><?php echo $booking_item['item2']; ?></td>
<td><?php echo '£ '. $booking_item['item3']; ?></td>
<td><?php echo $userEntered['item4']; ?></td>
<td><?php echo '£ '.$userEntered['item5'] * $booking_item['item6']; ?></td>
<?php $totalPrice = $userEntered['item7'] * $booking_item['item7'];?>
<td><button class="btn btn-success" data-toggle="modal" data-target="#exampleModalCenter<?php echo $increment; ?>"><i class="fa fa-calendar-check" style="color: white;"></i>Book now!</button></td>
</tr>
<?php $increment++; } ?>
</tbody>
</table>
I have button in each table row, I want to create a modal that pops up to ask the user to confirm the action using the modal code below:
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<?php echo $booking_item['item1']?>
<?php echo $booking_item['item2']?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Confirm Booking!</button>
</div>
</div>
</div>
</div>
However, I'm stumped as to how to load each row of data into the modal for each table row, I have done this before in another project but I can't for the life remember how to replicate it
For the modal to be loaded there needs to be seperate model content for each triggers. So you need model contents in foreach also.
<?php foreach
<td><button class="btn btn-success" data-toggle="modal" data-target="#exampleModalCenter<?php echo $increment; ?>"><i class="fa fa-calendar-check" style="color: white;"></i>Book now!</button></td>
foreach end
?>
<?php foreach
$increment =0;
<div class="modal fade" id="exampleModalCenter#exampleModalCenter<?php echo $increment; ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
model content
</div>
</div>
$increment++;
foreach end
?>
I hope you understand what I am trying to tell you. You need to loop modal also and make the id dynamic.
I managed to accomplish this by using some simple JQuery and data attributes. I pass the data attributes into the button during the foreach loop so my button now looks like this:
<button class="btn btn-success" data-toggle="modal" data-target="#exampleModalCenter"
data-specs="PC Specs: <?php echo $booking_item['specs'];?>"
data-date="Date: <?php echo $userEntered['date'];?>"
data-start="Start: <?php echo $userEntered['start_time'];?>"
data-end="End : <?php echo $userEntered['end_time'];?>"
data-totalprice="Total Price : <?php echo $totalPrice;?>"
data-hours="Hours : <?php echo $userEntered['hours_booked'];?>">
<i class="fa fa-calendar-check" style="color: white;"></i>Book now!
</button>
Now In my Jquery, I fetch these values and set the text of the classes I have established within the modal
$('#exampleModalCenter').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) //button that triggers modal
var spec = button.data('specs') // Extract info from data-* attributes
var date = button.data('date')
var start = button.data('start')
var end = button.data('end')
var hours = button.data('hours')
var totalPrice = button.data('totalprice')
var modal = $(this)
modal.find('.specs').text(spec)
modal.find('.date').text(date)
modal.find('.start').text(start)
modal.find('.end').text(end)
modal.find('.hours').text(hours)
modal.find('.totalprice').text(totalPrice)
})
I found this at: https://getbootstrap.com/docs/4.0/components/modal/
Firstly add id attribute to the confirm button and store all your data in data attribute as I did in the below code.
In your modal add form to submit your data stored in the hidden input fields.
Edit
As per your answer, I've updated my code
Your button
<button class="btn btn-success" id="confirmBtn"
data-specs="<?php echo $booking_item['specs'];?>"
data-date="<?php echo $userEntered['date'];?>"
data-start="<?php echo $userEntered['start_time'];?>"
data-end="<?php echo $userEntered['end_time'];?>"
data-totalprice="<?php echo $totalPrice;?>"
data-hours="<?php echo $userEntered['hours_booked'];?>">
<i class="fa fa-calendar-check" style="color: white;"></i>Book now!
</button>
Your Modal code
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="<?php echo base_url(); ?>your_controller_name/confirm_book" method="post">
<div class="modal-body">
<input type="hidden" name="id" id="bookId" />
<input type="hidden" name="specs" id="specs" />
<input type="hidden" name="date" id="date" />
<input type="hidden" name="start_time" id="start_time" />
<input type="hidden" name="end_time" id="end_time" />
<input type="hidden" name="totalPrice" id="totalPrice" />
<input type="hidden" name="hours_booked" id="hours_booked" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Confirm Booking!</button>
</div>
</form>
</div>
</div>
</div>
This is your jquery code which does all your work.
Jquery Code
$('#confirmBtn').on('click', function (e) {
e.preventDefault();
var id = $(this).data('id'); //takes the `id` from your button
var specs = $(this).data('specs');
var date = $(this).data('date');
var start_time = $(this).data('start_time');
var end_time = $(this).data('end_time');
var totalPrice = $(this).data('totalPrice');
var hours_booked = $(this).data('hours_booked');
$("#exampleModalCenter #bookId").val(id); //stores to modal hidden field
$("#exampleModalCenter #specs").val(specs);
$("#exampleModalCenter #date").val(date);
$("#exampleModalCenter #start_time").val(start_time);
$("#exampleModalCenter #end_time").val(end_time);
$("#exampleModalCenter #totalPrice").val(totalPrice);
$("#exampleModalCenter #hours_booked").val(hours_booked);
$('#exampleModalCenter').modal();
});
Here is your controller code
public function confirm_book(){
$id = $this->input->post('id');
$specs= $this->input->post('specs');
$date= $this->input->post('date');
$start_date= $this->input->post('start_date');
$end_date= $this->input->post('end_date');
$totalPrice= $this->input->post('totalPrice');
$hours_booked= $this->input->post('hours_booked');
//do whatever you want to do with these data
}
Hope this will help you.

How to pass value in bootstrap v4 modal?

As you can see below, I have a php-generated table with a td that contains both edit and delete anchors. I put the $data['id'] inside the data-id attribute of the anchor and I pass it to the modal via jquery. However, the ID of the article is not being displayed on the modal. Can someone tell what is wrong with my codes? Is it the php, the html, or the jquery? Thanks!
<?php
require "../connection.php";
$query = mysqli_query($conn, "SELECT * FROM `articles`");
while($data = mysqli_fetch_array($query)) {
echo '<tr>';
echo '<th scope="row">'.$data['id'].'</th>';
echo '<td><div align="center">EditDelete</div></td>';
echo '</tr>';
}
?>
PHP-GENERATED TABLE
<!-- Modal-->
<div id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" class="modal fade text-left">
<div role="document" class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 id="exampleModalLabel" class="modal-title">Edit Article</h5>
<button type="button" data-dismiss="modal" aria-label="Close" class="close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<p>Please save your changes after editing the article.</p>
<form id="myForm">
<div class="form-group">
<label>ID</label>
<input type="text" value="" name="articleId" id="articleId" class="form-control">
</form>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-secondary">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
HTML MODAL
$('#myModal').on('show.bs.modal', function (e) {
// get information to update quickly to modal view as loading begins
var opener=e.relatedTarget;//this holds the element who called the modal
//we get details from attributes
var myArticleId=$(opener).attr('data-id');
//set what we got to our form
$('#myForm').find('[name="articleId"]').val(myArticleId);
});
JQUERY
<table class="table table-striped table-hover">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Summary</th>
<th>Content</th>
<th><div align="center">Date Published</div></th>
<th><div align="center">Date Last Edited</div></th>
<th><div align="center">Action</div></th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td><div align="center">EditDelete</div>
</td>
</tr>
<tr>
<th scope="row">2</th>
<td><div align="center">EditDelete</div>
</td>
</tr>
<tr>
<th scope="row">3</th>
<td><div align="center">EditDelete</div>
</td>
</tr>
</tbody>
</table>
INSPECTED PAGE - TABLE
$('#articleEditModal').on('show.bs.modal', function (e) {
An error shows on this line above:
Uncaught ReferenceError: $ is not defined
at cms.php:162
var opener = $(e.relatedTarget); instead of var opener=e.relatedTarget;
Reference Bootstrap Modal
Hope this helps!
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" crossorigin="anonymous"></script>
<table>
<tr>
<th scope="row">2</th>
<td>
Edit
Delete
</td>
</tr>
</table>
<!-- Modal-->
<div id="articleEditModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" class="modal fade text-left">
<div class="modal-content">
<div class="modal-header">
<h5 id="exampleModalLabel" class="modal-title">Edit Article</h5>
<button type="button" data-dismiss="modal" aria-label="Close" class="close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<p>Please save your changes after editing the article.</p>
<form id="myForm">
<div class="form-group">
<label>ID</label>
<input type="text" value="" name="articleId" id="articleId" class="form-control">
</form>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-secondary">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<script>
$('#articleEditModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var article_id = button.attr('data-article-id')
// take advantage of data attribute
// var article_id = button.data('article-id');
var modal = $(this)
modal.find('.modal-title').text('Article ' + article_id)
modal.find('.modal-body input').val(article_id)
})
</script>
// Sample php data
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" crossorigin="anonymous"></script>
<?php
require "../connection.php";
$query = mysqli_query($conn, "SELECT * FROM `articles`");
while($data = mysqli_fetch_array($query)) {
echo '<tr>';
echo '<th scope="row">'.$data['id'].'</th>';
echo '<td><div align="center">EditDelete</div></td>';
echo '</tr>';
}
?>
<!-- Modal-->
<div id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" class="modal fade text-left">
<div role="document" class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 id="exampleModalLabel" class="modal-title">Edit Article</h5>
<button type="button" data-dismiss="modal" aria-label="Close" class="close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<p>Please save your changes after editing the article.</p>
<form id="myForm">
<div class="form-group">
<label>ID</label>
<input type="text" value="" name="articleId" id="articleId" class="form-control">
</form>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-secondary">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
<script>
$('#myModal').on('show.bs.modal', function (e) {
// get information to update quickly to modal view as loading begins
var opener=$(e.relatedTarget);//this holds the element who called the modal
//we get details from attributes
var myArticleId=$(opener).attr('data-id');
//set what we got to our form
$('#myForm').find('[name="articleId"]').val(myArticleId);
});
</script>

How to pass data from table of records to Modal for editing purposes

I know this has been asked a lot but I haven't found any of the answers to the issue to be very fruitful. I essentially have a table inside a view that is displayed using a foreach loop in PHP, this spits out the records one by one and appends some 'Action' buttons in the last column (download, delete and edit). The download and delete functions work perfectly, I just pass the ID in from each record in the foreach loop, job done.
I'm having a lot of issues with my modal though, it only ever displays the data from the first record when I echo the data in the 'value' field of each input. I'm really stumped on how to make this functionality work (JQuery is not my strongest language). I've seen some responses talking about Ajax, but I'd rather not use Ajax in this project. I'm using the codeigniter framework also for some more info.
I think the issue is that the modal is only created once when the foreach loop starts running, hence why it only ever has the first record data inside the modal, any help to get around this so I can edit each individual record inside the table would be great! Thanks for the help.
HTML/PHP:
<div class="container" id="widecontainer">
<h1 id="title">VMS Failure Records</h1>
<br>
<!-- print table with results onto view.php -->
<table class="table table-bordered" id="record">
<?php if($results) : ?>
<thead>
<tr style="background-color: #d3d3d3;">
<th>ID</th>
<th>VSM S/N</th>
<th>VM S/N</th>
<th>Project</th>
<th>Site</th>
<th>Install Loc</th>
<th>Observed During</th>
<th>Comments</th>
<th>Reported By</th>
<th>Replaced With</th>
<th>Date</th>
<th>Failure Classification</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<!-- foreach result place it in row in table -->
<?php foreach($results as $res) : ?>
<tr>
<td><?php echo $res['id'] ?></td>
<td><?php echo $res['vsm_sn'] ?></td>
<td><?php echo $res['vm_sn'] ?></td>
<td><?php echo $res['project'] ?></td>
<td><?php echo $res['site'] ?></td>
<td><?php echo $res['install_location'] ?></td>
<td><?php echo $res['observed_during'] ?></td>
<td><?php echo $res['comments'] ?></td>
<td><?php echo $res['reported_by'] ?></td>
<td><?php echo $res['replaced_with'] ?></td>
<td><?php echo $res['date'] ?></td>
<td><?php echo $res['classification'] ?></td>
<td>
<?php echo form_open('/pages/delete/'. $res['id']); ?>
<button type="submit" class="btn btn-danger delete_btn" id="delete_btn" target="#confirmation">
<i class="fa fa-trash" aria-hidden="true"></i>
</button>
<!-- Modal displays when user clicks delete, asking them to confirm the deletion -->
<div id="confirm" name="confirm" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Delete Record <i class="fa fa-trash" aria-hidden="true"></i></h4>
</div>
<div class="modal-body">
<p style="color: red;"><strong>Deleting this record will delete .PDF and QRCode Data.</strong></p>
<p>Are you sure you want to delete this record?</p>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-danger" id="delete">Delete</button>
<button type="button" data-dismiss="modal" class="btn">Cancel</button>
</div>
</div>
</div>
</div>
</form>
<!--Modal displays to allow user to download the selected record. -->
<?php echo form_open('/pages/downloadFile/'. $res['id']); ?>
<button type="submit" class="btn btn-primary" alt="Download .pdf">
<i class="fa fa-download" aria-hidden="true"></i>
</button>
</form>
<form>
<button type="button" class="btn btn-success update_btn" id="update_btn" data-toggle="modal" data-target="#myModal"
vsm-sn="<?php echo $res['vsm_sn'];?>" record-id="<?php echo $res['id']; ?>">
<i class="fa fa-pencil" aria-hidden="true"></i>
</button>
</form>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Update Record</h4>
</div>
<div class="modal-body">
<form id="profileForm">
<input type="hidden" class="form-control" name="id" value="">
VSM SN : <input class="form-control" name="vsm_sn" value="" placeholder="VSM SN">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</td>
</tr>
<?php endforeach; ?>
<!-- If there are no results, display table headings and message -->
<?php elseif(!$results) : ?>
<thead>
<tr>
<th>ID</th>
<th>VSM S/N</th>
<th>VM S/N</th>
<th>Project</th>
<th>Site</th>
<th>Install Loc</th>
<th>Observed During</th>
<th>Comments</th>
<th>Reported By</th>
<th>Replaced With</th>
<th>Date</th>
<th>Failure Classification</th>
</tr>
</thead>
<tbody>
<h3 style="color: red;">No Results to Display</h3>
</tbody>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
JQUERY:
$('#myModal').on('show.bs.modal', function (e) {
// get information to update quickly to modal view as loading begins
var opener=e.relatedTarget;//this holds the element who called the modal
//we get details from attributes
var vsm_sn=$(opener).attr('vsm-sn');
//set what we got to our form
$('#profileForm').find('[name="vsm_sn"]').val(vsm_sn);
});
The best way to go about it , is to use events hooks which is tied to the modal to help manage dynamism on modals.
Take for example, you want to pass information from the for loop to the modal you can do this using just a modal and then update the modal as it opens.
check bootstrap docs you will see this hook for modal
show.bs.modal
we then use attributes from the button to pick out our information we are going to display on the modal, e.g
<button user-id="<?php echo $data[$i]->userID; ?>" first-name="<?php echo $data[$i]->firstname;?>">Edit</button>
then we can use Jquery to pick it up and hook it when the modal is opening
See for example code here, replace the static repeat with your dynamic coding
$('#myModal').on('show.bs.modal', function (e) {
// get information to update quickly to modal view as loading begins
var opener=e.relatedTarget;//this holds the element who called the modal
//we get details from attributes
var firstname=$(opener).attr('first-name');
//set what we got to our form
$('#profileForm').find('[name="firstname"]').val(firstname);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<table class="table">
<thead>
<tr>
<th>SN</th>
<th>Firstname</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Theophilus</td>
<td>
<button class="btn btn-primary" first-name="Theophilus" data-toggle="modal" data-target="#myModal">
Edit
</button>
</td>
</tr>
<tr>
<td>3</td>
<td>Omoregbee</td>
<td>
<button class="btn btn-primary" first-name="Omoregbee" data-toggle="modal" data-target="#myModal">
Edit
</button>
</td>
</tr>
<tr>
<td>3</td>
<td>Endurance</td>
<td>
<button class="btn btn-primary" first-name="Endurance" data-toggle="modal" data-target="#myModal">
Edit
</button>
</td>
</tr>
</tbody>
</table>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<form id="profileForm">
Firstname : <input class="form-control" name="firstname" value="" placeholder="firstname">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Run it and see the result, so you can change the table style to use loop in php and then echo your data as attribute.
Hope it helps.
assign an id to modal body, e.g. : modal-body
declare a variable to store the HTML for the modal body, e.g. var modalHTML = ''
then append the contents in the for loop to that variable.
after that append the variable to the modal body, using $('#modal-body).append($(modalHTML)).

Return as same value from database into bootstrap modal

I have my data displayed in table, and the way to edit and delete the data is in bootstrap modal. I'll just showing my delete modal. I used CodeIgniter 2.2.6:
My table:
<table class="table table-striped table-bordered table-hover">
<thead class="text-center">
<th class="text-center">No.</th>
<th class="text-center">Major Code</th>
<th class="text-center">Major Name</th>
<th class="text-center">Option</th>
</thead>
<tbody>
<?php $no = 1; ?>
<?php foreach ($select_major as $row): ?>
<tr>
<td><?php echo $no++; ?></td>
<td><?php echo $row->cd_major; ?></td>
<td><?php echo $row->name_major; ?></td>
<td align=center>
<!-- DELETE BUTTON -->
<a
class="btn btn-danger btn-xs"
role="button"
data-toggle="modal"
data-target="#modal-delete"
href="<?php
$cd_major = $row->cd_major;
$name_major = $row->name_major;
?>">
<i class="fa fa-fw fa-trash"></i> Delete
</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
My Modal:
<!-- MODAL DELETE DATA -->
<div class="modal fade" id="modal-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form class="form-horizontal" method="POST" action="<?php echo base_url('major'); ?>">
<input type="hidden" name="id_major" value="<?php echo (isset($id_major) ? $id_major : ''); ?>" />
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<!-- MODAL TITLE -->
<h4 class="modal-title"><i class="fa fa-fw fa-trash"></i> Delete Data</h4>
</div>
<!-- FORM -->
<div class="modal-body">
<p>Are you sure to delete this major? <b><?php echo $name_major; ?></b> ini?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-danger" name="delete" value="Yes, delete" />
</div>
</form>
</div><!--/ .modal-content -->
</div><!--/ .modal-dialog -->
</div><!--/ .modal -->
But when I try to delete the selected data, it always ordering to delete the last data. What should I do to fix it?
In your case you would add code something like below:
Your new table:
<table class="table table-striped table-bordered table-hover">
<thead class="text-center">
<th class="text-center">No.</th>
<th class="text-center">Major Code</th>
<th class="text-center">Major Name</th>
<th class="text-center">Option</th>
</thead>
<tbody>
<?php $no = 1; ?>
<?php foreach ($select_major as $row): ?>
<tr>
<td><?php echo $no++; ?></td>
<td><?php echo $row->cd_major; ?></td>
<td><?php echo $row->name_major; ?></td>
<td align=center>
<!-- DELETE BUTTON -->
<a
class="btn btn-danger btn-xs"
role="button"
data-toggle="modal"
data-target="#modal-delete"
href="<?php
$cd_major = $row->cd_major;
$name_major = $row->name_major;
?>" onclick=deleteRecord(<?php $row->cd_major?>)>
<i class="fa fa-fw fa-trash"></i> Delete
</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<script>
function deleteRecord(id){
document.getElementById("id_major").value = id;
}
</script>
Your new modal:
<!-- MODAL DELETE DATA -->
<div class="modal fade" id="modal-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form class="form-horizontal" method="POST" action="<?php echo base_url('major'); ?>">
<input type="hidden" name="id_major" id="id_major" value="<?php echo (isset($id_major) ? $id_major : ''); ?>" />
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<!-- MODAL TITLE -->
<h4 class="modal-title"><i class="fa fa-fw fa-trash"></i> Delete Data</h4>
</div>
<!-- FORM -->
<div class="modal-body">
<p>Are you sure to delete this major? <b><?php echo $name_major; ?></b> ini?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-danger" name="delete" value="Yes, delete" />
</div>
</form>
</div><!--/ .modal-content -->
</div><!--/ .modal-dialog -->
</div><!--/ .modal -->
Please use the code which i have given you, it should work now.
I assume cd_major is the id of the row which you want to delete, if not, you can replace the field name in the function which we have added to <a> tag in onclick event.
Thanks

Categories