bslinkedsetfieldrenderer.class.inc.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. <?php
  2. // Copyright (C) 2010-2016 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. namespace Combodo\iTop\Renderer\Bootstrap\FieldRenderer;
  19. use \utils;
  20. use \Dict;
  21. use \UserRights;
  22. use \InlineImage;
  23. use \DBObjectSet;
  24. use \MetaModel;
  25. use \Combodo\iTop\Renderer\FieldRenderer;
  26. use \Combodo\iTop\Renderer\RenderingOutput;
  27. use \Combodo\iTop\Form\Field\LinkedSetField;
  28. /**
  29. * Description of BsLinkedSetFieldRenderer
  30. *
  31. * @author Guillaume Lajarige <guillaume.lajarige@combodo.com>
  32. */
  33. class BsLinkedSetFieldRenderer extends FieldRenderer
  34. {
  35. /**
  36. * Returns a RenderingOutput for the FieldRenderer's Field
  37. *
  38. * @return \Combodo\iTop\Renderer\RenderingOutput
  39. */
  40. public function Render()
  41. {
  42. $oOutput = new RenderingOutput();
  43. $sFieldMandatoryClass = ($this->oField->GetMandatory()) ? 'form_mandatory' : '';
  44. // Vars to build the table
  45. $sAttributesToDisplayAsJson = json_encode($this->oField->GetAttributesToDisplay());
  46. $sAttCodesToDisplayAsJson = json_encode($this->oField->GetAttributesToDisplay(true));
  47. $aItems = array();
  48. $aItemIds = array();
  49. $this->PrepareItems($aItems, $aItemIds);
  50. $sItemsAsJson = json_encode($aItems);
  51. $sItemIdsAsJson = htmlentities(json_encode($aItemIds), ENT_QUOTES, 'UTF-8');
  52. if (!$this->oField->GetHidden())
  53. {
  54. // Rendering field
  55. $oOutput->AddHtml('<div class="form-group ' . $sFieldMandatoryClass . '">');
  56. if ($this->oField->GetLabel() !== '')
  57. {
  58. $oOutput->AddHtml('<label for="' . $this->oField->GetGlobalId() . '" class="control-label">')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
  59. }
  60. $oOutput->AddHtml('<div class="help-block"></div>');
  61. // Rendering table
  62. // - Vars
  63. $sTableId = 'table_' . $this->oField->GetGlobalId();
  64. // - Output
  65. $oOutput->AddHtml(
  66. <<<EOF
  67. <div class="form_linkedset_wrapper">
  68. <div class="row">
  69. <div class="col-xs-12">
  70. <input type="hidden" id="{$this->oField->GetGlobalId()}" name="{$this->oField->GetId()}" value="{$sItemIdsAsJson}" />
  71. <table id="{$sTableId}" data-field-id="{$this->oField->GetId()}" class="table table-striped table-bordered responsive" cellspacing="0" width="100%">
  72. <tbody>
  73. </tbody>
  74. </table>
  75. </div>
  76. </div>
  77. EOF
  78. );
  79. // Rendering table widget
  80. // - Vars
  81. $sEmptyTableLabel = htmlentities(Dict::S( ($this->oField->GetReadOnly()) ? 'Portal:Datatables:Language:EmptyTable' : 'UI:Message:EmptyList:UseAdd'), ENT_QUOTES, 'UTF-8');
  82. $sSelectionOptionHtml = ($this->oField->GetReadOnly()) ? 'false' : '{"style": "multi"}';
  83. $sSelectionInputHtml = ($this->oField->GetReadOnly()) ? '' : '<span class="row_input"><input type="checkbox" name="' . $this->oField->GetId() . '" /></span>';
  84. // - Output
  85. $oOutput->AddJs(
  86. <<<EOF
  87. var oColumnProperties_{$this->oField->GetGlobalId()} = {$sAttributesToDisplayAsJson};
  88. var oRawDatas_{$this->oField->GetGlobalId()} = {$sItemsAsJson};
  89. var oTable_{$this->oField->GetGlobalId()};
  90. var oSelectedItems_{$this->oField->GetGlobalId()} = {};
  91. var getColumnsDefinition_{$this->oField->GetGlobalId()} = function()
  92. {
  93. var aColumnsDefinition = [];
  94. var sFirstColumnId = Object.keys(oColumnProperties_{$this->oField->GetGlobalId()})[0];
  95. for(sKey in oColumnProperties_{$this->oField->GetGlobalId()})
  96. {
  97. // Level main column
  98. aColumnsDefinition.push({
  99. "width": "auto",
  100. "searchable": true,
  101. "sortable": true,
  102. "title": oColumnProperties_{$this->oField->GetGlobalId()}[sKey],
  103. "defaultContent": "",
  104. "type": "html",
  105. "data": "attributes."+sKey+".att_code",
  106. "render": function(data, type, row){
  107. var cellElem;
  108. // Preparing the cell data
  109. if(row.attributes[data].url !== undefined)
  110. {
  111. cellElem = $('<a></a>');
  112. cellElem.attr('target', '_blank').attr('href', row.attributes[data].url);
  113. }
  114. else
  115. {
  116. cellElem = $('<span></span>');
  117. }
  118. cellElem.attr('data-object-id', row.id).html('<span>' + row.attributes[data].value + '</span>');
  119. if(data === sFirstColumnId)
  120. {
  121. cellElem.prepend('{$sSelectionInputHtml}');
  122. }
  123. return cellElem.prop('outerHTML');
  124. },
  125. });
  126. }
  127. return aColumnsDefinition;
  128. };
  129. // Note : Those options should be externalized in an library so we can use them on any DataTables for the portal.
  130. // We would just have to override / complete the necessary elements
  131. oTable_{$this->oField->GetGlobalId()} = $('#{$sTableId}').DataTable({
  132. "language": {
  133. "emptyTable": "{$sEmptyTableLabel}"
  134. },
  135. "displayLength": -1,
  136. "scrollY": "300px",
  137. "scrollCollapse": true,
  138. "dom": 't',
  139. "columns": getColumnsDefinition_{$this->oField->GetGlobalId()}(),
  140. "select": {$sSelectionOptionHtml},
  141. "rowId": "id",
  142. "data": oRawDatas_{$this->oField->GetGlobalId()},
  143. });
  144. EOF
  145. );
  146. // Attaching JS widget
  147. $sObjectInformationsUrl = $this->oField->GetInformationEndpoint();
  148. $oOutput->AddJs(
  149. <<<EOF
  150. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").portal_form_field({
  151. 'validators': {$this->GetValidatorsAsJson()},
  152. 'get_current_value_callback': function(me, oEvent, oData){
  153. var value = null;
  154. // Retrieving JSON value as a string and not an object
  155. //
  156. // Note : The value is passed as a string instead of an array because the attribute would not be included in the posted data when empty.
  157. // Which was an issue when deleting all objects from linkedset
  158. //
  159. // Old code : value = JSON.parse(me.element.find('#{$this->oField->GetGlobalId()}').val());
  160. value = me.element.find('#{$this->oField->GetGlobalId()}').val();
  161. return value;
  162. },
  163. 'set_current_value_callback': function(me, oEvent, oData){
  164. // When we have data (meaning that we picked objects from search)
  165. if(oData !== undefined && Object.keys(oData.values).length > 0)
  166. {
  167. // Showing loader while retrieving informations
  168. $('#page_overlay').fadeIn(200);
  169. // Retrieving new rows ids
  170. var aObjectIds = Object.keys(oData.values);
  171. // Retrieving rows informations so we can add them
  172. $.post(
  173. '{$sObjectInformationsUrl}',
  174. {
  175. sObjectClass: '{$this->oField->GetTargetClass()}',
  176. aObjectIds: aObjectIds,
  177. aObjectAttCodes: $sAttCodesToDisplayAsJson
  178. },
  179. function(oData){
  180. // Updating datatables
  181. if(oData.items !== undefined)
  182. {
  183. for(var i in oData.items)
  184. {
  185. // Adding item to table only if it's not already there
  186. if($('#{$sTableId} tr#' + oData.items[i].id + '[role="row"]').length === 0)
  187. {
  188. // Making id negative in order to recognize it when persisting
  189. oData.items[i].id = -1 * parseInt(oData.items[i].id);
  190. oTable_{$this->oField->GetGlobalId()}.row.add(oData.items[i]);
  191. }
  192. }
  193. oTable_{$this->oField->GetGlobalId()}.draw();
  194. }
  195. }
  196. )
  197. .done(function(oData){
  198. // Updating hidden field
  199. var aData = oTable_{$this->oField->GetGlobalId()}.rows().data().toArray();
  200. var aObjectIds = [];
  201. for(var i in aData)
  202. {
  203. aObjectIds.push({id: aData[i].id});
  204. }
  205. $('#{$this->oField->GetGlobalId()}').val(JSON.stringify(aObjectIds));
  206. })
  207. .always(function(oData){
  208. // Hiding loader
  209. $('#page_overlay').fadeOut(200);
  210. });
  211. }
  212. // We come from a button
  213. else
  214. {
  215. // Updating hidden field
  216. var aData = oTable_{$this->oField->GetGlobalId()}.rows().data().toArray();
  217. var aObjectIds = [];
  218. for(var i in aData)
  219. {
  220. aObjectIds.push({id: aData[i].id});
  221. }
  222. $('#{$this->oField->GetGlobalId()}').val(JSON.stringify(aObjectIds));
  223. }
  224. }
  225. });
  226. EOF
  227. );
  228. // Additional features if in edition mode
  229. if (!$this->oField->GetReadOnly())
  230. {
  231. // Rendering table
  232. // - Vars
  233. $sButtonAllId = 'btn_all_' . $this->oField->GetGlobalId();
  234. $sButtonNoneId = 'btn_none_' . $this->oField->GetGlobalId();
  235. $sButtonRemoveId = 'btn_remove_' . $this->oField->GetGlobalId();
  236. $sButtonAddId = 'btn_add_' . $this->oField->GetGlobalId();
  237. $sLabelAll = Dict::S('Core:BulkExport:CheckAll');
  238. $sLabelNone = Dict::S('Core:BulkExport:UncheckAll');
  239. $sLabelRemove = Dict::S('UI:Button:Remove');
  240. $sLabelAdd = Dict::S('UI:Button:AddObject');
  241. // - Output
  242. $oOutput->AddHtml(
  243. <<<EOF
  244. <div class="row">
  245. <div class="col-xs-6">
  246. <button type="button" class="btn btn-secondary" id="{$sButtonAllId}">{$sLabelAll}</button>
  247. <button type="button" class="btn btn-secondary" id="{$sButtonNoneId}">{$sLabelNone}</button>
  248. </div>
  249. <div class="col-xs-6 text-right">
  250. <button type="button" class="btn btn-danger" id="{$sButtonRemoveId}">{$sLabelRemove}</button>
  251. <button type="button" class="btn btn-default" id="{$sButtonAddId}">{$sLabelAdd}</button>
  252. </div>
  253. </div>
  254. EOF
  255. );
  256. // Rendering table widget
  257. // - Vars
  258. $sAddButtonEndpoint = str_replace('-sMode-', 'from-attribute', $this->oField->GetSearchEndpoint());
  259. // - Output
  260. $oOutput->AddJs(
  261. <<<EOF
  262. // Handles items selection/deselection
  263. // - Directly on the table
  264. oTable_{$this->oField->GetGlobalId()}.off('select').on('select', function(oEvent, dt, type, indexes){
  265. var aData = oTable_{$this->oField->GetGlobalId()}.rows(indexes).data().toArray();
  266. // Checking input
  267. $('#{$sTableId} tr[role="row"].selected td:first-child input').prop('checked', true);
  268. // Saving values in temp array
  269. for(var i in aData)
  270. {
  271. var iItemId = aData[i].id;
  272. if(!(iItemId in oSelectedItems_{$this->oField->GetGlobalId()}))
  273. {
  274. oSelectedItems_{$this->oField->GetGlobalId()}[iItemId] = aData[i].name;
  275. }
  276. }
  277. });
  278. oTable_{$this->oField->GetGlobalId()}.off('deselect').on('deselect', function(oEvent, dt, type, indexes){
  279. var aData = oTable_{$this->oField->GetGlobalId()}.rows(indexes).data().toArray();
  280. // Checking input
  281. $('#{$sTableId} tr[role="row"]:not(.selected) td:first-child input').prop('checked', false);
  282. // Saving values in temp array
  283. for(var i in aData)
  284. {
  285. var iItemId = aData[i].id;
  286. if(iItemId in oSelectedItems_{$this->oField->GetGlobalId()})
  287. {
  288. delete oSelectedItems_{$this->oField->GetGlobalId()}[iItemId];
  289. }
  290. }
  291. });
  292. // - From the bottom buttons
  293. $('#{$sButtonAllId}').off('click').on('click', function(){
  294. oTable_{$this->oField->GetGlobalId()}.rows().select();
  295. });
  296. $('#{$sButtonNoneId}').off('click').on('click', function(){
  297. oTable_{$this->oField->GetGlobalId()}.rows().deselect();
  298. });
  299. // Handles items remove/add
  300. $('#{$sButtonRemoveId}').off('click').on('click', function(){
  301. oTable_{$this->oField->GetGlobalId()}.rows({selected: true}).remove().draw();
  302. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").triggerHandler('set_current_value');
  303. });
  304. $('#{$sButtonAddId}').off('click').on('click', function(){
  305. // Creating a new modal
  306. var oModalElem;
  307. if($('.modal[data-source-element="{$sButtonAddId}"]').length === 0)
  308. {
  309. oModalElem = $('#modal-for-all').clone();
  310. oModalElem.attr('id', '').attr('data-source-element', '{$sButtonAddId}').appendTo('body');
  311. }
  312. else
  313. {
  314. oModalElem = $('.modal[data-source-element="{$sButtonAddId}"]').first();
  315. }
  316. // Resizing to small modal
  317. oModalElem.find('.modal-dialog').removeClass('modal-sm').addClass('modal-lg');
  318. // Loading content
  319. oModalElem.find('.modal-content').html($('#page_overlay .overlay_content').html());
  320. oModalElem.find('.modal-content').load(
  321. '{$sAddButtonEndpoint}',
  322. {
  323. sFormPath: '{$this->oField->GetFormPath()}',
  324. sFieldId: '{$this->oField->GetId()}'
  325. }
  326. );
  327. oModalElem.modal('show');
  328. });
  329. EOF
  330. );
  331. }
  332. }
  333. // ... and in hidden mode
  334. else
  335. {
  336. $oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="' . $sItemIdsAsJson . '" />');
  337. }
  338. // End of table rendering
  339. $oOutput->AddHtml('</div>');
  340. $oOutput->AddHtml('</div>');
  341. return $oOutput;
  342. }
  343. protected function PrepareItems(&$aItems, &$aItemIds)
  344. {
  345. $oValueSet = $this->oField->GetCurrentValue();
  346. $oValueSet->OptimizeColumnLoad(array($this->oField->GetTargetClass() => $this->oField->GetAttributesToDisplay(true)));
  347. while ($oItem = $oValueSet->Fetch())
  348. {
  349. $aItemProperties = array(
  350. 'id' => $oItem->GetKey(),
  351. 'name' => $oItem->GetName(),
  352. 'attributes' => array()
  353. );
  354. // In case of indirect linked set, we must retrieve the remote object
  355. if ($this->oField->IsIndirect())
  356. {
  357. $oRemoteItem = MetaModel::GetObject($this->oField->GetTargetClass(), $oItem->Get($this->oField->GetExtKeyToRemote()));
  358. }
  359. else
  360. {
  361. $oRemoteItem = $oItem;
  362. }
  363. foreach ($this->oField->GetAttributesToDisplay(true) as $sAttCode)
  364. {
  365. if ($sAttCode !== 'id')
  366. {
  367. $aAttProperties = array(
  368. 'att_code' => $sAttCode
  369. );
  370. $oAttDef = MetaModel::GetAttributeDef($this->oField->GetTargetClass(), $sAttCode);
  371. if ($oAttDef->IsExternalKey())
  372. {
  373. $aAttProperties['value'] = $oRemoteItem->Get($sAttCode . '_friendlyname');
  374. }
  375. else
  376. {
  377. $aAttProperties['value'] = $oAttDef->GetValueLabel($oRemoteItem->Get($sAttCode));
  378. }
  379. $aItemProperties['attributes'][$sAttCode] = $aAttProperties;
  380. }
  381. }
  382. $aItems[] = $aItemProperties;
  383. $aItemIds[] = array('id' => $oItem->GetKey());
  384. }
  385. }
  386. /**
  387. * Renders an regular search button
  388. *
  389. * @param RenderingOutput $oOutput
  390. */
  391. protected function RenderRegularSearch(RenderingOutput &$oOutput)
  392. {
  393. $sSearchButtonId = 's_rg_' . $this->oField->GetGlobalId();
  394. $sEndpoint = str_replace('-sMode-', 'from-attribute', $this->oField->GetSearchEndpoint());
  395. $oOutput->AddHtml('<div class="col-xs-2 col-lg-1">');
  396. $oOutput->AddHtml('<button type="button" class="btn btn-default" id="' . $sSearchButtonId . '">S</button>');
  397. $oOutput->AddHtml('</div>');
  398. $oOutput->AddJs(
  399. <<<EOF
  400. $('#{$sSearchButtonId}').off('click').on('click', function(){
  401. // Creating a new modal
  402. var oModalElem;
  403. if($('.modal[data-source-element="{$sSearchButtonId}"]').length === 0)
  404. {
  405. oModalElem = $('#modal-for-all').clone();
  406. oModalElem.attr('id', '').attr('data-source-element', '{$sSearchButtonId}').appendTo('body');
  407. }
  408. else
  409. {
  410. oModalElem = $('.modal[data-source-element="{$sSearchButtonId}"]').first();
  411. }
  412. // Resizing to small modal
  413. oModalElem.find('.modal-dialog').removeClass('modal-sm').addClass('modal-lg');
  414. // Loading content
  415. oModalElem.find('.modal-content').html($('#page_overlay .overlay_content').html());
  416. oModalElem.find('.modal-content').load(
  417. '{$sEndpoint}',
  418. {
  419. sFormPath: '{$this->oField->GetFormPath()}',
  420. sFieldId: '{$this->oField->GetId()}'
  421. }
  422. );
  423. oModalElem.modal('show');
  424. });
  425. EOF
  426. );
  427. }
  428. }