Fail to load different content in modal Table - javascript

I have two bootstrap tables, one of them (table_compras) calls a modal (table_modal) depending on the column clicked, but i am having troubles refreshing the content rows in table, here is my code:
HTML:
<div id="modalTable" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Acumulado por Obra</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="bodyIP">
<table id="table_modal" data-detail-view="true" data-checkbox-header="true" data-search="true"
data-search-align="left" data-detail-filter="detailFilter" data-pagination="true">
<thead id="thDel">
<tr>
</tr>
</thead>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS Here i am getting the row and column index to populate the modal table but when I click on a different cell it continues getting the same data rows of the first cell. I have tried the commented lines of code but none of them give me the desired result :
var $table_compras = $('#table_compras')
var $table = $('#table_modal')
$(function() {
$('#modalTable').on('shown.bs.modal', function () {
$table.bootstrapTable('resetView');
})
$('#modalTable').on('hide.bs.modal', function (e) {
//var table = $('#table_modal').DataTable();
//table.clear();
//$("#table_modal tr").remove();
//$('#table_modal').empty();
//$(e.target).removeData('bs.modal');
$('#table_modal').detach();
//$("#table_modal").empty();
//$("#table_modal thead").remove();
//$('#modalTable').removeData();
})
});
$('#table_compras').on('click-cell.bs.table', function (field, value, row, $el)
{
buildTable2($table, 2, $el.C1, value);
$("#modalTable").modal();
//alert($el.C1+"-"+$el.C2+"-"+$el.C3+"---"+value);
});
function buildTable2($el, cells, ano, mes)
{
var columns = []
var data = []
columns.push({ field: 'C1', title: 'idObra', sortable: true})
columns.push({ field: 'C2', title: 'Nombre', sortable: true})
columns.push({ field: 'C3', title: 'Monto', sortable: true})
columns.push({ field: 'C4', title: '% Participacion', sortable: true})
{% for obra in cobros_por_obra %}
var noMes = parseInt('{{obra.1}}');
noMes = noMes + 1;
if ('{{obra.0}}' == ano && 'C' + noMes == mes)
{
//console.log('C' + noMes, mes);
row = {}
row['C1'] = '{{obra.2}}';
row['C2'] = '{{obra.3}}';
row['C3'] = '$' + Number({{obra.4}}).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
row['C4'] = Number({{obra.4}}).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
data.push(row)
}
{% endfor %}
console.log(data);
$el.bootstrapTable({
columns: columns,
data: data,
detailView: cells > 2,
onExpandRow: function (index, row, $detail) {
/* eslint no-use-before-define: ["error", { "functions": false }]*/
//console.log($detail)
expandTable($detail, cells - 1, row.C1)
}
});
}

Got it work:
Just added:
var $body = $('#bodyIP')
and change all $table for $body:
$('#table_compras').on('click-cell.bs.table', function (field, value, row, $el)
{
buildTable2($body.html('<table data-search="true" data-search-align="left" data-detail-filter="detailFilter" data-pagination="true"></table>').find('table'), 2, $el.C1, value);
$("#modalTable").modal();
//alert($el.C1+"-"+$el.C2+"-"+$el.C3+"---"+value);
});

Related

datatable scrollX not working properly in dynamic column

I'm trying to display a lot of columns dynamically from geojson feature.properties in modal. I have successfully displayed it but the problem is when I click next page scrollX didn't work as intended.
Here is my code:
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document" style="margin:auto !important;max-width:1080px !important;">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Map Attributes</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modalbody_1">
<div class="">
<table id="mapattr" class="display nowrap" style="width:100%" cellspacing="0">
<thead></thead>
<tbody></tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
var dataGSet = [];
var dataGArray;
var columnRef = [];
$.get(url, function(data) {
columnRef = [];
$("#mapattr > thead").append("<tr></tr>");
$.each(data.features, function(a, b) {
var cRow = [];
$.each(b.properties, function(key, value) {
if (a == 0) {
$("#mapattr > thead > tr").append("<td>" + key + "</td>");
columnRef.push({
title: key
})
}
cRow.push(value);
});
dataGSet.push(cRow);
});
}).done(function() {
dataGArray = JSON.parse(JSON.stringify(dataGSet));
if (!$.fn.DataTable.isDataTable('#mapattr')) {
$("#mapattr").DataTable({
dom: 'Bfrtip',
data: dataGArray,
scrollX: true,
buttons: [
'copy', 'csv', 'excel', 'pdf'
]
});
} else {
$('#mapattr').DataTable().destroy();
$('#mapattr').empty();
$("#mapattr").DataTable({
dom: 'Bfrtip',
data: dataGArray,
scrollX: true,
buttons: [
'copy', 'csv', 'excel', 'pdf'
]
});
}
});
</script>
First load:
When I click page 2:
I already tried the table-responsive suggestion from this article but the problem with the user scrolling it, the buttons, page, and search box will also be scrolled so it's a little hassle for the client when they want to navigate in another page.

How to use Vue.js to template a Modal and reuse it?

So currently I have a web app that loads a dashboard based on a SQL database and that works just fine, each of these elements have buttons and those buttons are SUPPOSED to spawn a modal with the content of the problem and you can interact with it etc.
Recently I have figured out how to use Vue.js to run a function that grabs this information and populate it on the modal. However, this modal can only be templated ONCE before it wont work again. Ex: I can click on problem 1 and problem 1's information is correct. however, if I click problem 2 after that it doesn't work
new Vue({
delimiters: ['!!!','!!!'],
el: '#problem-modal',
methods: {
close() {
this.$emit('close');
},
},
data: {
items: [],
name: null,
summary: null,
},
mounted: function () {
var self = this;
fetch('./api/problems')
.then(response => {
var response = response.json();
return response;
})
.then(json => {
var data = json.data;
var length = data.length;
for (var i = 0; i<length; i++) {
if (data[i].unique_id == button_id) {
this.name = data[i].problem_name;
this.summary = data[i].summary;
}
}
})
}
})
}
Here is my Script for the vue, assume that the problems load perfectly and this:
<div class="modal fade" id="problem-modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">!!! name !!!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
!!! summary !!!
</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>
is the modal. Any idea on how to make the modal element able to be used more than once?
Thanks!
I give you nearest illustration of your question ! I thought items is your problem list . As you mentioned you have to clicked button so that pass your clicked data to call method and grab data from items with that pass clicked data and set vue data . I hope it will be ok .. Look at my example
new Vue({
el: '#problem-modal',
methods: {
show(id) {
let cur = this.items.find(x => x.id == id);
this.name = cur.name;
this.summary = cur.summary;
}
},
data: {
items: [
{
id: 1,
name: "one",
summary: "one summary "
},
{
id: 2,
name: "two",
summary : "two summary"
}
],
name: null,
summary: null,
}
});
button {
width: 100%;
height: 20px;
margin: 10px 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="problem-modal">
<button v-for="item in items" #click="show(item.id)">{{item.id}}</button>
<div class="modal">
<h1>{{name}}</h1>
<pre>{{summary}}</pre>
</div>
</div>

modal popup from Controller .NET MVC

In my Index view.I have a Table with action link. In Action link I am passing some arguments on the base of arguments I execute query if query result is null I want to show the modal present in the Index View.
My Table is.
#foreach(var j in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => j.job_title)</td>
<td>#Html.DisplayFor(modelItem => j.job_description)</td>
<td>#Html.DisplayFor(modelItem => j.apply_before)</td>
<td>#Html.ActionLink( "Apply","applyingjobs","Student",
new {
id= #TempData["data"]
},
null
)
</td>
</tr>
}
My contoller Function which is receiving passed parameter is.
public ActionResult applyingjobs(String id)
{
SqlConnection con = new SqlConnection("xxxxxxxxxxx");
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.CommandText = "select count(*)from Users where id='" + id + "'and " + "type = " + 2 + " and exe!= null and qua!= null" ;
cmd.Connection = con;
Int32 countnamefieldadd = (Int32)cmd.ExecuteScalar();
if (countnamefieldadd == 0)
{
//here I want to show modal which is present in Index Page
}
else
{
return RedirectToAction("Index", "Student", new
{
id = id,
});
}
return RedirectToAction("Index", "Student", new
{
id = id,
});
}
My Modal Code is
<div id="modal_dialog" style="display: none">
// Modal content
</div>
Script to call Modal is
<script type="text/javascript">
$(function () {
$("#modal_dialog").dialog({
title: "Add Record",
open: function (type, data) { $(this).parent().appendTo("form"); },
modal: true
});
return false;
})
</script>
You can use Tempdata in your controller to retain the value and use it as a flag to check whether query returns records or not.
Try this. I hope it helps :)
HTML
#Html.ActionLink("Apply", "applyingjobs", "Employee")
<div>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
Script
$(document).ready(function ()
{
if ('#TempData["value"]' != "" || '#TempData["value"]' != null)
{
if ('#TempData["value"]' == "No Records")
{
$("#myModal").modal('show');
}
else {
$("#myModal").modal('hide');
}
}
});
Controller
public ActionResult applyingjobs()
{
var c = Repository.SelectAll().ToList();
if (c.Count() > 0)
{
return RedirectToAction("Create");
}
else
{
TempData["value"] = "No Records";
return RedirectToAction("Create");
}
}

Uncaught Error: You cannot apply bindings multiple times to the same element

How could I combine the two models which i have kept for two different purpose. One is to for file upload and the other is for render data from different object.Below is the respective html and JS i tried.
HTML section
<div class="well" data-bind="fileDrag: fileData">
<div class="form-group row">
<div class="col-md-6">
<img style="height: 125px;" class="img-rounded thumb" data-bind="attr: { src: fileData().dataURL }, visible: fileData().dataURL">
<div data-bind="ifnot: fileData().dataURL">
<label class="drag-label">Drag file here</label>
</div>
</div>
<div class="col-md-6">
<input type="file" data-bind="fileInput: fileData, customFileInput: {
buttonClass: 'btn btn-success',
fileNameClass: 'disabled form-control',
onClear: onClear,
}" accept="application/pdf,image/*">
</div>
</div>
</div>
<button class="btn btn-default" data-bind="click: debug">Upload</button>
</div>
<div id="notification" style="display: none;">
<span class="dismiss"><a title="dismiss this notification">X</a></span>
</div>
<!-- Collapsible Panels - START -->
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Plan Details</h3>
</div>
<div class="panel-body">
<span class="glyphicon glyphicon-plus clickable" id="addPlanBtn"></span>
<span class="glyphicon glyphicon-remove clickable" id="removePlanBtn"></span>
<span class="glyphicon glyphicon-edit clickable" id="editPlanBtn"></span>
<table id="docsDataTable" class="table table-striped display" width="100%">
<thead>
<tr>
<th></th>
<th>Contract Document ID</th>
<th>Contract ID</th>
<th>Document Name</th>
<th>File Path</th>
<th>Comments</th>
</tr>
</thead>
</table>
<div class="modal fade" id="notificationDialog" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" \>×</button>
<h4 class="modal-title">Notification</h4>
</div>
<div class="modal-body" id="notificationBody">
</div>
<div class = "modal-footer">
<button type = "button" class = "btn btn-primary" data-dismiss = "modal">
Ok
</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="confirmBox" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" \>×</button>
<h4 class="modal-title">Confirmation</h4>
</div>
<div class="modal-body" id="confirmBody">
Selected rows will be made inactive.
</div>
<div class = "modal-footer">
<button type = "button" class = "btn btn-default" data-dismiss = "modal" id="confirmNoBtn">
Cancel
</button>
<button type = "button" class = "btn btn-primary" data-dismiss = "modal" id="confirmYesBtn">
Ok
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Javascript section to bind the data
var dataset;
var docsModel;
var docsTable;
var vasTypes;
$(function(){
var viewModel = {};
viewModel.fileData = ko.observable({
dataURL: ko.observable(),
// base64String: ko.observable(),
});
viewModel.onClear = function(fileData){
if(confirm('Are you sure?')){
fileData.clear && fileData.clear();
}
};
viewModel.debug = function(){
window.viewModel = viewModel;
//console.log(ko.toJSON(viewModel));
fileUpload(viewModel);
debugger;
};
ko.applyBindings(viewModel);
});
$(document).ready(function(){
docsModel = new $.cordys.model({
context: document.getElementById("addPanelForm"),
objectName: "CONTRACT_DOCUMENT",
fields: ["CONTRACT_DOCUMENT_ID" , "CONTRACT_ID" , "DOCUMENT_NAME" , "FILE_PATH" , "COMMENTS"],
defaults: {
namespace: "http://services.vw.com/lpms/1.0/wsapp"
},/*
update: {
method: "UpdatePlanVas"
},*/
read: {
method: "GetContractDocumentObjectsForContractId",
parameters: {
CONTRACT_ID: "CONTRACT_1000"
},
}
});
GetContractDocumentObjectsForContractId();
docsTable = $('#docsDataTable').DataTable({
data: dataset,
columnDefs: [ {
orderable: false,
className: 'select-checkbox',
defaultContent: "",
targets: 0},
{ data: "CONTRACT_DOCUMENT_ID",
targets: 1,
visible: false},
{ data: "CONTRACT_ID",
targets: 2},
{ data: "DOCUMENT_NAME",
targets: 3},
{ data: "COMMENTS",
targets: 5},
{ data: "FILE_PATH",
targets: 4}],
select: {
style: 'multi',
selector: 'td:first-child'
},
order: [[ 1, 'asc' ]],
"searching": false,
"lengthChange": false
});
});
function fileUpload(data){
dataObject=ko.toJS(viewModel);
fileName=dataObject.fileData.file.name;
fileContent=dataObject.fileData.dataURL.split(',')[1];
$.cordys.ajax({
method: "WriteFile",
parameters: {
filename: fileName,
encoded: "true",
data:fileContent
},
namespace:"http://schemas.cordys.com/1.0/ac/FileConnector",
dataType: "* json",
async: false,
success: function(e){
$.notify("Yeah ! File Uploaded", "success");
}
});
}
You're getting the error
You cannot apply bindings multiple times to the same element
Because Knockout only permits one view-model to be bound to a DOM element.
In your case, you need to somehow combine the two view-models into one. While you could simply add the properties from one view-model into the other, perhaps creating a third view-model with a new name so you can continue using the original form of these view-models elsewhere, my suggestion would be to create a new super view-model, and reference the two existing view-models as properties on this new view-model.
At this point I would normally create an example from the code in the OP but in this case, as #Jeroen has pointed out, it's rather difficult to make out what's going on in the OP. As far as I can see, there's only one view-model in there while your question revolves around having two view-models. So the following example is unfortunately very generic.
var ViewModel1 = function() {
var self = this;
self.obs1_1 = ko.observable();
self.obs1_2 = ko.observableArray([]);
// some initialisation stuff
},
ViewModel2 = function() {
var self = this;
self.obs2_1 = ko.observable();
self.obs2_2 = ko.observableArray([]);
// some initialisation stuff
},
SuperViewModel = function() {
var self = this;
self.vm1 = new ViewModel1();
self.vm2 = new ViewModel2();
// some initialisation stuff
};
You would then instantiate and data-bind SuperViewModel, and reference the observables like so
<input type="text" data-bind="textInput: vm1.obs1_1" />
<div data-bind="foreach: vm1.obs1_2">
<span data-bind="html: $data"></span>
</div>
or to make typing a little bit easier
<!-- ko with: vm1 -->
<input type="text" data-bind="textInput: obs1_1" /> <!-- this time without "vm1." -->
<div data-bind="foreach: obs1_2"> <!-- this time without "vm1." -->
<span data-bind="html: $data"></span>
</div>
<!-- /ko -->
You now have a single view-model, SuperViewModel, referencing your unchanged existing view-models. This solution allows you to leave existing JavaScript and views while offering an easy method of data-binding the functionality of multiple view-models inside a single view-model.
It's technically possible to achieve a similar result by doing some referencing at the prototype level, but that could quickly cause complications and the only advantage would be saving you from typing the name of a property.

Bootstrap Modal on clicking a link on UI Grid

In my UI Grid here are the Column Defs in my myController.js file:
{ field: 'trans_typ_dsc', headerTooltip: 'Transaction Type Description', displayName: 'Transaction Type Description', cellTemplate: '<div class="wordwrap">{{COL_FIELD}}</div>' },
{ field: 'trans_stat', displayName: 'Transaction Status' },
{ field: 'sub_trans_actn_typ', displayName: 'Sub Transaction Action Type', cellTemplate: '<div class="wordwrap">{{COL_FIELD}}</div>' , visible : false },
{ field: 'case_key', displayName: 'Case Key', visible: true, celltemplate: '<a class="text-center" ng-href="#" ng-click="grid.appScope.setAssociateCaseModal(row)">{{COL_FIELD}}</a>' },
{ field: 'approved_by', displayName: 'Approved By', visible: false }
Here on clicking the case_key link a UI Bootstrap modal should pop up .
How to do that ?
I know in a html file using a button click it is something like :
<h3>Search Transaction</h3>
<div style="float: right; margin-top: -35px"><button type="button" class="btn btn-default" data-toggle="modal" data-target="#recentSearchesModal">Recent Searches</button></div>
</div>
<div class="modal fade" id="recentSearchesModal" role="dialog">
<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">Recent Searches</h4>
</div>
<div class="modal-body">
<div class="panel panel-default">
<div class="menu_simple" ng-repeat="obj in CaseRecentSearches" style="padding:8px;">
<ul>
<li>
{{obj | placeholderfunc}}
</li>
</ul>
</div>
<!-- /.panel-body -->
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
But here the click event is my controller.js file then how to get the modal opened ?
You need to modify the field's cellTemplate and then call grid.appScope.openModal(). openModal should live in your main controller under $scope.openModal. Do it like this:
Your template:
var myTemplate = "<a href='#' ng-click='grid.appScope.openModal($event, row)'>{{ row.entity.myFieldName }}</a>";
Use the template in gridOptions.
$scope.gridOptions = {
columnDefs: [{
field: 'myFieldName',
displayName: 'My Field Name',
cellTemplate: myTemplate;
}]
};
Function to call modal:
$scope.openModal = function (e, row) {
//in here, you can access the event object and row object
var myEvent = e;
var myRow = row;
//this is how you open a modal
var modalInstance = $uibModal.open({
templateUrl: '/path/to/modalTemplate.html',
controller: MyModalCtrl,
backdrop: 'static'
//disable the keyboard
//keyboard: false,
resolve {
//pass variables to the MyModalCtrl here
event: function() { return myEvent; },
row: function() { return myRow; }
}
});
//call the modal to open, then decide what to do with the promise
modalInstance.result.then(function() {
//blah blah the user clicked okay
},function(){
//blah blah the user clicked cancel
})
}

Categories

Resources