Want to perform Edit in popup, I have code but its not working
here is my script
$("#mylink").click(function(e) {
var count = 0;
var $dialog = $("<div id='divCreateTask'></div>");
var Id = $(this).data(e);//
url: "TaskTimeSheet/EditTaskPopUp/" + Id //
var url = "EditTaskUrl" + id;var url = '#Url.Action("EditTaskPopUp", "TaskTimeSheet")';
url += '/?Id=' +Id; $("#tab1").load(url);
$dialog.empty();$dialog.dialog({
autoOpen: true,
width: 600,
height: 650,
resizable: false,
modal: true,
open: function (event, ui) {
$(this).load(url);
},
buttons: {
"Cancel": function () {
$(this).dialog("close"); }
});
} });
#Html.ActionLink("Edit", "TaskTimeSheet", new {id="mylink", param = dr["id"].ToString() })
From this link i have to pass id .....
This all is loaded in table Table Each row Have Edit Button ....now ho to pass Id to the querY,..
use an ajax call
$('.btnSubmit').on('click', function(){
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: 'post',
cache: false,
async: true,
data: { id: "ID" },
success: function(result){
$('.divContent').html(result);
}
});
});
your controller action would be something like
[HttpPost]
public PartialViewResult Action(int id){
var Model = //query the database
return PartialView("_PartialView", Model);
}
This will call your controller, return a partial view and put it into a container with class "divContent". Then you can run your dialog code to pop up the container.
row id update
to get the id of a table row I use this in the row click event
$(this).closest('tr').find('.ID').val(); // or .html() if you have put it in the cell itself
this will get the row that you are on and then find a cell in that row with class ID. Hopefully this helps.
Related
I've been struggling for a few days now, trying to get a single dropdown to filter my table. Upon selection of the eraId, the columns should be refreshed to only show the columns of the selected eraId.
This is how my tables looks like:
I've read a lot of examples on Datatables website or forums but I can't seem to find something working.
I have managed to create a dropdown menu containing the different EraIds as filter (I have simplified the example below with only 3 eraIds) but after selecting an entry in the dropdown, the table gets empty and the column list is not refreshed.
I think the problem is that I first retrieve the columns names, based on the eraId and then draw the table accordingly, displaying only the resources from the specific eraId. I have tried several things but did not manage.
Ideally I should callback getPlayerResourceTable with the selected eraId or update the column list with the resources on the selected eraId.
Javascript:
var columns = [];
function getPlayerResourceTable($selectedEraId) {
$.ajax({
type: "POST",
url: "./graphs.php",
data: { call_function : 'getResourceTableColumns', eraId: $selectedEraId},
success: function (data) {
data = JSON.parse(data);
columnNames = Object.keys(data.data);
for (var i in data.data) {
columns.push({data: data.data[i],
title: data.data[i]});
}
$('#playerResourceTable').DataTable( {
processing: true,
serverSide: false,
filter: true,
columns: columns,
ajax: {
url: './graphs.php',
type: 'POST',
data: { call_function: 'playerResourceTable', column_fields : data.data, eraId: $selectedEraId}
},
initComplete: function () {
this.api().columns( 0 ).every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( $("#playerResourceTablesWrapper .dataTables_filter"))
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column.search( this.value ).draw();
} );
select.append( '<option value="1">Era 1</option>' )
select.append( '<option value="2">Era 2</option>' )
select.append( '<option value="3">Era 3</option>' )
} );
}
});
}
});
}
$(document).ready(function() {
$selectedEraId = 1;
getPlayerResourceTable($selectedEraId);
} );
PHP:
getResourceTableColumns returns the column list with query similar to SELECT columnName FROM ages WHERE eraId = ?
playerResourceTable returns the resources for each column (type of resource) with query similar to SELECT ".$field_list." FROM user_resources
I also thought of removing WHERE eraId = ? in my MySQL query and filtering the columns on the client side but no luck either.
I eventually ended up separating both functions and destroying/re-creating the table when changing Era.
function getColumns($selectedEraId) {
var columns = [];
$.ajax({
type: "POST",
url: "./graphs.php",
data: { call_function : 'getResourceTableColumns', eraId: $selectedEraId},
success: function (data) {
data = JSON.parse(data);
for (var i in data.data) {
columns.push({data: data.data[i],
title: data.data[i]});
}
if ( $.fn.dataTable.isDataTable( '#playerResourceTable' ) ) { // If the table already exists, detroy it before creating it again
$('#playerResourceTable').DataTable().destroy();
}
getPlayerResourceTable($selectedEraId, columns); // Will recreate the table with the new columns
}
});
}
function getPlayerResourceTable($selectedEraId, columns_to_show) {
$city_id = 91;
$playerResourceTable = $('#playerResourceTable').DataTable( {
processing: true,
serverSide: false,
filter: true,
columns: columns_to_show,
ajax: {
url: './graphs.php',
type: 'POST',
data: { call_function: 'playerResourceTable', column_fields : columns_to_show, city_id : parseInt($city_id)}
},
initComplete: function () {
this.api().columns( 0 ).every( function () {
var column = this;
var select = $('<select id="selectEraId" ><option value=""></option></select>')
.appendTo( $("#playerResourceTablesWrapper .dataTables_filter"))
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column.search( this.value ).draw();
} );
dropdown_string = getEraDropdown($selectedEraId);
} );
$('#selectEraId').on('change', function() {
$selectedEraId = this.value;
columns_to_show = getColumns($selectedEraId);
});
}
});
}
I made a custom model and i have a one2many field where i click on "add new line" then "search more" to look for the item i want to add just like the picture below
What I want is to click on "add new line", and the whole products page appear without having to go throw the previous process
You can extend ListRenderer and override _onAddRecord to open a search more view using a condition in context.
The following code adds a new widget to open search more... link and select many records.
odoo.define('stack_overflow.open_list_view', function (require) {
"use strict";
var pyUtils = require('web.py_utils');
var dialogs = require('web.view_dialogs');
var core = require('web.core');
var _t = core._t;
var fieldRegistry = require('web.field_registry');
var ListRenderer = require('web.ListRenderer');
var AddManyFieldOne2ManyRenderer = ListRenderer.extend({
/**
* It will returns the first visible widget that is editable
*
* #private
* #returns {Class} Widget returns first widget
*/
_getFirstWidget: function () {
var record = this.state.data[this.currentRow];
var recordWidgets = this.allFieldWidgets[record.id];
var firstWidget = _.chain(recordWidgets).filter(function (widget) {
var isLast =
widget.$el.is(':visible') &&
(
widget.$('input').length > 0 || widget.tagName === 'input' ||
widget.$('textarea').length > 0 || widget.tagName === 'textarea'
) &&
!widget.$el.hasClass('o_readonly_modifier');
return isLast;
}).first().value();
return firstWidget;
},
add_rows: function (lines, field_name) {
var self = this;
if (lines.length > 0) {
self.trigger_up('add_record', {
context: [{ [field_name]: lines[0] }],
forceEditable: "bottom",
allowWarning: true,
onSuccess: function () {
self.unselectRow();
lines.shift(); // Remove the first element after adding a line
self.add_rows(lines, field_name);
}
});
}
},
_onAddRecord: function (ev) {
// we don't want the browser to navigate to a the # url
ev.preventDefault();
// we don't want the click to cause other effects, such as unselecting
// the row that we are creating, because it counts as a click on a tr
ev.stopPropagation();
var self = this;
// but we do want to unselect current row
this.unselectRow().then(function () {
var context = ev.currentTarget.dataset.context;
if (context && pyUtils.py_eval(context).open_list_view) {
// trigger add_record to get field name and model
// you do not need to trigger add_record if you pass the field name and model in context
self.trigger_up('add_record', {
context: [{}],
onSuccess: function () {
var widget = self._getFirstWidget();
var field_name = 'default_' + widget.name;
var model = widget.field.relation;
self.unselectRow();
self._rpc({
model: model,
method: 'search',
args: [[]],
}).then(
function (result) {
return new dialogs.SelectCreateDialog(self, _.extend({}, self.nodeOptions, {
res_model: model,
context: context,
title: _t("Search: add lines"),
initial_ids: result,
initial_view: 'search',
disable_multiple_selection: false,
no_create: !self.can_create,
on_selected: function (records) {
self.add_rows(records.map(product => product.id), field_name);
}
})).open();
});
}
});
} else {
self.trigger_up('add_record', { context: context && [context] });
}
});
},
});
var AddManyFieldOne2Many = fieldRegistry.map.section_and_note_one2many.extend({
/**
* We want to use our custom renderer for the list.
*
* #override
*/
_getRenderer: function () {
if (this.view.arch.tag === 'tree') {
return AddManyFieldOne2ManyRenderer;
}
return this._super.apply(this, arguments);
},
});
fieldRegistry.add('add_many_one2many', AddManyFieldOne2Many);
});
To use it define the widget attribute of the one2Many field to
<field name="field_name" widget="add_many_one2many"...
And add the following option to the tree view of the one2Many field
<create string="Open list view" context="{'open_list_view': True}"/>
Salam Ahmed
you can create a function that take you directly to product page and assigned to a button like in wizard's when you click to create a new view or get data from another view or page
i try to change the navbar properties on a jqgrid in a callback function without succes.
The grid is display afeter user is chosing a period. Depend on either the period is open or close user can or cannot edit, add, delete rows. So the navbar need to change properties dynamically.
My code look like that:
$('#mygrid').jqGrid({
// some properties of my grid that works fine
pager : '#gridpager'
});
$("#mygrid").bind("jqGridLoadComplete",function(){
$.ajax({
url: 'checkifperiodopen.php',
data: {
$("#period").val()
},
success: function(data){
if(period==='open'){
jQuery("#mygrid").jqGrid('navGrid','#gridpager',{add:false,edit:false,del:true,search:true,refresh:true});
}
if(period==='close'){
jQuery("#mygrid").jqGrid('navGrid','#gridpager',{add:true,edit:true,del:true,search:true,refresh:true});
}
}
});
});
$('#validChossenPeriod').click(function () {
ajax call to get data on choosen period
success:function(data){
$("#mygrid").jqGrid('clearGridData');
$("#mygrid").jqGrid('setGridParam', { datatype: 'local'});
$("#mygrid").jqGrid('setGridParam', { data: data});
$("#mygrid").trigger('reloadGrid');
}
});
I finally found the answer by show or hide the div that include the navgrid button:
grid = $("#mygrid");
gid = $.jgrid.jqID(grid[0].id);
var $tdadd = $('#add_' + gid);
var $tdedit = $('#edit_' + gid);
var $tddel = $('#del_' + gid);
$("#mygrid").jqGrid('navGrid','#gridpager',{add:true,edit:true,del:true,search:true,refresh:true});
condition if false =
$tdadd.hide();
$tdedit.hide();
$tddel.hide();
if true =
$tdadd.show();
$tdedit.show();
$tddel.show();
Why so complex? There is a other clear way to do this
var view_buttons = true;
if(condition_to_hide) {
view_buttons = false;
}
$("#mygrid").jqGrid('navGrid','#gridpager', { add:view_buttons, edit:view_buttons, del:view_buttons, search:true, refresh:true});
I have a table that shows a pop-up when the first cell is clicked like this:
$('#tblAllUsers tbody').on('click', 'td', function () {
var visIdx = $(this).index();
if (visIdx != 0) {
return false;
}
var par = this.parentNode.parentNode.id;
var oTable = $("#tblAllUsers").dataTable();
var rowIndex = $(this).closest('tr').index();
var aPos = oTable.fnGetPosition(this);
var aData = oTable.fnGetData(aPos[0]);
var name = aData[1];
if (name != '') {
GetUser(name, rowIndex, "#tblAllUsers");
}
else {
ErrorDialog("#MessageDialog", "#lblError", "The User ID is blank in that row.", "No User ID");
return false;
}
});
The pop-up allows the user to modify fields and save it, close the dialog and then return to the grid. If the dialog is canceled, data not saved, the scroll is maintained. But if the data is saved, and I am not reloading the table, the table moves to the top. The AJAX update function is within the pop-up:
$.ajax({
type: 'POST',
data: $("#formUserModification").serializeArray(),
url: '#Url.Action("UpdateUser")',
success: function (data) {
if (data.Errors === 'ERROR') {
ErrorDialog("#MessageDialog", "#lblError", "There was an error encountered in modifying the user, please try again later.", "Error");
}
else {
updateTable(data);
}
$("#divDetails").dialog('close');
},
beforeSend: function () {
$("#divOverlay").show();
},
complete: function () {
$("#divOverlay").hide();
}
});
The update function simply loads the row:
function updateTable(data) {
var tab = $("#tblAllUsers").dataTable();
tab.fnUpdate(data.LastName + ', ' + data.FirstName, data.RowIndex, 0);
tab.fnUpdate(data.ID, data.RowIndex, 2);
tab.fnUpdate(data.LocationText, data.RowIndex, 3);
tab.fnUpdate(data.SiteText, data.RowIndex, 4);
}
Is there a way with this setup to keep the scroll position?
I accomplished my goal by doing this:
Define a variable:
var scrollToPos;
In the dialog definition set the value when it is opened and place the scroll bar when it is closed:
$("#divAllUsersDetail").dialog({
autoOpen: false,
width: '90%',
resizable: false,
draggable: false,
title: 'Details',
position: { my: 'top', at: 'top+100' },
modal: true,
closeOnEscape: false,
open: function() {
scrollToPos = $("#divAllUsers").find(".dataTables_scrollBody").scrollTop();
},
close: function () {
$("#divAllUsers").find(".dataTables_scrollBody").scrollTop(scrollToPos);
},
show: {
effect: 'drop', direction: 'up'
},
hide: {
effect: 'fade', duration: 200
},
buttons: {
"Cancel": function () {
$(this).dialog("close");
}
}
}).prev("ui-dialog-titlebar").css("cursor", "default");
This works famously.
I need help.
I have grid with toolbar when i create new grid with data (open window of create via button in toolbar)
the new row not displayed only after reloading the page i see the new row.
Thank you.
this is store:
var writer = new Ext.data.JsonWriter({
type: 'json',
encode: false,
listful: true,
writeAllFields: true,
returnJson: true
});
var reader = new Ext.data.JsonReader({
totalProperty: 'total',
successProperty: 'success',
idProperty: 'Id',
root: 'Data',
messageProperty: 'message'
});
var proxy = new Ext.data.HttpProxy({
reader: reader,
writer: writer,
type: 'ajax',
api: {
read: '/Item/Get',
create: '/Cart/CreateCart',
update: '/Cart/CreateCart',
destroy: '/Cart/CreateCart',
add: '/Cart/CreateCart'
},
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
});
Ext.define('ExtMVC.store.Items', {
extend: 'Ext.data.Store',
model: 'ExtMVC.model.Item',
autoLoad: true,
paramsAsHash: true,
autoSync: true,
proxy: proxy
});
this is methode to create:
additem: function (button) {
var win = button.up('window'),
form = win.down('form'),
values = form.getValues();
Ext.Ajax.request({
url: 'Item/CreateItem',
params: values,
success: function (response, options) {
var data = Ext.decode(response.responseText);
if (data.success) {
Ext.Msg.alert('Create', data.message);
}
else {
Ext.Msg.alert('Create', 'Creating is faild');
}
win.close();
}
});
}
In your function addItem you add the data (record) to your database, you don't add this record to the store (that's bound to the grid).
Because you save the data to your database it's loaded to the store (and shown in the grid) after you reload.
You can add the record to your store as follows:
var win = button.up('window'),
form = win.down('form'),
values = form.getValues();
var store = *referenceToYourGrid*.getStore();
var model = Ext.ModelMgr.getModel(store.model);
var record = model.create();
record.set(values);
store.add(record);
Now it should show in your store. Instead of store.add you could you store.insert(0, record) to insert the record in a specific place. In this case as first record (position: 0). Store.add will place the record on the end of the store (and grid). You could store.sync() to save the record to the database instead of the Ajax request. You have the api property of the proxy allready configured.