How to upload image to jqgrid column - jqgrid

jqGrid shows images in column using colmodel below. Images are stored in database in binary column.
How to allow users to upload image to existing and new row ?
colModel: [{"name":"ProductId","edittype":"custom","editoptions":{"custom_element":function(value, options) { return combobox_element(value, options)}
,"custom_value":combobox_value
},"editable":true,"width":112,"fixed":true,"hidden":false},
{"name":"Image","formatter":function( cell, options,row) {
return "<img src='Grid/GetImage?image=" + row[0] + "'/>"
}
}]
public FileContentResult GetImage(string image) {
byte[] image = ....
return File(image, "image/jpg");
}

The problem is jQgrid uses ajax, and the image upload requires a File Dialog, and File Dialogs don't work over ajax.
I got around this by not doing inline editing (as is done on the other grids), but I redirected to a form on another page when the user clicks on the inline edit button. One form for edit and another for add. These forms then have the file dialog, as well as the other form elements for editing/adding the row. When the form is submitted, the user is redirected back to the grid.
In most grids I use formatter: 'actions', as well as navgrid. But for the grid with the images it did it like this:
For the navgrid, I use the following code:
jQuery("#grid1").jqGrid('navGrid', '#pager1',
{ search: false, editfunc: goEdit, addfunc: goAdd }, //options
It calls functions goEdit(), etc, which look like this:
function goEdit(rowid) {
window.location = "/controllerName/EditFormName/" + rowid;
}
This column replaces the column that is usually the formatter: 'actions' column:
{ name: 'RowActions', width: 60, fixed: true, sortable: false, resize: false, formatter: formatCustomED },
formatCustomED function makes the inline edit images, and makes them redirect:
formatCustomED = function (el, cellval, opts) {
return "<div style=\"float: left; cursor: pointer;padding-left:8px\" class=\"ui-pg-div ui-inline-edit\" onmouseover=\"jQuery(this).addClass('ui-state-hover');\" title=\"Edit selected row\" onmouseout=\"jQuery(this).removeClass('ui-state-hover')\" onclick='goEdit(" + opts[0] + ")'><span class=\"ui-icon ui-icon-pencil\"></span></div><div style=\"margin-left: 5px; float: left;\" class=\"ui-pg-div ui-inline-del\" onmouseover=\"jQuery(this).addClass('ui-state-hover');\" title=\"Delete selected row\" onmouseout=\"jQuery(this).removeClass('ui-state-hover');\" onclick=\"doDelete("+opts[0]+")\"><span class=\"ui-icon ui-icon-trash\"></span></div>";
}

Related

Has a Kendo UI Widget been applied to a DOM object (to avoid duplication)

This function display the dialog. While opening, it creates also a kendo editor. The problem is that, when the dialog is closed then reopened, the editor is duplicated.
function openChangeProjectStatusPopup(popupElementName) {
$("#" + popupElementName).dialog({
width: 700,
height: 400,
draggable: false,
resizable: false,
modal: true,
open: function () {
$('#changePhaseTextArea').kendoEditor();
},
close: function () {
}
});
}
To avoid duplication, I should do a check like this
if(changePhaseTextArea is a not already a kendoeditor){
$('#changePhaseTextArea').kendoEditor();
}
I've checked the kendo websites, I can't find where one can check the type of the object.
Thanks for helping
The easiest way is asking for the widget object that is referenced via data("kendoEditor") or in general data("kendo_<String>") where <String> is the name of the widget.
For your code example:
var elem = $("#changePhaseTextArea");
if (!elem.data("kendoEditor")) {
$('#changePhaseTextArea').kendoEditor();
}

Dynamically change a column's editable property with select box

I am using form editing. I would like to disable certain fields in my add and edit forms based on the selection from a drop down box. What event is best to use to trigger this? I have attempted using dataEvents:
{ name:'type_cd',
edittype:'select',
editoptions:{
dataUrl:'functions.php',
dataEvents:[{
type:'change',
fn: function(e){
$(this).setColProp('cntrct_id',{
editoptions:{editable:false}
});
}
}]
}
},
This has no visible effect on my form fields, but I know that it's being reached because I can get an alert message from it if I put one in.
EDIT
If I submit the form, the next time I open it, the column that was set to editable:false will not appear. This is a step in the right direction, BUT I want it to immediately be uneditable. Really, I would like it to be visible, but disabled (i.e. disabled:true)
First of all dataEvents allows you to register callbacks on elements of edit elements. Inside of callbacks this will be initialized to the DOM element which will be bound. So $(this) inside of change handler it will be wrapper on <select> element and not on the grid. The usage of $(this).setColProp will be incorrect.
To disable some input field in Add/Edit form you can use the fact that all input elements get the same id like the value of name property on the corresponding column in colModel. So if you need to disable input of cntrct_id you can set disabled property to true on the element with id="cntrct_id"
{
name: 'type_cd',
edittype: 'select',
editoptions: {
dataUrl: 'functions.php',
dataEvents: [{
type: 'change',
fn: function (e) {
// disable input/select field for column 'cntrct_id'
// in the edit form
$("#cntrct_id").prop("disabled", true);
}
}]
}
}
It's important to understand that editoptions will be used for any existing editing modes (form editing, inline editing and cell editing). If you want to write the code of dataEvents which supports all editing modes you have to detect editing mode and use a little other ids of editing fields. The code (not tested) can be about as below
{
name: 'type_cd',
edittype: 'select',
editoptions: {
dataUrl: 'functions.php',
dataEvents: [{
type: 'change',
fn: function (e) {
var $this = $(e.target), $td, rowid;
// disable input/select field for column 'cntrct_id'
if ($this.hasClass("FormElement")) {
// form editing
$("#cntrct_id").prop("disabled", true);
} else {
$td = $this.closest("td");
if ($td.hasClass("edit-cell") {
// cell editing
// we don't need to disable $("#cntrct_id")
// because ONLY ONE CELL are edited in cell editing mode
} else {
// inline editing
rowid = $td.closest("tr.jqgrow").attr("id");
if (rowid) {
$("#" + $.jgrid.jqID(rowid) + "_cntrct_id")
.prop("disabled", true);
}
}
}
}
}]
}
}
The last remark. If you still use old version of jQuery (before jQuery 1.6) which don't support prop method you have to use attr instead.
#Oleg: This is working(could get the alert messages) but its not disabling the field.
Should the form field require any special values?

jqgrid group header not showing ampersand character in IE 7/8

I am using jqgrid to show dynamic data in it, my sql stored procedure returns some data as "T & E". I am displaying this data in group header, i can only see "T" in the group header the rest of the data is trimmed down in IE 7/8. The same thing when i run it in Firefox it show correctly as "T & E". Please tell me the solution for this problem, any help would be appreciated.
I have tried the autoencode property setting it to true, but it did not work,
I have kept the meta tag character encoding utf-8 in the aspx file.
I had similar issue while editing . This link helped me to attain what i wanted with some tweaks.
My system config.
Win 7 with IE8
While editing, the text after the '&' was lost. Eg: If we had text like 'a&a' only 'a' used to show up in the grid and get saved eventually.
The custom formatter how ever did the trick for me.
//In col Model
//Assuming description is one of your column in the jqGrid
//Note the formatter , this is the custom formatter which does the magic for us in this case.
{ name: 'Description', index: 'Description', align: "center", sorttype: 'text', sortable: true, resizable: false, editable: editGrids, formatter: formatTextDisplay,unformat:unformatTextDisplay}
//Formatter code
var formatTextDisplay = function (cellval, opts, action) {
if (cellval) {
return $.jgrid.htmlEncode(cellval);
};
return "";
}
//Un formatter code, in case you want to read through the text in its original state from the grid for processing in the javascript file.
var unformatTextDisplay = function (cellval, opts, action) {
if (cellval) {
return $.jgrid.htmlDecode(cellval);
};
return "";
}

jqGrid inline edit: odd behavior with an autocomplete column

I have a jqGrid (using inline editing) with an autocomplete column. When the user selects a value from the autocomplete column, an event handler sets a value on another column, and also sets the value on the autocomplete column to something other than the label returned from the autocomplete source. The two column definitions (complete jsFiddle example here):
{
name: 'cartoonId',
index: 'cartoonId',
width: 90,
editable: false},
{
name: 'cartoon',
index: 'cartoon',
width: 200,
editable: true,
edittype: 'text',
editoptions: {
dataInit: function(elem) {
$(elem).autocomplete({
source: autocompleteSource,
select: function(event, ui){
var rowId = $("#inlineGrid").jqGrid('getGridParam', 'selrow');
if(ui.item){
$("#inlineGrid").jqGrid('setCell', rowId, 'cartoonId', ui.item.CartoonId);
$("#inlineGrid").jqGrid('setCell', rowId, 'cartoon', ui.item.Name);
}
return false;
}
});
}
}},
The problem is that whenever the user selects a value from the autocomplete, either by clicking it or using arrows and pressing the tab key, that cell is no longer editable, and the grid appears to lose focus entirely. If I comment out the line that sets the cartoon cell value, it behaves normally. Is there any way I can get around this behavior? I need the entire row to remain in edit mode, including the cartoon column, until the user completes the edit.
jqGrid 4.4.1
jQuery 1.7.2
jQuery UI 1.8.18
You should rename Name property of the items from the autocompleteSource to value because jQuery UI Autocomplete examines the label and value per default (see the documentation).
You can't use setCell of the 'cartoon' column which is currently in the editing mode. You should remove return false; from select callback too. So the code could looks about the following
dataInit: function (elem) {
$(elem).autocomplete({
source: autocompleteSource,
select: function (event, ui) {
var rowId = $("#inlineGrid").jqGrid('getGridParam', 'selrow');
if (ui.item) {
$("#inlineGrid").jqGrid('setCell', rowId, 'cartoonId',
ui.item.CartoonId);
}
}
});
}
See http://jsfiddle.net/27dLM/38/

Add a hyperlink in one of the columns in JQGrid and clicking on Hyperlink should open a new window

I have a jqgrid with certain columns and I need hyperlink in one of the columns, clicking on the hyperlink should open a new window, basically call a window.open().
Also when I call the window.open(), I need the hyperlink column value.
Please provide me with some sample code.Anyhelp would be highly appreciated.
Thanks
Oleg, I tried the below code and it is throwing error "object expected" in load().
{name:'FileName', FileName:'price', width:60, align:"center", formatter:returnMyLink}
function returnMyLink(cellValue, options, rowdata)
{
return "<a href='javascript:load();'>Open Window</a>";
}
function load()
{
var guid = 'CEF9C407-2500-4619-95E3-8E6227B65954';
window.open ('/irj/servlet/prt/portal/prtroot/com.medline.medpack.ExcelViewerPL.ExcelViewer?report=CustomerBenefit&reportId='+guid );
}
I did try the document.delegate to capture the a href event.
$(document).delegate('#CustomerSavingsView .jqgrow td a[href="#"]', 'click',function()
{
alert('test');
}
I was not able to capture this event either.
Sorry Im new to Jquery. Please correct me if Im wrong.
Thanks
This is how I solved it. In the grid complete event added the following code.
hl = "<a href='#Test' target='_blank' id='hlink"+cl+"'>Test</a>";
And then added a event handler for it.
$(document).delegate('#CustomerSavingsView .jqgrow td a[href*="#Test"]', 'click', function ()
{
var guid = 'CEF9C407-2500-4619-95E3-8E6227B65954';
window.open('/irj/servlet/prt/portal/prtroot/com.medline.medpack.ExcelViewerPL.ExcelViewer?report=CustomerBenefit&reportId='+guid );
}
This solved the purpose. Thanks again Oleg and Walter.
maybe this will be help:
in colModel,define a col: {name:'test',formatter:linkformatter}
and in javascript create a function named linkformatter which returns a link;
like:
function linkformatter( cellvalue, options, rowObject){
return '<a href='xxxxxx' />';
}
The predefined formatter 'showlink' can be used to create the link in the grid column. You can use target property of the formatoptions options to define target of the link.
First declare the Jquery JQGrid column definition as follows
colModel: [{ name: 'Notes/Memos', width: "5", sortable: true, classes: 'ellip', resizable: false, formatter: MethodFormatter }]
The formatter property takes the method name which is invoked with the three parameters which internally having the cells value and its id and the following method returns the hyperlink.
function MethodFormatter(cellValue, options, rowObject) {
var selectedRowId = options.rowId;
return '<a href="javascript:MethodJS(' + selectedRowId + ')" style="color: #3366ff" id="' + selectedRowId + '" >' + cellValue + '</a>';}
The following JS Function is invoked after clicking the hyperlink which opens up another page in a window.
function MethodJS(selectedRowId) {
document.location.href = "ViewContact.aspx?NoteID=" + selectedRowId;
}
My approach involves fewer lines of code and gives the solution asked for. In my grid, a column called Project Number is formatted as a hyper link. It opens a new page and passes the project number as a parameter.
colNames: ["Project #", ...],
colModel: [
{ name: 'Project Number', index: 'Project Number', width: 80, key: true, formatter: 'showlink', formatoptions: { baseLinkUrl: 'Details.aspx', target: '_new' } },
Note where I have key: true. Without this, the url returns the row number. The url returned is http://localhost:57631/Details.aspx?id=2103
I'm using jqGrid version 5.0.1
This is my pattern. As I said, it is much more code than Oleg's suggestion of using the showlink formatter, but it is more customizable.
// bind a live event handler to any elements matching the selector 'a.linkWindowOpener'
$('a.linkWindowOpener').live('click', linkWindowOpener);
// colModel settings
{ name: 'ItemDescription', index: 'ItemDescription', formatter: itemDescription_formatter, unformat: itemDescription_unformatter },
// custom formatter to create the hyperlink
function itemDescription_formatter(cellvalue, options, rowObject) {
var html = '';
var itemID = rowObject.itemID;
var itemDescription = cellvalue;
var a = $('<a>')
.attr('href', '/Forms/WorkOrder/ViewItem.aspx?ItemID=' + itemID)
.attr('data-itemDescription', itemDescription )
.html(itemDescription)
.addClass('linkWindowOpener');
html = a.getHtml();
return html;
}
// unformatter to return the raw value
function itemDescription_unformatter( cellvalue, options, cell) {
return $('a', cell).attr('data-itemDescription');
}
// event handler to call when clicking the hyperlink
function linkWindowOpener(event) {
event.preventDefault();
event.stopPropagation();
var o = $(event.currentTarget);
var url = o.attr('href');
window.open(url);
return false;
}
// jQuery extenision function I wrote to get the HTML of an element
// returns the HTML of an element. It works by wrapping the element
// inside a DIV and calling DIV.html(). It then returns the element back to
// it's original DOM location
jQuery.fn.getHtml = function () {
var elm = $(this[0]);
// create a div
var div = $('<div>');
// append it to the parent of the target element
elm.parent().append(div);
// append the element to the div
div.append(elm);
// get the html of the div
var html = div.html();
// move element back to its parent
div.parent().append(elm);
div.remove();
return html;
}

Resources