grid.odata.js 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. /**
  2. * @license OData plugin for Free-jqGrid
  3. *
  4. * Copyright (c) 2014-2018, Mark Babayev (https://github.com/mirik123) markolog@gmail.com
  5. * License MIT (MIT-LICENSE.txt)
  6. *
  7. * inspired by Richard Bennett gist code: jqGrid.ODataExtensions.js
  8. * https://gist.github.com/dealproc/6678280
  9. */
  10. /*jslint continue: true, nomen: true, plusplus: true, unparam: true, todo: true, vars: true, white: true */
  11. /*global jQuery, define, module, require */
  12. (function (factory) {
  13. "use strict";
  14. if (typeof define === "function" && define.amd) {
  15. // AMD. Register as an anonymous module.
  16. define([
  17. "jquery",
  18. "free-jqgrid/grid.base"
  19. ], factory);
  20. } else if (typeof module === "object" && module.exports) {
  21. // Node/CommonJS
  22. module.exports = function (root, $) {
  23. if ($ === undefined) {
  24. // require("jquery") returns a factory that requires window to
  25. // build a jQuery instance, we normalize how we use modules
  26. // that require this pattern but the window provided is a noop
  27. // if it's defined (how jquery works)
  28. $ = typeof window !== "undefined" ?
  29. require("jquery") :
  30. require("jquery")(root || window);
  31. }
  32. require("free-jqgrid/grid.base");
  33. factory($);
  34. return $;
  35. };
  36. } else {
  37. // Browser globals
  38. factory(jQuery);
  39. }
  40. }(function ($) {
  41. /*
  42. *Functions:
  43. * parseMetadata - $.jgrid.odataHelper.parseMetadata(rawdata, metadatatype)
  44. * metadatatype can be: xml,json,datajs.
  45. * this is a generic function that can be used in external packages too, not only in jqGrid.
  46. * It parses $metadata ajax response in xml/json format to plain javascript object.
  47. * IT can also consume metadata returned from datajs.js method "OData.parseMetadata"
  48. *
  49. * odataGenColModel - $("#grid").jqGrid('odataGenColModel', {...});
  50. * This function generates jqgrid style columns by requesting odata $metadata.
  51. * It is automatically called by odataInit when gencolumns=true.
  52. *
  53. * Options:
  54. * metadatatype: 'xml' - ajax dataType, can be json, jsonp or xml
  55. * async: false - set ajax sync/async for $metadata request (when calling from odataInit only async=false is supported)
  56. * entitySet: null - required field, the name of the desired entity set
  57. * expandable: (none|link|json|subgrid) - the expansion type for ComplexTypes and NavigationProperties, for details see "odata colModel parameters".
  58. * metadataurl: (odataurl || p.url) + '/$metadata'
  59. * - set ajax url for $metadata request
  60. * successfunc: null - odataGenColModel callback to see when metadata request is over and jqgrid can be refreshed
  61. * parsecolfunc: null - event for converting parsed metadata data array in form of {name,type,nullable,iskey,...} to the jqgrid colModel array
  62. * parsemetadatafunc: null - event for converting unparsed metadata data (xml or json) to the jqgrid colModel array
  63. * errorfunc: null - error callback
  64. *
  65. * jqGrid Events:
  66. * jqGridODataParseMetadata - the same as parsemetadatafunc, when no custom function exists the default function is used: $("#grid").jqGrid('parseMetadata', rawdata, dataType)
  67. * jqGridODataParseColumns - the same as parsecolfunc, when no custom function exists the default function is used: $("#grid").jqGrid('parseColumns', {...})
  68. *
  69. * odataInit - $("#grid").jqGrid('odataInit', {...});
  70. * This is main plugin function. It should be called before colModel is initialized.
  71. * When columns are defined manually it can be called from events beforeInitGrid, onInitGrid.
  72. * When columns are created automatically it can be called from event beforeInitGrid only.
  73. *
  74. * Options:
  75. * gencolumns: false - automatically generate columns from odata $metadata (calls odataGenColModel)
  76. * odataurl: p.url - required field, main odata url
  77. * datatype: 'json' - ajax dataType, can be json, jsonp or xml
  78. * entitySet: null - required field, the name of the desired entity set
  79. * annotations: false - use odata annotations for getting jqgrid parameters: page,records,count,total
  80. * annotationName: "@jqgrid.GridModelAnnotate" - odata annotations class and namespace
  81. * version - odata version, used to set $count=true or $inlinecount=allpages
  82. * errorfunc: null - error callback
  83. * metadatatype: datatype || 'xml' - when gencolumns=true, alternative ajax dataType for $metadata request
  84. * odataverbs: { - http verbs for odata and their corresponding actions in jqgrid
  85. * inlineEditingAdd: 'POST',
  86. * inlineEditingEdit: 'PATCH',
  87. * formEditingAdd: 'POST',
  88. * formEditingEdit: 'PUT'
  89. * }
  90. *
  91. * odata colModel parameters
  92. * isnavigation - the column type is a NavigationProperty that points to another entity
  93. * iscomplex - the column type is a ComplexType
  94. * iscollection - the column is a Collection of entities that can be opened in a new subgrid
  95. * nosearch - when true, this column is excluded from odata search
  96. * unformat: function (searchField, searchString, searchOper) - works analogous to xmlmap/jsonmap,
  97. * for example the function body can be: { return searchString !== '-1' ? 'cltype/Id' : null; }
  98. * expand: (link|json|subgrid) - defines data expansion types for complex amd navigation properties,
  99. * it works only with custom formatters specified in odata cmTemplates.
  100. * link - the link to the property is displayed
  101. * json - the property data is displayed in a json string form
  102. * subgrid - jquery subgrid is opened when clicking on a link inside column
  103. *
  104. * odata column templates (cmTemplate)
  105. * odataComplexType - column template for odata Complex type.
  106. * odataNavigationProperty - column template for odata Navigation property.
  107. *
  108. *Plugin allows setting custom cmTemplates for any odata type, for example:
  109. * $.jgrid.cmTemplate["Edm.GeographyPoint"] = {
  110. * editable: false,
  111. * formatter: function(cellvalue, options, rowObject) {
  112. * if (!cellvalue && this.p.datatype === 'xml') {
  113. * var xmlvalue = $(rowObject).filter(function() {
  114. * return this.localName.toLowerCase() === options.colModel.name.toLowerCase();
  115. * });
  116. * cellvalue = $.jgrid.odataHelper.convertXmlToJson(xmlvalue[0]);
  117. * }
  118. * if(cellvalue.crs && cellvalue.coordinates) {
  119. * return $.jgrid.format('<div>{0}</div><div>[{1},{2}]</div>', cellvalue.crs.properties.name, cellvalue.coordinates[0], cellvalue.coordinates[1]);
  120. * }
  121. * return $.jgrid.format('<div>{0}</div>', cellvalue);
  122. * }
  123. * };
  124. *
  125. * Example of using standard service from http://www.odata.org/odata-services:
  126. * $("#grid").jqGrid({
  127. * ...,
  128. * beforeInitGrid: function () {
  129. * $(this).jqGrid('odataInit', {
  130. * annotations: false,
  131. * metadatatype: 'xml',
  132. * datatype: 'jsonp',
  133. * version: 4,
  134. * gencolumns: true,
  135. * expandable: 'json',
  136. * entitySet: 'Products',
  137. * odataurl: "http://services.odata.org/V4/OData/OData.svc/Products",
  138. * metadataurl: 'http://services.odata.org/V4/OData/OData.svc/$metadata',
  139. * errorfunc: function (jqXHR, parsedError) {
  140. * jqXHR = jqXHR.xhr || jqXHR;
  141. * parsedError = $('#errdialog').html() + parsedError;
  142. * $('#errdialog').html(parsedError).dialog('open');
  143. * });
  144. * }
  145. * });
  146. *
  147. * $.ajax({
  148. * url: 'http://services.odata.org/V4/OData/OData.svc/$metadata',
  149. * dataType: xml,
  150. * type: 'GET'
  151. * }).done(function(data, st, xhr) {
  152. * var dataType = xhr.getResponseHeader('Content-Type').indexOf('json') >= 0 ? 'json' : 'xml';
  153. * if(dataType === 'json') {
  154. * data = $.jgrid.odataHelper.resolveJsonReferences(data);
  155. * }
  156. * data = $.jgrid.odataHelper.parseMetadata(data, dataType);
  157. * var colModels = {};
  158. * for (i in data) {
  159. * if (data.hasOwnProperty(i) && i) {
  160. * colModels[i] = $(this).jqGrid('parseColumns', data[i], 'subgrid');
  161. * }
  162. * }
  163. * $("#grid").jqGrid({
  164. * colModel: colModels['Product'],
  165. * odata: {
  166. * iscollection: true,
  167. * subgridCols: colModels
  168. * },
  169. * ...,
  170. * beforeInitGrid: function () {
  171. * $(this).jqGrid('odataInit', {
  172. * annotations: false,
  173. * datatype: 'jsonp',
  174. * version: 4,
  175. * gencolumns: false,
  176. * entitySet: 'Products',
  177. * odataurl: "http://services.odata.org/V4/OData/OData.svc/Products"
  178. * });
  179. * }
  180. * });
  181. * });
  182. *
  183. * Examples of using custom services from https://github.com/mirik123/jqGridSamples:
  184. * $("#grid").jqGrid({
  185. * colModel: colModelDefinition,
  186. * ...,
  187. * // when columns are defined manually (gencolumns=false) the odataInit call can be also put in onInitGrid event.
  188. * beforeInitGrid: function () {
  189. * $(this).jqGrid('odataInit', {
  190. * version: 3,
  191. * gencolumns: false,
  192. * odataurl: 'http://localhost:56216/odata/ODClient'
  193. * });
  194. * }
  195. * });
  196. *
  197. * $("#grid").jqGrid({
  198. * colModel: colModelDefinition,
  199. * ...,
  200. * beforeInitGrid: function () {
  201. * $(this).jqGrid('odataInit', {
  202. * version: 4,
  203. * datatype: 'json',
  204. * annotations: true,
  205. * gencolumns: true,
  206. * entitySet: 'ODClient',
  207. * odataurl: 'http://localhost:56216/odata/ODClient',
  208. * metadataurl: 'http://localhost:56216/odata/$metadata'
  209. * });
  210. * }
  211. * });
  212. *
  213. * $("#grid").jqGrid({
  214. * colModel: colModelDefinition,
  215. * ...,
  216. * beforeInitGrid: function () {
  217. * $(this).jqGrid('odataInit', {
  218. * version: 4,
  219. * datatype: 'xml',
  220. * annotations: false,
  221. * gencolumns: true,
  222. * entitySet: 'ODClient',
  223. * odataurl: 'http://localhost:56216/odata/ODClient',
  224. * metadataurl: 'http://localhost:56216/odata/$metadata'
  225. * });
  226. * }
  227. * });
  228. */
  229. "use strict";
  230. $.jgrid.odataHelper = {
  231. //http://stackoverflow.com/questions/15312529/resolve-circular-references-from-json-object
  232. resolveJsonReferences: function (json, refs) {
  233. var i, ref, byid = {}; // all objects by id
  234. refs = refs || []; // references to objects that could not be resolved
  235. function recurse(obj, prop, parent) {
  236. if (typeof obj !== 'object' || !obj) {// a primitive value
  237. return obj;
  238. }
  239. if (Object.prototype.toString.call(obj) === '[object Array]') {
  240. for (i = 0; i < obj.length; i++) {
  241. // check also if the array element is not a primitive value
  242. if (typeof obj[i] !== 'object' || !obj[i]) {// a primitive value
  243. return obj[i];
  244. }
  245. if (obj[i].$ref) {
  246. obj[i] = recurse(obj[i], i, obj);
  247. }
  248. else {
  249. obj[i] = recurse(obj[i], prop, obj);
  250. }
  251. }
  252. return obj;
  253. }
  254. if (obj.$ref) { // a reference
  255. ref = obj.$ref;
  256. if (byid[ref]) {
  257. return byid[ref];
  258. }
  259. // else we have to make it lazy:
  260. refs.push([parent, prop, ref]);
  261. return;
  262. }
  263. if (obj.$id) {
  264. var id = obj.$id;
  265. delete obj.$id;
  266. if (obj.$values) {// an array
  267. obj = obj.$values.map(recurse);
  268. }
  269. else {// a plain object
  270. var itm;
  271. for (itm in obj) {
  272. if (obj.hasOwnProperty(itm)) {
  273. obj[itm] = recurse(obj[itm], itm, obj);
  274. }
  275. }
  276. }
  277. byid[id] = obj;
  278. }
  279. return obj;
  280. }
  281. if (typeof json === 'string') {
  282. json = JSON.parse(json);
  283. }
  284. json = recurse(json); // run it!
  285. for (i = 0; i < refs.length; i++) { // resolve previously unknown references
  286. ref = refs[i];
  287. ref[0][ref[1]] = byid[ref[2]];
  288. // Notice that this throws if you put in a reference at top-level
  289. }
  290. return json;
  291. },
  292. // Changes XML to JSON
  293. //http://davidwalsh.name/convert-xml-json
  294. convertXmlToJson: function (xml) {
  295. // Create the return object
  296. var obj = {}, i, j, attribute, item, nodeName, old;
  297. if (!xml) { return null; }
  298. if (xml.nodeType === 1) { // element
  299. // do attributes
  300. if (xml.attributes.length > 0) {
  301. obj["@attributes"] = {};
  302. for (j = 0; j < xml.attributes.length; j++) {
  303. attribute = xml.attributes.item(j);
  304. obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
  305. }
  306. }
  307. }
  308. else if (xml.nodeType === 3) { // text
  309. obj = xml.nodeValue;
  310. }
  311. else if (!xml.nodeType) {
  312. obj = xml;
  313. }
  314. // do children
  315. if (xml.hasChildNodes && xml.hasChildNodes()) {
  316. for (i = 0; i < xml.childNodes.length; i++) {
  317. item = xml.childNodes.item(i);
  318. if (item.nodeType === 3) {
  319. return item.nodeValue;
  320. }
  321. nodeName = item.nodeName;
  322. if (obj[nodeName] === undefined) {
  323. obj[nodeName] = $.jgrid.odataHelper.convertXmlToJson(item);
  324. } else {
  325. if (obj[nodeName].push === undefined) {
  326. old = obj[nodeName];
  327. obj[nodeName] = [];
  328. obj[nodeName].push(old);
  329. }
  330. obj[nodeName].push($.jgrid.odataHelper.convertXmlToJson(item));
  331. }
  332. }
  333. }
  334. return $.isEmptyObject(obj) ? null : obj;
  335. },
  336. parseMetadata: function (rawdata, metadatatype) {
  337. function parseXmlMetadata(data) {
  338. var entities = {}, entityValues = [], mdata = {};
  339. var namespace = $('Schema', data).attr('Namespace') + '.';
  340. $('EntityContainer EntitySet', data).each(function (i, itm) {
  341. entities[$(itm).attr('EntityType').replace(namespace, '')] = $(itm).attr('Name');
  342. entityValues.push($(itm).attr('Name'));
  343. });
  344. $('EntityType, ComplexType', data).each(function () {
  345. var cols, props, keys, key, iskey, isComplex, isNav, entityType, attr;
  346. props = $(this).find('Property,NavigationProperty');
  347. keys = $('Key PropertyRef', this);
  348. key = keys && keys.length > 0 ? keys.first().attr('Name') : '';
  349. entityType = $(this).attr('Name');
  350. if (props) {
  351. cols = [];
  352. props.each(function (n, itm) {
  353. attr = {};
  354. $.each(itm.attributes, function () {
  355. attr[this.name] = this.value;
  356. });
  357. iskey = attr.Name === key;
  358. isNav = itm.tagName === 'NavigationProperty';
  359. isComplex = itm.tagName === 'Property' && $('ComplexType[Name="' + attr.Name + '"]', data).length > 0;
  360. cols.push($.extend({
  361. iskey: iskey,
  362. isComplex: isComplex,
  363. isNavigation: isNav,
  364. isCollection: $.inArray(attr.Name, entityValues) >= 0
  365. }, attr));
  366. });
  367. if(entities[entityType]) {
  368. mdata[entities[entityType]] = cols;
  369. }
  370. mdata[entityType] = cols;
  371. }
  372. });
  373. return mdata;
  374. }
  375. function parseJsonMetadata(data) {
  376. var cols, props, keys, key, iskey, i, j, isComplex, isNav, nullable, type, entityType, mdata = {}, entities = {}, entityValues = [];
  377. for (i = 0; i < data.EntityContainer.Elements.length; i++) {
  378. entities[data.EntityContainer.Elements[i].Type.ElementType.Definition.Name] = data.EntityContainer.Elements[i].Name;
  379. entityValues.push(data.EntityContainer.Elements[i].Name);
  380. }
  381. for (i = 0; i < data.SchemaElements.length ; i++) {
  382. props = Array.prototype.concat(data.SchemaElements[i].DeclaredProperties, data.SchemaElements[i].NavigationProperties).filter(function(itm) {return !!itm;});
  383. keys = data.SchemaElements[i].DeclaredKey;
  384. key = keys && keys.length > 0 ? keys[0].Name : '';
  385. entityType = data.SchemaElements[i].Name;
  386. if (props) {
  387. cols = [];
  388. for (j = 0; j < props.length; j++) {
  389. iskey = props[j].Name === key;
  390. nullable = props[j].Type.IsNullable;
  391. type = props[j].Type.Definition.Namespace + props[j].Type.Definition.Name;
  392. isComplex = !!props[j].Type.Definition.DeclaredProperties;
  393. isNav = !isComplex && !props[j].Type;
  394. cols.push({
  395. Name: props[j].Name,
  396. Type: type,
  397. Nullable: nullable,
  398. iskey: iskey,
  399. isComplex: isComplex,
  400. isNavigation: isNav,
  401. isCollection: $.inArray(props[j].Name, entityValues) >= 0
  402. });
  403. }
  404. if(entities[entityType]) {
  405. mdata[entities[entityType]] = cols;
  406. }
  407. mdata[entityType] = cols;
  408. }
  409. }
  410. return mdata;
  411. }
  412. function parseDataJSMetadata(data) {
  413. var cols, props, keys, key, iskey, i, j, isComplex, isNav, nullable, type, entityType, mdata = {}, entities = {}, entityValues = [], entityTypes = [], complexTypes = [];
  414. var schema = data.dataServices.schema[0];
  415. var namespace = schema.namespace + '.';
  416. for (i = 0; i < schema.entityContainer[0].entitySet.length; i++) {
  417. entities[schema.entityContainer[0].entitySet[i].entityType.replace(namespace, '')] = schema.entityContainer[0].entitySet[i].name;
  418. entityValues.push(schema.entityContainer[0].entitySet[i].name);
  419. }
  420. for (i = 0; i < schema.complexType.length; i++) {
  421. complexTypes.push(schema.complexType[i].name);
  422. }
  423. entityTypes = Array.prototype.concat(schema.entityType, schema.complexType).filter(function(itm) {return !!itm;});
  424. for (i = 0; i < entityTypes.length ; i++) {
  425. props = Array.prototype.concat(entityTypes[i].property, entityTypes[i].navigationProperty).filter(function(itm) {return !!itm;});
  426. keys = entityTypes[i].key;
  427. key = keys && keys.propertyRef.length > 0 ? keys.propertyRef[0].name : '';
  428. entityType = entityTypes[i].name;
  429. if (props) {
  430. cols = [];
  431. for (j = 0; j < props.length; j++) {
  432. iskey = props[j].name === key;
  433. nullable = props[j].nullable !== "false";
  434. type = props[j].type;
  435. isComplex = !!props[j].type && $.inArray(props[j].type.replace(namespace, ''), complexTypes) >= 0;
  436. isNav = !props[j].type;
  437. cols.push({
  438. Name: props[j].name,
  439. Type: type,
  440. Nullable: nullable,
  441. iskey: iskey,
  442. isComplex: isComplex,
  443. isNavigation: isNav,
  444. isCollection: $.inArray(props[j].name, entityValues) >= 0
  445. });
  446. }
  447. if(entities[entityType]) {
  448. mdata[entities[entityType]] = cols;
  449. }
  450. mdata[entityType] = cols;
  451. }
  452. }
  453. return mdata;
  454. }
  455. var mdata;
  456. switch(metadatatype) {
  457. case 'xml':
  458. mdata = parseXmlMetadata(rawdata);
  459. break;
  460. case 'json':
  461. mdata = parseJsonMetadata(rawdata);
  462. break;
  463. case 'datajs':
  464. mdata = parseDataJSMetadata(rawdata);
  465. break;
  466. }
  467. return mdata;
  468. },
  469. loadError: function (jqXHR, textStatus, errorThrown) {
  470. var status = jqXHR.status;
  471. var title = textStatus;
  472. var message = errorThrown;
  473. if (!jqXHR.responseJSON) {
  474. if (jqXHR.responseXML) {
  475. jqXHR.responseText = jqXHR.responseText.replace(/<(\/?)([^:>\s]*:)?([^>]+)>/g, "<$1$3>");
  476. jqXHR.responseXML = $.parseXML(jqXHR.responseText);
  477. jqXHR.responseJSON = $.jgrid.odataHelper.convertXmlToJson(jqXHR.responseXML);
  478. }
  479. else if (jqXHR.responseText) {
  480. try {
  481. jqXHR.responseJSON = $.parseJSON(jqXHR.responseText);
  482. }
  483. catch (ignore) {
  484. }
  485. }
  486. }
  487. if (jqXHR.responseJSON) {
  488. var odataerr = jqXHR.responseJSON["@odata.error"] || jqXHR.responseJSON["odata.error"] || jqXHR.responseJSON.error;
  489. if (odataerr) {
  490. if (odataerr.innererror) {
  491. if (odataerr.innererror.internalexception) {
  492. title = odataerr.innererror.internalexception.message;
  493. message = odataerr.innererror.internalexception.stacktrace || '';
  494. }
  495. else {
  496. title = odataerr.innererror.message;
  497. message = odataerr.innererror.stacktrace || '';
  498. }
  499. }
  500. else {
  501. title = odataerr.message.value || odataerr.message;
  502. message = odataerr.stacktrace || '';
  503. }
  504. }
  505. }
  506. else if (errorThrown && $.isPlainObject(errorThrown)) {
  507. title = errorThrown.message;
  508. message = errorThrown.stack;
  509. status = errorThrown.code;
  510. }
  511. var errstring = "<div>Status/error code: " + status + "</div><div>Message: " + title + '</div><div style="font-size: 0.8em;">' + message + '</div><br/>';
  512. return errstring;
  513. }
  514. };
  515. $.jgrid.cmTemplate.odataComplexType = {
  516. editable: false,
  517. formatter: function (cellvalue, options, rowObject) {
  518. return $(this).jqGrid('odataJson', cellvalue, options, rowObject);
  519. }
  520. };
  521. $.jgrid.cmTemplate.odataNavigationProperty = {
  522. editable: false,
  523. formatter: function (cellvalue, options, rowObject) {
  524. if (!options.colModel.odata.expand || options.colModel.odata.expand === 'link') {
  525. return $(this).jqGrid('odataLink', cellvalue, options, rowObject);
  526. }
  527. if (options.colModel.odata.expand === 'json') {
  528. return $(this).jqGrid('odataJson', cellvalue, options, rowObject);
  529. }
  530. if (options.colModel.odata.expand === 'subgrid') {
  531. return $(this).jqGrid('odataSubgrid', cellvalue, options, rowObject);
  532. }
  533. }
  534. };
  535. $.jgrid.cmTemplate["Edm.GeographyPoint"] = {
  536. editable: false,
  537. formatter: function (cellvalue, options, rowObject) {
  538. if (!cellvalue && this.p.datatype === 'xml') {
  539. var xmlvalue = $(rowObject).filter(function () {
  540. return this.localName.toLowerCase() === options.colModel.name.toLowerCase();
  541. });
  542. cellvalue = $.jgrid.odataHelper.convertXmlToJson(xmlvalue[0]);
  543. }
  544. if (cellvalue.crs && cellvalue.coordinates) {
  545. return $.jgrid.format('<div>{0}</div><div>[{1},{2}]</div>', cellvalue.crs.properties.name, cellvalue.coordinates[0], cellvalue.coordinates[1]);
  546. }
  547. return $.jgrid.format('<div>{0}</div>', cellvalue);
  548. }
  549. };
  550. $.jgrid.extend({
  551. odataLink: function (cellvalue, options, rowObject) {
  552. var keyValue, result, $p = this[0].p;
  553. if ($p.datatype !== 'xml') {
  554. if (rowObject[options.colModel.name + '@odata.navigationLink']) {
  555. keyValue = rowObject[options.colModel.name + '@odata.navigationLink'];
  556. result = $.jgrid.format('<a href="{0}/{1}" target="_self">{2}</a>', $p.odata.baseUrl, keyValue, options.colModel.name);
  557. return result;
  558. }
  559. keyValue = rowObject[$p.jsonReader.id];
  560. }
  561. else {
  562. keyValue = (function (id) {
  563. return $(rowObject).filter(function () {
  564. return this.localName && this.localName.toLowerCase() === id;
  565. }).text();
  566. }($p.xmlReader.id.toLowerCase()));
  567. }
  568. if ($p.odata.iscollection) {
  569. result = $.jgrid.format('<a href="{0}({1})/{2}" target="_self">{2}</a>', $p.url, keyValue, options.colModel.name);
  570. }
  571. else {
  572. result = $.jgrid.format('<a href="{0}/{1}" target="_self">{1}</a>', $p.url, options.colModel.name);
  573. }
  574. return result;
  575. },
  576. odataJson: function (cellvalue, options, rowObject) {
  577. var i, result, $p = this[0].p, tmpObj = {};
  578. if ($p.datatype === 'xml') {
  579. var xmlvalue = $(rowObject).filter(function () {
  580. return this.localName.toLowerCase() === options.colModel.name.toLowerCase();
  581. });
  582. cellvalue = $.jgrid.odataHelper.convertXmlToJson(xmlvalue[0]);
  583. }
  584. for (i in cellvalue) {
  585. if (cellvalue.hasOwnProperty(i) && i && i.indexOf('@odata.') < 0 && i.indexOf('@attributes') < 0) {
  586. tmpObj[i] = cellvalue[i];
  587. }
  588. }
  589. result = JSON.stringify(tmpObj, null, 1);
  590. return result;
  591. },
  592. odataSubgrid: function (cellvalue, options, rowObject) {
  593. var i, keyValue, result, $p = this[0].p;
  594. if ($p.datatype !== 'xml') {
  595. keyValue = rowObject[$p.jsonReader.id];
  596. }
  597. else {
  598. keyValue = (function (id) {
  599. return $(rowObject).filter(function () {
  600. return this.localName && this.localName.toLowerCase() === id;
  601. }).text();
  602. }($p.xmlReader.id.toLowerCase()));
  603. }
  604. for (i in $p._index) {
  605. if ($p._index.hasOwnProperty(i) && i && keyValue === $p._index[i].toString()) {
  606. keyValue = i;
  607. break;
  608. }
  609. }
  610. var onclick = '\'$(\"#{2}\").jqGrid(\"setGridParam\", { odata: {activeEntitySet: \"{1}\" } });$(\"#{2}\").jqGrid(\"expandSubGridRow\", \"{0}\");return false;\'';
  611. result = '<a style="cursor:pointer" data-id="{0}" onclick=' + onclick + '>{1}</a>';
  612. result = $.jgrid.format(result, keyValue, options.colModel.name, options.gid);
  613. return result;
  614. },
  615. parseColumns: function (cols, expandable) {
  616. var i = 0, isInt, isNum, isDate, isBool, cmTemplate, newcol = [], searchrules, searchtype, label;
  617. var intTypes = 'Edm.Int16,Edm.Int32,Edm.Int64';
  618. var numTypes = 'Edm.Decimal,Edm.Double,Edm.Single';
  619. var boolTypes = 'Edm.Byte,Edm.SByte';
  620. for (i = 0; i < cols.length; i++) {
  621. isInt = intTypes.indexOf(cols[i].Type) >= 0;
  622. isNum = numTypes.indexOf(cols[i].Type) >= 0;
  623. isBool = boolTypes.indexOf(cols[i].Type) >= 0;
  624. isDate = cols[i].Type && (cols[i].Type.indexOf('Edm.') >= 0 && (cols[i].Type.indexOf('Date') >= 0 || cols[i].Type.indexOf('Time') >= 0));
  625. cmTemplate =
  626. $.jgrid.cmTemplate[cols[i].Type] ? cols[i].Type :
  627. cols[i].isComplex ? 'odataComplexType' :
  628. cols[i].isNavigation ? 'odataNavigationProperty' :
  629. isInt ? 'integerStr' :
  630. isNum ? 'numberStr' :
  631. isBool ? 'booleanCheckbox' :
  632. 'text';
  633. searchrules = { integer: isInt, number: isNum, date: isDate, required: !cols[i].Nullable || cols[i].Nullable === 'false' };
  634. searchtype = isInt ? 'integer' : isNum ? 'number' : isDate ? 'datetime' : isBool ? 'checkbox' : 'text';
  635. label = (cols[i].isNavigation || cols[i].isComplex) ?
  636. '<span class="ui-icon ui-icon-arrowreturn-1-s" style="display:inline-block;vertical-align:middle;"></span>' + cols[i].Name : cols[i].Name;
  637. newcol.push($.extend({
  638. label: label,
  639. name: cols[i].Name,
  640. index: cols[i].Name,
  641. editable: !cols[i].isNavigation && !cols[i].iskey,
  642. searchrules: searchrules,
  643. editrules: searchrules,
  644. searchtype: searchtype,
  645. inputtype: searchtype,
  646. edittype: searchtype,
  647. key: cols[i].iskey,
  648. odata: {
  649. expand: cols[i].isNavigation ? expandable : cols[i].isComplex ? 'json' : null,
  650. isnavigation: cols[i].isNavigation,
  651. iscomplex: cols[i].isComplex,
  652. iscollection: cols[i].isCollection
  653. }
  654. }, $.jgrid.cmTemplate[cmTemplate]));
  655. }
  656. return newcol;
  657. },
  658. odataInit: function (options) {
  659. // builds out OData expressions... the condition.
  660. function prepareExpression(p, searchField, searchString, searchOper) {
  661. var i, col;
  662. // if we want to support "in" clauses, we need to follow this stackoverflow article:
  663. //http://stackoverflow.com/questions/7745231/odata-where-id-in-list-query/7745321#7745321
  664. // this is for basic searching, with a single term.
  665. if (searchField && (searchString || searchOper === 'nu' || searchOper === 'nn')) {
  666. if (searchString) {
  667. //append '' when searched field is of the string type
  668. for (i = 0; i < p.colModel.length; i++) {
  669. col = p.colModel[i];
  670. if (col.name === searchField) {
  671. if (col.odata.nosearch) { return; }
  672. if (col.odata.unformat) {
  673. searchField = $.isFunction(col.odata.unformat) ? col.odata.unformat(searchField, searchString, searchOper) : col.odata.unformat;
  674. if (!searchField) { return; }
  675. }
  676. if (!col.searchrules || (!col.searchrules.integer && !col.searchrules.number && !col.searchrules.date)) {
  677. searchString = "'" + searchString + "'";
  678. }
  679. else if (col.searchrules && col.searchrules.date) {
  680. searchString = (new Date(searchString)).toISOString();
  681. //v3: postData.searchString = "datetimeoffset'" + postData.searchString + "'";
  682. //v2: postData.searchString = "DateTime'" + postData.searchString + "'";
  683. }
  684. break;
  685. }
  686. }
  687. }
  688. switch (searchOper) {
  689. case "in": // is in
  690. case "cn": // contains
  691. //return "substringof(" + searchString + ", " + searchField + ") eq true";
  692. return "indexof(" + searchField + ",tolower(" + searchString + ")) gt -1";
  693. case "ni": // is not in
  694. case "nc": // does not contain.
  695. //return "substringof(" + searchString + ", " + searchField + ") eq false";
  696. return "indexof(" + searchField + ",tolower(" + searchString + ")) eq -1";
  697. case "bw": // begins with
  698. return "startswith(" + searchField + "," + searchString + ") eq true";
  699. case "bn": // does not begin with
  700. return "startswith(" + searchField + "," + searchString + ") eq false";
  701. case "ew": // ends with
  702. return "endswith(" + searchField + "," + searchString + ") eq true";
  703. case "en": // does not end with.
  704. return "endswith(" + searchField + "," + searchString + ") eq false";
  705. case "nu": // is null
  706. return searchField + " eq null";
  707. case "nn": // is not null
  708. return searchField + " ne null";
  709. default: // eq,ne,lt,le,gt,ge,
  710. return searchField + " " + searchOper + " " + searchString;
  711. }
  712. }
  713. }
  714. // when dealing with the advanced query dialog, this parses the encapsulating Json object
  715. // which we will then build the advanced OData expression from.
  716. function parseFilterGroup(filterGroup, p) {
  717. var i, rule, filterText = "", filterRes;
  718. if (filterGroup.groups) {
  719. if (filterGroup.groups.length) {
  720. for (i = 0; i < filterGroup.groups.length; i++) {
  721. filterText += "(" + parseFilterGroup(filterGroup.groups[i], p) + ")";
  722. if (i < filterGroup.groups.length - 1) {
  723. filterText += " " + filterGroup.groupOp.toLowerCase() + " ";
  724. }
  725. }
  726. if (filterGroup.rules && filterGroup.rules.length) {
  727. filterText += " " + filterGroup.groupOp.toLowerCase() + " ";
  728. }
  729. }
  730. }
  731. if (filterGroup.rules.length) {
  732. for (i = 0; i < filterGroup.rules.length; i++) {
  733. rule = filterGroup.rules[i];
  734. filterRes = prepareExpression(p, rule.field, rule.data, rule.op);
  735. if (filterRes) {
  736. filterText += filterRes + " " + filterGroup.groupOp.toLowerCase() + " ";
  737. }
  738. }
  739. }
  740. filterText = filterText.trim().replace(/\s(and|or)$/, '').trim();
  741. return filterText;
  742. }
  743. function setupWebServiceData(p, o, postData) {
  744. var params = {};
  745. //var expandlist = p.colModel.filter(function(itm) { return itm.odata && itm.odata.isnavigation && (itm.odata.expand === 'json' || itm.odata.expand === 'subgrid'); });
  746. //if(expandlist.length > 0) {
  747. // params.$expand = expandlist.reduce(function(x,y) { return x+','+ y.name; }, '').substring(1);
  748. //}
  749. //Query options $orderby, $count, $skip and $top cannot be applied to the requested resource
  750. if (!p.odata.iscollection) {
  751. if (!o.version || o.version < 4) {
  752. params.$format = o.datatype === 'xml' ? 'atom' : 'application/json;odata=fullmetadata';
  753. }
  754. else {
  755. params.$format = o.datatype === 'xml' ? 'atom' : 'application/json;odata.metadata=full';
  756. }
  757. return params;
  758. }
  759. params = {
  760. $top: postData.rows, //- $top removes odata.nextLink parameter
  761. $skip: (parseInt(postData.page, 10) - 1) * p.rowNum
  762. };
  763. if (o.datatype === 'jsonp') { params.$callback = o.callback; }
  764. if (!o.version || o.version < 4) {
  765. params.$inlinecount = "allpages";
  766. params.$format = o.datatype === 'xml' ? 'atom' : 'application/json;odata=fullmetadata';
  767. }
  768. else {
  769. params.$count = true;
  770. params.$format = o.datatype === 'xml' ? 'atom' : 'application/json;odata.metadata=full';
  771. }
  772. // if we have an order-by clause to use, then we build it.
  773. if (postData.sidx) {
  774. // two columns have the following data:
  775. // postData.sidx = "{ColumnName} {order}, {ColumnName} "
  776. // postData.sord = "{order}"
  777. // we need to split sidx by the ", " and see if there are multiple columns. If there are, we need to go through
  778. // each column and get its parts, then parse that for the appropriate columns to build for the sort.
  779. params.$orderby = postData.sidx + " " + postData.sord;
  780. }
  781. if (!postData._search) { return params; }
  782. // complex searching, with a groupOp. This is for if we enable the form for multiple selection criteria.
  783. if (postData.filters) {
  784. var filterGroup = $.parseJSON(postData.filters);
  785. var groupSearch = parseFilterGroup(filterGroup, p);
  786. if (groupSearch.length > 0) {
  787. params.$filter = groupSearch;
  788. }
  789. }
  790. else {
  791. params.$filter = prepareExpression(p, postData.searchField, postData.searchString, postData.searchOper);
  792. }
  793. return params;
  794. }
  795. function subgridRowExpanded(p, o, subgrid_id, row_id) {
  796. //var rowObject = $(this).jqGrid('getRowData', row_id, p.odata.activeEntitySet), result;
  797. //var rowObject = p.data[p._index[row_id]][p.odata.activeEntitySet], result;
  798. var result, colModel = p.colModel.filter(function (itm) { return itm.name === p.odata.activeEntitySet; })[0];
  799. row_id = p._index[row_id];
  800. if (p.odata.iscollection) {
  801. result = $.jgrid.format('{0}({1})/{2}', p.url, row_id, p.odata.activeEntitySet);
  802. }
  803. else {
  804. result = $.jgrid.format('{0}/{1}', p.url, p.odata.activeEntitySet);
  805. }
  806. var odatainit = {
  807. datatype: o.datatype,
  808. version: o.version,
  809. gencolumns: false,
  810. expandable: o.expandable,
  811. odataurl: result,
  812. errorfunc: o.errorfunc,
  813. annotations: o.annotations,
  814. entitySet: p.odata.activeEntitySet
  815. };
  816. $("#" + subgrid_id).html('<table id="' + subgrid_id + '_t" class="scroll"></table>');
  817. $("#" + subgrid_id + "_t").jqGrid({
  818. colModel: p.odata.subgridCols[p.odata.activeEntitySet],
  819. odata: $.extend({}, p.odata, colModel.odata),
  820. loadonce: true,
  821. beforeInitGrid: function () {
  822. $(this).jqGrid('odataInit', odatainit);
  823. },
  824. loadError: function (jqXHR, textStatus, errorThrown) {
  825. var parsedError = $.jgrid.odataHelper.loadError(jqXHR, textStatus, errorThrown);
  826. parsedError = $('#errdialog').html() + parsedError;
  827. $('#errdialog').html(parsedError).dialog('open');
  828. }
  829. });
  830. }
  831. function initDefaults(p, o) {
  832. var i, defaultGetAjaxOptions = {
  833. datatype: o.datatype,
  834. jsonpCallback: o.callback
  835. },
  836. subGridRowExpandedFunc = function (subgrid_id, row_id) {
  837. return subgridRowExpanded(p, o, subgrid_id, row_id);
  838. };
  839. if (!p.odata) { p.odata = { iscollection: true }; }
  840. $.extend(p, {
  841. serializeGridData: function (postData) {
  842. postData = setupWebServiceData(p, o, postData);
  843. this.p.odata.postData = postData;
  844. return postData;
  845. },
  846. ajaxGridOptions: defaultGetAjaxOptions,
  847. mtype: 'GET',
  848. url: o.odataurl
  849. }, defaultGetAjaxOptions);
  850. if (p.colModel) {
  851. for (i = 0; i < p.colModel.length; i++) {
  852. if (p.colModel[i].odata && p.colModel[i].odata.expand === 'subgrid') {
  853. p.subGrid = true;
  854. p.subGridRowExpanded = subGridRowExpandedFunc;
  855. p.odata.activeEntitySet = p.colModel[i].name;
  856. p.loadonce = true;
  857. break;
  858. }
  859. }
  860. }
  861. var defaultAjaxOptions = {
  862. contentType: 'application/' + (o.datatype === 'jsonp' ? 'json' : o.datatype) + ';charset=utf-8',
  863. datatype: (o.datatype === 'jsonp' ? 'json' : o.datatype)
  864. };
  865. p.inlineEditing = $.extend(true, {
  866. beforeSaveRow: function (options, rowid) {
  867. if (options.extraparam.oper === 'edit') {
  868. options.url = o.odataurl;
  869. options.mtype = o.odataverbs.inlineEditingEdit;
  870. options.url += '(' + rowid + ')';
  871. }
  872. else {
  873. options.url = o.odataurl;
  874. options.mtype = o.odataverbs.inlineEditingAdd;
  875. }
  876. return true;
  877. },
  878. serializeSaveData: function (postdata) {
  879. return JSON.stringify(postdata);
  880. },
  881. ajaxSaveOptions: defaultAjaxOptions
  882. }, p.inlineEditing || {});
  883. $.extend(p.formEditing, {
  884. onclickSubmit: function (options, postdata, frmoper) {
  885. if (frmoper === 'add') {
  886. options.url = o.odataurl;
  887. options.mtype = o.odataverbs.formEditingAdd;
  888. }
  889. else if (frmoper === 'edit') {
  890. options.url = o.odataurl + '(' + postdata[p.id + "_id"] + ')';
  891. options.mtype = o.odataverbs.formEditingEdit;
  892. }
  893. return postdata;
  894. },
  895. ajaxEditOptions: defaultAjaxOptions,
  896. serializeEditData: function (postdata) {
  897. return JSON.stringify(postdata);
  898. }
  899. });
  900. $.extend(p.formDeleting, {
  901. url: o.odataurl,
  902. mtype: "DELETE",
  903. serializeDelData: function () {
  904. return "";
  905. },
  906. onclickSubmit: function (options, postdata) {
  907. options.url += '(' + postdata + ')';
  908. return '';
  909. },
  910. ajaxDelOptions: defaultAjaxOptions
  911. });
  912. var keyName = p.colModel.filter(function (itm) { return !!itm.key; })[0];
  913. keyName = keyName ? keyName.name : (p.sortname || 'id');
  914. if (o.datatype === 'xml') {
  915. if (o.annotations) {
  916. $.extend(true, p, {
  917. loadBeforeSend: function (jqXHR) {
  918. jqXHR.setRequestHeader("Prefer", 'odata.include-annotations="*"');
  919. }
  920. });
  921. }
  922. var root = '>feed';
  923. var entry = '>entry';
  924. var cell = '>content>properties';
  925. $.extend(true, p, {
  926. xmlReader: {
  927. root: function (data) {
  928. data = data.childNodes[0];
  929. data.innerHTML = data.innerHTML.replace(/<(\/?)([^:>\s]*:)?([^>]+)>/g, "<$1$3>");
  930. var param = $(data).attr('m:context');
  931. if (param) {
  932. p.odata.baseUrl = param.substring(0, param.indexOf('/$metadata'));
  933. p.odata.entityType = param.substring(param.indexOf('#') + 1).replace('/$entity', '');
  934. }
  935. param = $(data).attr('m:type');
  936. if (param) {
  937. p.odata.entityType = param.replace('#', '');
  938. }
  939. return data;
  940. },
  941. row: function (data) {
  942. if (data.localName === 'entry') {
  943. data = [data];
  944. }
  945. else {
  946. data = $(entry, data);
  947. }
  948. return data;
  949. },
  950. cell: function (data) {
  951. return $(cell, data).get(0).childNodes;
  952. },
  953. records: function (data) {
  954. return $(root + entry, data).length; //$('count', data).text()
  955. },
  956. page: function () {
  957. var skip = p.odata.postData.$skip + p.rowNum;
  958. return Math.ceil(skip / p.rowNum);
  959. },
  960. total: function (data) {
  961. var records = $(root + entry, data).length; //$('count', data).text()
  962. var skip = p.odata.postData.$skip + p.rowNum;
  963. return Math.ceil(skip / p.rowNum) + (records > 0 ? 1 : 0);
  964. },
  965. repeatitems: true,
  966. userdata: 'userdata',
  967. id: keyName
  968. }
  969. });
  970. }
  971. else {
  972. $.extend(true, p, {
  973. jsonReader: {
  974. root: function (data) {
  975. var param = data['@odata.context'];
  976. if (param) {
  977. p.odata.baseUrl = param.substring(0, param.indexOf('/$metadata'));
  978. p.odata.entityType = param.substring(param.indexOf('#') + 1).replace('/$entity', '');
  979. }
  980. param = data['@odata.type'];
  981. if (param) {
  982. p.odata.entityType = param.replace('#', '');
  983. }
  984. //data = $.jgrid.odataHelper.resolveJsonReferences(data);
  985. return data.value || [data];
  986. },
  987. repeatitems: true,
  988. id: keyName
  989. }
  990. });
  991. if (o.annotations) {
  992. $.extend(true, p, {
  993. loadBeforeSend: function (jqXHR) {
  994. jqXHR.setRequestHeader("Prefer", 'odata.include-annotations="*"');
  995. },
  996. jsonReader: {
  997. records: function (data) {
  998. return data[o.annotationName].records;
  999. },
  1000. page: function (data) { return data[o.annotationName].page; },
  1001. total: function (data) { return data[o.annotationName].total; },
  1002. userdata: function (data) { return data[o.annotationName].userdata; }
  1003. }
  1004. });
  1005. }
  1006. else {
  1007. $.extend(true, p, {
  1008. jsonReader: {
  1009. records: function (data) { return data["odata.count"] || data["@odata.count"]; },
  1010. page: function (data) {
  1011. var skip;
  1012. if (data["odata.nextLink"]) {
  1013. skip = parseInt(data["odata.nextLink"].split('skip=')[1], 10);
  1014. }
  1015. else {
  1016. skip = p.odata.postData.$skip + p.rowNum;
  1017. var total = data["odata.count"] || data["@odata.count"];
  1018. if (skip > total) { skip = total; }
  1019. }
  1020. return Math.ceil(skip / p.rowNum);
  1021. },
  1022. total: function (data) {
  1023. var total = data["odata.count"] || data["@odata.count"];
  1024. return Math.ceil(total / p.rowNum);
  1025. },
  1026. userdata: "userdata"
  1027. }
  1028. });
  1029. }
  1030. }
  1031. }
  1032. return this.each(function () {
  1033. var $t = this, $self = $(this), p = this.p;
  1034. if (!$t.grid || !p) { return; }
  1035. var o = $.extend(true, {
  1036. gencolumns: false,
  1037. odataurl: p.url,
  1038. datatype: 'json', //json,jsonp,xml
  1039. entitySet: null,
  1040. annotations: false,
  1041. annotationName: "@jqgrid.GridModelAnnotate",
  1042. odataverbs: {
  1043. inlineEditingAdd: 'POST',
  1044. inlineEditingEdit: 'PATCH',
  1045. formEditingAdd: 'POST',
  1046. formEditingEdit: 'PUT'
  1047. }
  1048. }, options || {});
  1049. if (o.datatype === 'jsonp') { o.callback = "jsonpCallback"; }
  1050. if (!o.entitySet) {
  1051. if ($.isFunction(o.errorfunc)) { o.errorfunc({}, 'entitySet cannot be empty', 0); }
  1052. return;
  1053. }
  1054. if (o.gencolumns) {
  1055. var gencol = $.extend(true, {
  1056. parsecolfunc: null,
  1057. parsemetadatafunc: null,
  1058. successfunc: null,
  1059. errorfunc: null,
  1060. async: false,
  1061. entitySet: null,
  1062. metadatatype: options.datatype || 'xml',
  1063. metadataurl: (options.odataurl || p.url) + '/$metadata'
  1064. }, options || {});
  1065. if (gencol.async) {
  1066. gencol.successfunc = function () {
  1067. if ($t.grid.hDiv) { $t.grid.hDiv.loading = false; }
  1068. $self.jqGrid('setGridParam', { datatype: o.datatype }).trigger('reloadGrid');
  1069. };
  1070. if ($t.grid.hDiv) { $t.grid.hDiv.loading = true; }
  1071. }
  1072. $self.jqGrid('odataGenColModel', gencol);
  1073. }
  1074. initDefaults(p, o);
  1075. });
  1076. },
  1077. odataGenColModel: function (options) {
  1078. var $t = this[0], p = $t.p, $self = $($t), mdata, coldata;
  1079. var o = $.extend(true, {
  1080. parsecolfunc: null,
  1081. parsemetadatafunc: null,
  1082. successfunc: null,
  1083. errorfunc: null,
  1084. entitySet: null,
  1085. metadataurl: p.url + '/$metadata',
  1086. metadatatype: 'xml', //json,jsonp,xml
  1087. expandable: 'link',
  1088. async: false
  1089. }, options || {});
  1090. if (o.metadatatype === 'jsonp') { o.callback = "jsonpCallback"; }
  1091. if (!o.entitySet) {
  1092. if ($.isFunction(o.errorfunc)) { o.errorfunc({}, 'entitySet cannot be empty', 0); }
  1093. return;
  1094. }
  1095. $.ajax({
  1096. url: o.metadataurl,
  1097. type: 'GET',
  1098. dataType: o.metadatatype,
  1099. jsonpCallback: o.callback,
  1100. //contentType: 'application/' + o.metadatatype + ';charset=utf-8',
  1101. //headers: {
  1102. //"OData-Version": "4.0"
  1103. //"Accept": "application/json;odata=light;q=1,application/json;odata=verbose;q=0.5"
  1104. //},
  1105. async: o.async,
  1106. cache: false
  1107. })
  1108. .done(function (data, st, xhr) {
  1109. var i = 0, j = 0, k = 0;
  1110. //var data = $.parseXML(data.responseText);
  1111. if (o.metadatatype === 'json' || o.metadatatype === 'jsonp') { data = $.jgrid.odataHelper.resolveJsonReferences(data); }
  1112. mdata = $self.triggerHandler("jqGridODataParseMetadata", data);
  1113. if (!mdata && $.isFunction(o.parsemetadatafunc)) { mdata = o.parsemetadatafunc(data, st, xhr); }
  1114. if (!mdata) {
  1115. mdata = $.jgrid.odataHelper.parseMetadata(data, o.metadatatype);
  1116. if (mdata) {
  1117. coldata = $self.triggerHandler("jqGridODataParseColumns", [o, mdata]);
  1118. if (!coldata && $.isFunction(o.parsecolfunc)) { coldata = o.parsecolfunc(o, mdata); }
  1119. if (!coldata) {
  1120. coldata = {};
  1121. for (i in mdata) {
  1122. if (mdata.hasOwnProperty(i) && i) {
  1123. coldata[i] = $self.jqGrid('parseColumns', mdata[i], o.expandable);
  1124. }
  1125. }
  1126. }
  1127. }
  1128. }
  1129. else {
  1130. coldata = mdata;
  1131. }
  1132. if (coldata) {
  1133. for (k in coldata) {
  1134. if (coldata.hasOwnProperty(k) && k) {
  1135. for (i = 0; i < p.colModel.length; i++) {
  1136. for (j = 0; j < coldata[k].length; j++) {
  1137. if (coldata[k][j].name === p.colModel[i].name) {
  1138. $.extend(true, coldata[k][j], p.colModel[i]);
  1139. break;
  1140. }
  1141. }
  1142. }
  1143. }
  1144. }
  1145. p.colModel = coldata[o.entitySet];
  1146. if (!p.colModel) {
  1147. if ($.isFunction(o.errorfunc)) { o.errorfunc({ data: data, status: st, xhr: xhr }, 'EntitySet ' + o.entitySet + ' is not found'); }
  1148. }
  1149. if (!p.odata) { p.odata = { iscollection: true }; }
  1150. p.odata.subgridCols = coldata;
  1151. if ($.isFunction(o.successfunc)) {
  1152. o.successfunc();
  1153. }
  1154. }
  1155. else {
  1156. if ($.isFunction(o.errorfunc)) { o.errorfunc({ data: data, status: st, xhr: xhr }, 'parse $metadata error'); }
  1157. }
  1158. })
  1159. .fail(function (xhr, err, code) {
  1160. if ($.isFunction(o.errorfunc)) {
  1161. var parsedError = $.jgrid.odataHelper.loadError(xhr, err, code);
  1162. o.errorfunc({ xhr: xhr, error: err, code: code }, parsedError);
  1163. }
  1164. });
  1165. return coldata;
  1166. }
  1167. //TODO: make function that checks allowed types of "odata.metadata"
  1168. /*getAllowedDataTypes: function(url, callback) {
  1169. $.ajax({
  1170. url: url,
  1171. type: 'HEAD'
  1172. })
  1173. .done(function (data, st, xhr) {
  1174. if($.isFunction(callback)) {
  1175. var result = [];
  1176. callback(result);
  1177. }
  1178. });
  1179. }*/
  1180. });
  1181. }));