i have create a bootstrap modal but i need the content to be dynamic. Each time i select a different table row, the content of that row should popup. The content inside bootstrap modal is a dynamic table. Is possible to show a simple sample of how by selecting from the row of a table, i can get a dynamic table in the popup modal. Please help. Thanks
while($row = $results->fetch_assoc()): ?>
<tr>
<td class="list-answer"
data-toggle="modal"
href="#content-confirmation">
<?= $row["name"]; ?>
</td>
</tr>
<?php endwhile ?>
<div class="control-popup modal fade" id="content-confirmation"
tabindex="-1" role="dialog">
<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">Are you sure you wanna do
that?</h4>
</div>
<div class="modal-body">
load dynamic table content.......
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"
data-dismiss="modal">Save</button>
</div>
</div>
</div>
Are you trying to give your table column a link with href ? because it would not work like that.
To your question, there are multiple ways of doing this. I would give the table's row an id and handle the row click or column click event in js code. after that i would get that rows content either with an ajax request or directly from the table's columns.
So your code would look like:
while($row = $results->fetch_assoc()): ?>
<tr data-id="<?= $row["id"]; ?>">
<td class="list-answer">
<?= $row["name"]; ?>
</td>
</tr>
your javascript code:
$(function(){
$(".list-answer").click(function() {
var row_id = $(this).parents('tr').attr('data-id');
get_data(row_id);
$('#my-modal').modal();
});
});
function get_data(row_id) {
//either get data with ajax request or row
//fill modals content with $('#input-field-id').val('vlaue') or .html()
}
$.ajax({
url : 'url',
method : 'post',
data: {
},
success : function(response)
{
$('#my-modal').html(response);
// put your html response in the popup div
$('#my-modal').modal();
}
});
<div id="my-modal"></div>
I don't know if i understand well, but i think you need something like me :
$("table").on('click', 'tr', function() {
var json_data = {
"controller": "NameOfController",
"action": "action",
"contentofRow": $(this).text()
};
$.post('ajax_handler.php', json_data, function (res) {
if (res.indexOf('ERREUR') != -1) {
alert(res);
return false;
}
else {
$('#mymodalID').modal();
$("#myModalLabel").html("Content of the row : " + res[0]);
$.each(res[1], function (index, valeur) {
$("#bodySupp").append($('<tr>')
.css("text-align", "center")
.css("fontSize", "12px")
.append($('<th>')
.html(valeur['indexOfValue'])
)
.append($('<th>')
.html(index)
)
.append($('<th>')
.html(valeur['indexOfValue2'])
)
.append($('<th>')
.html(valeur['indexOfValue3'])
)
)
});
}
}, 'json');
});
$("table").on('click', 'tr', function()
You open the modal on the click on the row of the table,
"contentofRow": $(this).text()
You take the content of the current row, this is what you will display :)
And then you have the controller :
class NameOfController implements AjaxControler {
public function execute($data)
{
switch($data['action']){
default :
$contentRow= $data['yourcontent'];
$res = array();
$res[] = $contentRow
return json_encode($res);
}
}
}
You can do that in OctoberCMS backend. I'll give you a quick example.
I put that in a controller _list_toolbar.htm
<button
href="javascript:;"
data-control="popup"
data-size="large"
disabled="disabled"
data-trigger-action="enable"
data-trigger=".control-list input[type=checkbox]"
data-trigger-condition="checked"
onClick="$(this).popup({ handler: 'onAssignTechnical', extraData: { checked: $('.control-list').listWidget('getChecked') } })"
href="javascript:;"
class="btn btn-default oc-icon-plus">
<?= e(trans('lilessam.maintenancesystem::lang.work_orders.assigntechnical_button')) ?>
</button>
And in the onAssignTechnical() in the controller I'll make a bootstrap modal.
public function onAssignTechnical() {
/** Check if this is even set **/
if (($checkedIds = post('checked')) && is_array($checkedIds) && count($checkedIds)) {
foreach($checkedIds as $workorder_checked_id) {
$check_work_order = \Lilessam\Maintenancesystem\Models\WorkOrder::where(['id' => $workorder_checked_id, 'assigned_to_id' => null])->count();
}
/** Check if there's more than one record checked */
if(count($checkedIds) == 1 && $check_work_order != 0):
/**Labels **/
$modal_title = Lang::get('lilessam.maintenancesystem::lang.assign_technical_title');
$assign_label = Lang::get('lilessam.maintenancesystem::lang.assign_label');
$name_label = Lang::get('lilessam.maintenancesystem::lang.assign_modal_name_label');
$action_label = Lang::get('lilessam.maintenancesystem::lang.assign_modal_action_label');
/** Getting all workers IDS by their group id 2 **/
$allWorkers_ids = DB::table('backend_users_groups')->where('user_group_id', 2)->get();
/** Workers Array **/
$workers_array = [];
// Looping to get all workers
foreach($allWorkers_ids as $worker_id) {
//Fetching the user
$worker = User::find($worker_id->user_id);
//Pushing the worker to workers' array
array_push($workers_array, [
'login' => $worker->login,
'first_name' => $worker->first_name,
'last_name' => $worker->last_name,
'id' => $worker->id,
]);
}
#setting the table header
$workers_code = '<div class="control-list list-unresponsive">
<table class="table data" data-control="rowlink">
<thead>
<tr>
<th>'.$name_label.'</th>
<th style="width: 150px"><span>'.$action_label.'</span></th>
</tr>
</thead>
<tbody>';
#Adding workers to the table
foreach($workers_array as $worker_row) {
foreach($checkedIds as $workorder_id):
$workers_code .= '<tr>
<td>
<a href="javascript:;">
'.$worker_row['first_name']." ".$worker_row['last_name'].'
</a>
</td>
<td>
<form method="post" data-request="onAssignNow">
<input type="hidden" name="workorder_id" value="'.$workorder_id.'">
<input type="hidden" name="id" value="'.$worker_row['id'].'">
<button type="submit" class="btn btn-info">'.$assign_label.'</button>
</form>
</td>
</tr>';
endforeach;
}
#Adding Table Fotter
$workers_code .= "</tbody>
</table>
</div>";
#Returning all modal
return '
<div class="control-popup modal fade in" id="content-confirmation" tabindex="-1" role="dialog" aria-hidden="false" style="display: block;">
<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">'.$modal_title.'</h4>
</div>
<div class="modal-body">
<div class="form-group textarea-field span-full" data-field-name="idea" id="Form-field-Idea-idea-groupc" style="height: 395px;
overflow-x: hidden;
margin-bottom: 20px;
overflow-y: scroll;">
<div class="qa-message-list" id="wallmessages">
'.$workers_code.'
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">X</button>
</div>
</div>
</div>
</div>
';
else:
/** Labels **/
$warning_title = Lang::get('lilessam.maintenancesystem::lang.assign_technical_warning_title');
$warning_body = Lang::get('lilessam.maintenancesystem::lang.assign_technical_warning');
#Returning all modal
return '
<div class="control-popup modal fade in" id="content-confirmation" tabindex="-1" role="dialog" aria-hidden="false" style="display: block;">
<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">'.$warning_title.'</h4>
</div>
<div class="modal-body">
<div class="form-group textarea-field span-full" data-field-name="idea" id="Form-field-Idea-idea-groupc" style="height: 395px;
overflow-x: hidden;
margin-bottom: 20px;
overflow-y: scroll;">
<div class="qa-message-list" id="wallmessages">
'.$warning_body.'
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">✖</button>
</div>
</div>
</div>
</div>
';
endif;
}
}
Excuse me for the long code but I'm sure It will help you.
Related
I create a modal and inside I insert an input field. When I write inside this input field a product name term, it must appear all the terms.
On blank page, I can see for ap (apple terms) all the apple products, no problem my ajax works fine
Now inside a page with some html element, I call a modal when there is my input fields. In this case, the ajax complexion does not work and inside the console log / result, I see my input field and not the result about my request.
I do not understand where my error below the result with a picture.
My modal call : works very fine
<!-- Link trigger modal -->
<div class="row">
<div class="col-md-12">
<div class="form-group row">
<label for="<?php echo $this->getDef('text_select_products'); ?>" class="col-5 col-form-label"><?php echo $this->getDef('text_select_products'); ?></label>
<div class="col-md-5">
<a
href="<?php echo $this->link('SelectPopUpProducts'); ?>"
data-bs-toggle="modal" data-refresh="true"
data-bs-target="#myModal"><?php echo '<h4><i class="bi bi-plus-circle" title="' . $this->getDef('icon_edit') . '"></i></h4>'; ?></a>
<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-body">
<div class="te"></div>
</div>
</div> <!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</div>
</div>
</div>
</div>
<script src="<?php echo this->link('modal_popup.js'); ?>"></script>
now my modal with the field displayed
<div class="col-md-12">
<div class="form-group row">
<label for="<?php echo $this->getDef('text_products_name') ; ?>" class="col-5 col-form-label"><?php echo $this->getDef('text_products_name') ; ?></label>
<div class="col-md-7">
<?php echo HTML::inputField('products_name', '', 'id="ajax_products_name" list="products_list" class="form-control"'); ?>
<datalist id="products_list"></datalist>
</div>
</div>
</div>
<?php $products_ajax = $this->link('ajax/products.php'); ?>
<script>
window.addEventListener("load", function(){
// Add a keyup event listener to our input element
document.getElementById('ajax_products_name').addEventListener("keyup", function(event){hinterManufacturer(event)});
// create one global XHR object
// so we can abort old requests when a new one is make
window.hinterManufacturerXHR = new XMLHttpRequest();
});
// Autocomplete for form
function hinterManufacturer(event) {
var input = event.target;
var ajax_products_name = document.getElementById('products_list'); //datalist id
// minimum number of characters before we start to generate suggestions
var min_characters = 0;
if (!isNaN(input.value) || input.value.length < min_characters ) {
return;
} else {
window.hinterManufacturerXHR.abort();
window.hinterManufacturerXHR.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse( this.responseText );
ajax_products_name.innerHTML = "";
response.forEach(function(item) {
// Create a new <option> element.
var option = document.createElement('option');
option.value = item.id + ' - ' + item.name;//get name
option.hidden = item.id; //get id
ajax_products_name.appendChild(option);
});
}
};
window.hinterManufacturerXHR.open("GET", "<?php echo $products_ajax ; ?>?q=" + input.value, true);
window.hinterManufacturerXHR.send()
}
}
</script>
Addedd js open modal
$( document ).ready(function() {
$("#myModal").on("show.bs.modal", function(e) {
const link = $(e.relatedTarget);
$(this).find(".modal-body").load(link.attr("href"));
});
});
there the screen shot of the result.
console result
Maybe the event keyup never fires because the input ajax_products_name doesn't exists until shown.bs.modal event is fired.
Try:
$("#myModal").on("shown.bs.modal", function(ev) {
document.getElementById('ajax_products_name').addEventListener("keyup", function(event) {
hinterManufacturer(event)
});
})
Let's set up an example
$('#exampleModal').on('shown.bs.modal', function() {
// $('#myInput').trigger('focus')
console.log("modal opened, *now* can addEventListener to stuff within modal")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/jquery#3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">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">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Anyway, The idea is to do the addEventListener on the ajax_products_name only after it's loaded. So given your new snippet, try this:
// instead of
$(this).find(".modal-body").load(link.attr("href"));
// do:
$(this).find(".modal-body").load(link.attr("href"), function(responseTxt, statusTxt, xhr) {
if (statusTxt == "success") {
// now that modal is opened AND content loaded
document.getElementById('ajax_products_name').addEventListener("keyup", function(event) {
hinterManufacturer(event)
})
}
});
i have a php app with 3 table, each one have multiple row with button for each row to get a form for the affected data
the idea is to give a value for the modal to have as much column as in the affected table.
until now, i tried to have one form with button fo each table, with different value, and testing it in php to use the correct table for for the column as below in the code (it's a test webpage so there is just one button, i'm just trying to open a modal manually after testing a php value ) :
<body>
<form action="" method="post">
<button type="submit" class="btn btn-primary" data-bs-toggle="modal" data-bs-
target="#CreateInfra" name="der">
Launch demo modal
</button>
</form>
<script>
function modal(){
$("#myModal").modal('show');
}
</script>
<div class="bs-example">
<!-- Modal HTML -->
<div id="myModal" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal Title</h5>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<p>This is a simple Bootstrap modal. Click the "Cancel button", "cross icon" or
"dark gray area" to close or hide the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data
dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</div>
<?php
if (isset($_POST['der'])){
$value = 1;
var_dump($value);
}
else{
$value=2;
var_dump($value);
}
if ($value == 1){
echo "<script>modal()</script>";
}
?>
</body>
the thing is , when i hit the button, i see my page loading something for maybe 0.4 second but nothing happen.
is there any way to do this or i should use something else ?
You can do something like this as long as you want it to decide on the page load
<script>
function modal(val){
let options = [];
var myModal = new bootstrap.Modal(document.getElementById('exampleModal'))
if (val == 0){
myModal.show()
}
}
</script>
<?php $val = 0; ?>
<?php echo "<script>modal(".$val.")</script>" ?>
Other than that you would have to do it through a fetch request or AJAX because php and JS can't directly talk to each other
After a button is selected on a fresh page, all information are there, but whenever another is clicked, the first info is still there and wont change until the page is refreshed.
Help me pass this will ya?
button
<?php while($b = mysqli_fetch_assoc($equery)): ?>
<button type="button" onclick="modal(<?=$b['id'];?>)" class="w3-btn w3-border" style="width: 260px; display: inline-block; margin: 9px">
<img src="">
<h3><?php echo $b['product'];?></h3>
<h5>Descritopm</h5>
<h6></h6>
</button>
<?php endwhile;?>
js:
function modal(id){
var data = {"id" : id};
jQuery.ajax({
url : <?=BASEURL;?>+'includes/modal.php',
method : "post",
data : data,
success: function(data){
jQuery('body').append(data);
jQuery('#mod').modal('show');
},
error: function(){
alert("IDK")
}
});
}
modal:
<?php
require_once '../core/init.php';
$id = $_POST['id'];
$id =(int)$id;
$sql = "SELECT * FROM aisle WHERE id = '$id'";
$result = $db->query($sql);
$product = mysqli_fetch_assoc($result);
?>
<!-- Modal -->
<?php ob_start();?>
<div id="mod" class="modal fade" role="dialog" tabindex="-1">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title w3-center"><?=$product['product'];?></h3>
</div>
<div class="modal-body">
<p><?=$product['aisle'];?></p>
<p>$<?=$product['price'];?></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<?php echo ob_get_clean();?>
The problem is here
jQuery('body').append(data);
This line will append more modal and many modals will appear on your page. You should follow this way. Create a div tag called contents_from_ajax inside body tag and then use this.
jQuery('#contents_from_ajax').html(data);
This code will remove all old modals and create a new one instead of append, and then it will work fine.
Hope this help
In my modal I am trying to put Datatables in there, the problem I'm having is that the width is incorrect, it should be the width of the modal but it is actually like this
My jQuery calling the Datatables
function getValidTags(){
var ruleID = $('.ruleID').val();
var table = $('.valid-tags').DataTable({
"ajax": {
"url": "/ajax/getValidTags.php",
"type": "POST",
"data": {
ruleID: ruleID
},
},
"columnDefs": [{
"targets": 2,
"render": function(data, type, full, meta){
return '<button class="btn btn-default btn-sm" type="button">Manage</button> <button class="btn btn-danger btn-sm">Delete</button>';
}
}]
});
}
My HTML
<!-- Modal where you will be able to add new rule -->
<div class="modal fade validation-list-modal" tabindex="-1" role="dialog" aria-labelledby="LargeModalLabel" aria-hidden="true" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-wide">
<div class="modal-content">
<div class="modal-header modal-header-custom">
<input class="ruleID" type="hidden"></input>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h4 class="modal-title modal-title-main">Create New Rule</h4>
</div>
<div class="modal-body">
<div class="topBar">
<div>
<input type="text" class="validTags inputTextStyling">
</div>
</div>
<table class="table table-striped table-condensed valid-tags">
<thead>
<tr>
<th>Tag Name</th>
<th>Autofixes</th>
<th>Manage</th>
</tr>
</thead>
<tbody class="validTagsTable">
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="saveValidTags">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I find this more appropriate solution,
First make your table width 100%
like this:
<table width="100%" id="datatable"></table>
then initialize your table
$('#datatable').DataTable();
and this this
$(document).on('shown.bs.modal', function (e) {
$.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
});
For starters try adding following class to your table element
.dataTableLayout {
table-layout:fixed;
width:100%;
}
It would be good if you could make a fiddle of your code with dummy data for solving your problem.
I dont think the accepted answer is the correct answer. There should be no need at all for altering the CSS. It could cause unexpected issues elsewhere. The problem is, that the container (the modal) not is fully established at the time the dataTable is rendered. Look at columns.adjust() :
var table = $('#example').DataTable({
initComplete: function() {
this.api().columns.adjust()
}
...
})
or
$('.modal').on('shown.bs.modal', function() {
table.columns.adjust()
})
I just added table inside div, assigned width:100%; overflow-x:auto to that div and it worked.
I want to create modal button for delete a user gets from a foreach in the html body.
The modal opens an iframe with a form. The iframe url seems like
<iframe src=<?php echo base_url('index/page/');?> witdth....
I want to pass to the iframe src the php variable contains an userid, for example:
<iframe src=<?php echo base_url('/index/page/'+username);?> witdth....
First code works fine and it shows the view but no variable passed with the second code.
I use a javascript for open the modal and get the ID variable.
The link:
<a data-toggle="modal" data-target="#myModal" data-detail-id=<?php echo $users->username; ?>>
And the js:
<script>
$(".myModal").on("click", function(e) {
var username;
e.preventDefault();
username = $(this).data("detail-id");
});
</script>
How to get the detailId to the iframe src to pass the variable to the index/page?
Thanks a lot.
EDIT---
I will post full code, the ovjective is to pass a PHP variable got in a foreach to a modal windows in that calls a iframce to other view to use the variable:
<a data-toggle="modal" data-target="#myModal" data-detail-id=<?php echo $users->username; ?>></a>
<!-- Modal -->
<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"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<script>
$(".myModal").on("click", function(e) {
var username;
e.preventDefault();
username= $(this).data("detail-id");
});
</script>
<center><iframe src=<?php echo base_url('/index/page/'+username);?> width="500" height="380" frameborder="0" allowtransparency="true"></iframe></center>
</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>
Thanks!!
You are mixing JS and PHP together:
<iframe src=<?php echo base_url('/index/page/'+username);?> width.... ( note the + )
<iframe src=<?php echo base_url('/index/page/'.$username);?> width.... ( append with . operator )
In PHP, you append with . operator
Also if you are looking for easy solution to delete smoething (ex. user) you can use something like this in your view:
<script>
function doconfirm()
{
job=confirm("Are you sure, to delete?");
if(job!=true)
{
return false;
}
}
</script>
<?php foreach ($users as $user_detail): ?>
Delete user<br>
<?php endforeach ?>
and from your user model try somethig like:
public function delete($user_id)
{
$query = $this->db->where('user_id', $user_id);
return $query = $this->db->delete('users');
}
Hope this helps.