bslinkedsetfieldrenderer.class.inc.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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 BsSelectObjectFieldRenderer
  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('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. // Retrieving new rows ids
  168. var aObjectIds = Object.keys(oData.values);
  169. // Retrieving rows informations so we can add them
  170. $.post(
  171. '{$sObjectInformationsUrl}',
  172. {
  173. sObjectClass: '{$this->oField->GetTargetClass()}',
  174. aObjectIds: aObjectIds,
  175. aObjectAttCodes: $sAttCodesToDisplayAsJson
  176. },
  177. function(oData){
  178. // Updating datatables
  179. if(oData.items !== undefined)
  180. {
  181. for(var i in oData.items)
  182. {
  183. // Adding item to table only if it's not already there
  184. if($('#{$sTableId} tr#' + oData.items[i].id + '[role="row"]').length === 0)
  185. {
  186. // Making id negative in order to recognize it when persisting
  187. oData.items[i].id = -1 * parseInt(oData.items[i].id);
  188. oTable_{$this->oField->GetGlobalId()}.row.add(oData.items[i]);
  189. }
  190. }
  191. oTable_{$this->oField->GetGlobalId()}.draw();
  192. }
  193. }
  194. )
  195. .done(function(oData){
  196. // Updating hidden field
  197. var aData = oTable_{$this->oField->GetGlobalId()}.rows().data().toArray();
  198. var aObjectIds = [];
  199. for(var i in aData)
  200. {
  201. aObjectIds.push({id: aData[i].id});
  202. }
  203. $('#{$this->oField->GetGlobalId()}').val(JSON.stringify(aObjectIds));
  204. });
  205. }
  206. // We come from a button
  207. else
  208. {
  209. // Updating hidden field
  210. var aData = oTable_{$this->oField->GetGlobalId()}.rows().data().toArray();
  211. var aObjectIds = [];
  212. for(var i in aData)
  213. {
  214. aObjectIds.push({id: aData[i].id});
  215. }
  216. $('#{$this->oField->GetGlobalId()}').val(JSON.stringify(aObjectIds));
  217. }
  218. }
  219. });
  220. EOF
  221. );
  222. // Additional features if in edition mode
  223. if (!$this->oField->GetReadOnly())
  224. {
  225. // Rendering table
  226. // - Vars
  227. $sButtonAllId = 'btn_all_' . $this->oField->GetGlobalId();
  228. $sButtonNoneId = 'btn_none_' . $this->oField->GetGlobalId();
  229. $sButtonRemoveId = 'btn_remove_' . $this->oField->GetGlobalId();
  230. $sButtonAddId = 'btn_add_' . $this->oField->GetGlobalId();
  231. $sLabelAll = Dict::S('Core:BulkExport:CheckAll');
  232. $sLabelNone = Dict::S('Core:BulkExport:UncheckAll');
  233. $sLabelRemove = Dict::S('UI:Button:Remove');
  234. $sLabelAdd = Dict::S('UI:Button:AddObject');
  235. // - Output
  236. $oOutput->AddHtml(
  237. <<<EOF
  238. <div class="row">
  239. <div class="col-xs-6">
  240. <button type="button" class="btn btn-secondary" id="{$sButtonAllId}">{$sLabelAll}</button>
  241. <button type="button" class="btn btn-secondary" id="{$sButtonNoneId}">{$sLabelNone}</button>
  242. </div>
  243. <div class="col-xs-6 text-right">
  244. <button type="button" class="btn btn-danger" id="{$sButtonRemoveId}">{$sLabelRemove}</button>
  245. <button type="button" class="btn btn-default" id="{$sButtonAddId}">{$sLabelAdd}</button>
  246. </div>
  247. </div>
  248. EOF
  249. );
  250. // Rendering table widget
  251. // - Vars
  252. $sAddButtonEndpoint = str_replace('-sMode-', 'from-attribute', $this->oField->GetSearchEndpoint());
  253. // - Output
  254. $oOutput->AddJs(
  255. <<<EOF
  256. // Handles items selection/deselection
  257. // - Directly on the table
  258. oTable_{$this->oField->GetGlobalId()}.off('select').on('select', function(oEvent, dt, type, indexes){
  259. var aData = oTable_{$this->oField->GetGlobalId()}.rows(indexes).data().toArray();
  260. // Checking input
  261. $('#{$sTableId} tr[role="row"].selected td:first-child input').prop('checked', true);
  262. // Saving values in temp array
  263. for(var i in aData)
  264. {
  265. var iItemId = aData[i].id;
  266. if(!(iItemId in oSelectedItems_{$this->oField->GetGlobalId()}))
  267. {
  268. oSelectedItems_{$this->oField->GetGlobalId()}[iItemId] = aData[i].name;
  269. }
  270. }
  271. });
  272. oTable_{$this->oField->GetGlobalId()}.off('deselect').on('deselect', function(oEvent, dt, type, indexes){
  273. var aData = oTable_{$this->oField->GetGlobalId()}.rows(indexes).data().toArray();
  274. // Checking input
  275. $('#{$sTableId} tr[role="row"]:not(.selected) td:first-child input').prop('checked', false);
  276. // Saving values in temp array
  277. for(var i in aData)
  278. {
  279. var iItemId = aData[i].id;
  280. if(iItemId in oSelectedItems_{$this->oField->GetGlobalId()})
  281. {
  282. delete oSelectedItems_{$this->oField->GetGlobalId()}[iItemId];
  283. }
  284. }
  285. });
  286. // - From the bottom buttons
  287. $('#{$sButtonAllId}').off('click').on('click', function(){
  288. oTable_{$this->oField->GetGlobalId()}.rows().select();
  289. });
  290. $('#{$sButtonNoneId}').off('click').on('click', function(){
  291. oTable_{$this->oField->GetGlobalId()}.rows().deselect();
  292. });
  293. // Handles items remove/add
  294. $('#{$sButtonRemoveId}').off('click').on('click', function(){
  295. oTable_{$this->oField->GetGlobalId()}.rows({selected: true}).remove().draw();
  296. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").triggerHandler('set_current_value');
  297. });
  298. $('#{$sButtonAddId}').off('click').on('click', function(){
  299. // Creating a new modal
  300. var oModalElem;
  301. if($('.modal[data-source-element="{$sButtonAddId}"]').length === 0)
  302. {
  303. oModalElem = $('#modal-for-all').clone();
  304. oModalElem.attr('id', '').attr('data-source-element', '{$sButtonAddId}').appendTo('body');
  305. }
  306. else
  307. {
  308. oModalElem = $('.modal[data-source-element="{$sButtonAddId}"]').first();
  309. }
  310. // Resizing to small modal
  311. oModalElem.find('.modal-dialog').removeClass('modal-sm').addClass('modal-lg');
  312. // Loading content
  313. oModalElem.find('.modal-content').html($('#page_overlay .overlay_content').html());
  314. oModalElem.find('.modal-content').load(
  315. '{$sAddButtonEndpoint}',
  316. {
  317. sFormPath: '{$this->oField->GetFormPath()}',
  318. sFieldId: '{$this->oField->GetId()}'
  319. }
  320. );
  321. oModalElem.modal('show');
  322. });
  323. EOF
  324. );
  325. }
  326. }
  327. // ... and in hidden mode
  328. else
  329. {
  330. $oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="' . $sItemIdsAsJson . '" />');
  331. }
  332. // End of table rendering
  333. $oOutput->AddHtml('</div>');
  334. $oOutput->AddHtml('</div>');
  335. return $oOutput;
  336. }
  337. protected function PrepareItems(&$aItems, &$aItemIds)
  338. {
  339. $oValueSet = $this->oField->GetCurrentValue();
  340. $oValueSet->OptimizeColumnLoad(array($this->oField->GetTargetClass() => $this->oField->GetAttributesToDisplay(true)));
  341. while ($oItem = $oValueSet->Fetch())
  342. {
  343. $aItemProperties = array(
  344. 'id' => $oItem->GetKey(),
  345. 'name' => $oItem->GetName(),
  346. 'attributes' => array()
  347. );
  348. // In case of indirect linked set, we must retrieve the remote object
  349. if ($this->oField->IsIndirect())
  350. {
  351. $oRemoteItem = MetaModel::GetObject($this->oField->GetTargetClass(), $oItem->Get($this->oField->GetExtKeyToRemote()));
  352. }
  353. else
  354. {
  355. $oRemoteItem = $oItem;
  356. }
  357. foreach ($this->oField->GetAttributesToDisplay(true) as $sAttCode)
  358. {
  359. if ($sAttCode !== 'id')
  360. {
  361. $aAttProperties = array(
  362. 'att_code' => $sAttCode
  363. );
  364. $oAttDef = MetaModel::GetAttributeDef($this->oField->GetTargetClass(), $sAttCode);
  365. if ($oAttDef->IsExternalKey())
  366. {
  367. $aAttProperties['value'] = $oRemoteItem->Get($sAttCode . '_friendlyname');
  368. }
  369. else
  370. {
  371. $aAttProperties['value'] = $oAttDef->GetValueLabel($oRemoteItem->Get($sAttCode));
  372. }
  373. $aItemProperties['attributes'][$sAttCode] = $aAttProperties;
  374. }
  375. }
  376. $aItems[] = $aItemProperties;
  377. $aItemIds[] = array('id' => $oItem->GetKey());
  378. }
  379. }
  380. /**
  381. * Renders an regular search button
  382. *
  383. * @param RenderingOutput $oOutput
  384. */
  385. protected function RenderRegularSearch(RenderingOutput &$oOutput)
  386. {
  387. $sSearchButtonId = 's_rg_' . $this->oField->GetGlobalId();
  388. $sEndpoint = str_replace('-sMode-', 'from-attribute', $this->oField->GetSearchEndpoint());
  389. $oOutput->AddHtml('<div class="col-xs-2 col-lg-1">');
  390. $oOutput->AddHtml('<button type="button" class="btn btn-default" id="' . $sSearchButtonId . '">S</button>');
  391. $oOutput->AddHtml('</div>');
  392. $oOutput->AddJs(
  393. <<<EOF
  394. $('#{$sSearchButtonId}').off('click').on('click', function(){
  395. // Creating a new modal
  396. var oModalElem;
  397. if($('.modal[data-source-element="{$sSearchButtonId}"]').length === 0)
  398. {
  399. oModalElem = $('#modal-for-all').clone();
  400. oModalElem.attr('id', '').attr('data-source-element', '{$sSearchButtonId}').appendTo('body');
  401. }
  402. else
  403. {
  404. oModalElem = $('.modal[data-source-element="{$sSearchButtonId}"]').first();
  405. }
  406. // Resizing to small modal
  407. oModalElem.find('.modal-dialog').removeClass('modal-sm').addClass('modal-lg');
  408. // Loading content
  409. oModalElem.find('.modal-content').html($('#page_overlay .overlay_content').html());
  410. oModalElem.find('.modal-content').load(
  411. '{$sEndpoint}',
  412. {
  413. sFormPath: '{$this->oField->GetFormPath()}',
  414. sFieldId: '{$this->oField->GetId()}'
  415. }
  416. );
  417. oModalElem.modal('show');
  418. });
  419. EOF
  420. );
  421. }
  422. }