bslinkedsetfieldrenderer.class.inc.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. <?php
  2. // Copyright (C) 2010-2017 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 \Exception;
  20. use \utils;
  21. use \IssueLog;
  22. use \Dict;
  23. use \UserRights;
  24. use \InlineImage;
  25. use \DBObjectSet;
  26. use \MetaModel;
  27. use \Combodo\iTop\Renderer\FieldRenderer;
  28. use \Combodo\iTop\Renderer\RenderingOutput;
  29. use \Combodo\iTop\Form\Field\LinkedSetField;
  30. /**
  31. * Description of BsLinkedSetFieldRenderer
  32. *
  33. * @author Guillaume Lajarige <guillaume.lajarige@combodo.com>
  34. */
  35. class BsLinkedSetFieldRenderer extends FieldRenderer
  36. {
  37. /**
  38. * Returns a RenderingOutput for the FieldRenderer's Field
  39. *
  40. * @return \Combodo\iTop\Renderer\RenderingOutput
  41. */
  42. public function Render()
  43. {
  44. $oOutput = new RenderingOutput();
  45. $oOutput->AddCssClass('form_field_' . $this->oField->GetDisplayMode());
  46. $sFieldMandatoryClass = ($this->oField->GetMandatory()) ? 'form_mandatory' : '';
  47. // Vars to build the table
  48. $sAttributesToDisplayAsJson = json_encode($this->oField->GetAttributesToDisplay());
  49. $sAttCodesToDisplayAsJson = json_encode($this->oField->GetAttributesToDisplay(true));
  50. $aItems = array();
  51. $aItemIds = array();
  52. $this->PrepareItems($aItems, $aItemIds);
  53. $sItemsAsJson = json_encode($aItems);
  54. $sItemIdsAsJson = htmlentities(json_encode(array('current' => $aItemIds)), ENT_QUOTES, 'UTF-8');
  55. if (!$this->oField->GetHidden())
  56. {
  57. // Rendering field
  58. $sIsEditable = ($this->oField->GetReadOnly()) ? 'false' : 'true';
  59. $sCollapseTogglerIconVisibleClass = 'glyphicon-menu-down';
  60. $sCollapseTogglerIconHiddenClass = 'glyphicon-menu-down collapsed';
  61. $sCollapseTogglerClass = 'form_linkedset_toggler';
  62. $sCollapseTogglerId = $sCollapseTogglerClass . '_' . $this->oField->GetGlobalId();
  63. $sFieldWrapperId = 'form_linkedset_wrapper_' . $this->oField->GetGlobalId();
  64. // Preparing collapsed state
  65. if($this->oField->GetDisplayOpened())
  66. {
  67. $sCollapseTogglerExpanded = 'true';
  68. $sCollapseTogglerIconClass = $sCollapseTogglerIconVisibleClass;
  69. $sCollapseJSInitState = 'true';
  70. }
  71. else
  72. {
  73. $sCollapseTogglerClass .= ' collapsed';
  74. $sCollapseTogglerExpanded = 'false';
  75. $sCollapseTogglerIconClass = $sCollapseTogglerIconHiddenClass;
  76. $sCollapseJSInitState = 'false';
  77. }
  78. $oOutput->AddHtml('<div class="form-group ' . $sFieldMandatoryClass . '">');
  79. if ($this->oField->GetLabel() !== '')
  80. {
  81. $oOutput->AddHtml('<label for="' . $this->oField->GetGlobalId() . '" class="control-label">')
  82. ->AddHtml('<a id="' . $sCollapseTogglerId . '" class="' . $sCollapseTogglerClass . '" data-toggle="collapse" href="#' . $sFieldWrapperId . '" aria-expanded="' . $sCollapseTogglerExpanded . '" aria-controls="' . $sFieldWrapperId . '">')
  83. ->AddHtml($this->oField->GetLabel(), true)
  84. ->AddHtml('<span class="text">' . count($aItemIds) . '</span>')
  85. ->AddHtml('<span class="glyphicon ' . $sCollapseTogglerIconClass . '"></>')
  86. ->AddHtml('</a>')
  87. ->AddHtml('</label>');
  88. }
  89. $oOutput->AddHtml('<div class="help-block"></div>');
  90. // Rendering table
  91. // - Vars
  92. $sTableId = 'table_' . $this->oField->GetGlobalId();
  93. // - Output
  94. $oOutput->AddHtml(
  95. <<<EOF
  96. <div class="form_linkedset_wrapper collapse" id="{$sFieldWrapperId}">
  97. <div class="row">
  98. <div class="col-xs-12">
  99. <input type="hidden" id="{$this->oField->GetGlobalId()}" name="{$this->oField->GetId()}" value="{$sItemIdsAsJson}" />
  100. <table id="{$sTableId}" data-field-id="{$this->oField->GetId()}" class="table table-striped table-bordered responsive" cellspacing="0" width="100%">
  101. <tbody>
  102. </tbody>
  103. </table>
  104. </div>
  105. </div>
  106. EOF
  107. );
  108. // Rendering table widget
  109. // - Vars
  110. $sEmptyTableLabel = htmlentities(Dict::S(($this->oField->GetReadOnly()) ? 'Portal:Datatables:Language:EmptyTable' : 'UI:Message:EmptyList:UseAdd'), ENT_QUOTES, 'UTF-8');
  111. $sLabelGeneralCheckbox = htmlentities(Dict::S('Core:BulkExport:CheckAll') . ' / ' . Dict::S('Core:BulkExport:UncheckAll'), ENT_QUOTES, 'UTF-8');
  112. $sSelectionOptionHtml = ($this->oField->GetReadOnly()) ? 'false' : '{"style": "multi"}';
  113. $sSelectionInputGlobalHtml = ($this->oField->GetReadOnly()) ? '' : '<span class="row_input"><input type="checkbox" id="' . $this->oField->GetGlobalId() . '_check_all" name="' . $this->oField->GetGlobalId() . '_check_all" title="' . $sLabelGeneralCheckbox . '" /></span>';
  114. $sSelectionInputHtml = ($this->oField->GetReadOnly()) ? '' : '<span class="row_input"><input type="checkbox" name="' . $this->oField->GetGlobalId() . '" /></span>';
  115. // - Output
  116. $oOutput->AddJs(
  117. <<<EOF
  118. // Collapse handlers
  119. // - Collapsing by default to optimize form space
  120. // It would be better to be able to construct the widget as collapsed, but in this case, datatables thinks the container is very small and therefore renders the table as if it was in microbox.
  121. $('#{$sFieldWrapperId}').collapse({toggle: {$sCollapseJSInitState}});
  122. // - Change toggle icon class
  123. $('#{$sFieldWrapperId}').on('shown.bs.collapse', function(){
  124. // Creating the table if null (first expand). If we create it on start, it will be displayed as if it was in a micro screen due to the div being "display: none;"
  125. if(oTable_{$this->oField->GetGlobalId()} === undefined)
  126. {
  127. buildTable_{$this->oField->GetGlobalId()}();
  128. }
  129. })
  130. .on('show.bs.collapse', function(){
  131. $('#{$sCollapseTogglerId} > span.glyphicon').removeClass('{$sCollapseTogglerIconHiddenClass}').addClass('{$sCollapseTogglerIconVisibleClass}');
  132. })
  133. .on('hide.bs.collapse', function(){
  134. $('#{$sCollapseTogglerId} > span.glyphicon').removeClass('{$sCollapseTogglerIconVisibleClass}').addClass('{$sCollapseTogglerIconHiddenClass}');
  135. });
  136. // Places a loader in the empty datatables
  137. $('#{$sTableId} > tbody').html('<tr><td class="datatables_overlay" colspan="100">' + $('#page_overlay').html() + '</td></tr>');
  138. // Prepares data for datatables
  139. var oColumnProperties_{$this->oField->GetGlobalId()} = {$sAttributesToDisplayAsJson};
  140. var oRawDatas_{$this->oField->GetGlobalId()} = {$sItemsAsJson};
  141. var oTable_{$this->oField->GetGlobalId()};
  142. var oSelectedItems_{$this->oField->GetGlobalId()} = {};
  143. var getColumnsDefinition_{$this->oField->GetGlobalId()} = function()
  144. {
  145. var aColumnsDefinition = [];
  146. if({$sIsEditable})
  147. {
  148. aColumnsDefinition.push({
  149. "width": "auto",
  150. "searchable": false,
  151. "sortable": false,
  152. "title": '{$sSelectionInputGlobalHtml}',
  153. "type": "html",
  154. "data": "",
  155. "render": function(data, type, row)
  156. {
  157. var oCheckboxElem = $('{$sSelectionInputHtml}');
  158. oCheckboxElem.find(':input').attr('data-object-id', row.id).attr('data-target-object-id', row.target_id);
  159. return oCheckboxElem.prop('outerHTML');
  160. }
  161. });
  162. }
  163. for(sKey in oColumnProperties_{$this->oField->GetGlobalId()})
  164. {
  165. // Level main column
  166. aColumnsDefinition.push({
  167. "width": "auto",
  168. "searchable": true,
  169. "sortable": true,
  170. "title": oColumnProperties_{$this->oField->GetGlobalId()}[sKey],
  171. "defaultContent": "",
  172. "type": "html",
  173. "data": "attributes."+sKey+".att_code",
  174. "render": function(data, type, row){
  175. var cellElem;
  176. // Preparing the cell data
  177. if(row.attributes[data].url !== undefined)
  178. {
  179. cellElem = $('<a></a>');
  180. cellElem.attr('target', '_blank').attr('href', row.attributes[data].url);
  181. }
  182. else
  183. {
  184. cellElem = $('<span></span>');
  185. }
  186. cellElem.html('<span>' + row.attributes[data].value + '</span>');
  187. return cellElem.prop('outerHTML');
  188. },
  189. });
  190. }
  191. return aColumnsDefinition;
  192. };
  193. // Helper to build the datatable
  194. // Note : Those options should be externalized in an library so we can use them on any DataTables for the portal.
  195. // We would just have to override / complete the necessary elements
  196. var buildTable_{$this->oField->GetGlobalId()} = function()
  197. {
  198. var iDefaultOrderColumnIndex = ({$sIsEditable}) ? 1 : 0;
  199. // Instanciates datatables
  200. oTable_{$this->oField->GetGlobalId()} = $('#{$sTableId}').DataTable({
  201. "language": {
  202. "emptyTable": "{$sEmptyTableLabel}"
  203. },
  204. "displayLength": -1,
  205. "scrollY": "300px",
  206. "scrollCollapse": true,
  207. "order": [[iDefaultOrderColumnIndex, "asc"]],
  208. "dom": 't',
  209. "columns": getColumnsDefinition_{$this->oField->GetGlobalId()}(),
  210. "select": {$sSelectionOptionHtml},
  211. "rowId": "id",
  212. "data": oRawDatas_{$this->oField->GetGlobalId()},
  213. });
  214. // Handles items selection/deselection
  215. // - Directly on the table
  216. oTable_{$this->oField->GetGlobalId()}.off('select').on('select', function(oEvent, dt, type, indexes){
  217. var aData = oTable_{$this->oField->GetGlobalId()}.rows(indexes).data().toArray();
  218. // Checking input
  219. $('#{$sTableId} tbody tr[role="row"].selected td:first-child input').prop('checked', true);
  220. // Saving values in temp array
  221. for(var i in aData)
  222. {
  223. var iItemId = aData[i].id;
  224. if(!(iItemId in oSelectedItems_{$this->oField->GetGlobalId()}))
  225. {
  226. oSelectedItems_{$this->oField->GetGlobalId()}[iItemId] = aData[i].name;
  227. }
  228. }
  229. // Updating remove button
  230. updateRemoveButtonState_{$this->oField->GetGlobalId()}();
  231. });
  232. oTable_{$this->oField->GetGlobalId()}.off('deselect').on('deselect', function(oEvent, dt, type, indexes){
  233. var aData = oTable_{$this->oField->GetGlobalId()}.rows(indexes).data().toArray();
  234. // Checking input
  235. $('#{$sTableId} tbody tr[role="row"]:not(.selected) td:first-child input').prop('checked', false);
  236. // Saving values in temp array
  237. for(var i in aData)
  238. {
  239. var iItemId = aData[i].id;
  240. if(iItemId in oSelectedItems_{$this->oField->GetGlobalId()})
  241. {
  242. delete oSelectedItems_{$this->oField->GetGlobalId()}[iItemId];
  243. }
  244. }
  245. // Unchecking global checkbox
  246. $('#{$this->oField->GetGlobalId()}_check_all').prop('checked', false);
  247. // Updating remove button
  248. updateRemoveButtonState_{$this->oField->GetGlobalId()}();
  249. });
  250. // - From the global button
  251. $('#{$this->oField->GetGlobalId()}_check_all').off('click').on('click', function(oEvent){
  252. if($(this).prop('checked'))
  253. {
  254. oTable_{$this->oField->GetGlobalId()}.rows().select();
  255. }
  256. else
  257. {
  258. oTable_{$this->oField->GetGlobalId()}.rows().deselect();
  259. }
  260. updateRemoveButtonState_{$this->oField->GetGlobalId()}();
  261. });
  262. };
  263. EOF
  264. );
  265. // Additional features if in edition mode
  266. if (!$this->oField->GetReadOnly())
  267. {
  268. // Attaching JS widget
  269. $sObjectInformationsUrl = $this->oField->GetInformationEndpoint();
  270. $oOutput->AddJs(
  271. <<<EOF
  272. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").portal_form_field({
  273. 'validators': {$this->GetValidatorsAsJson()},
  274. 'get_current_value_callback': function(me, oEvent, oData){
  275. var value = null;
  276. // Retrieving JSON value as a string and not an object
  277. //
  278. // 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.
  279. // Which was an issue when deleting all objects from linkedset
  280. //
  281. // Old code : value = JSON.parse(me.element.find('#{$this->oField->GetGlobalId()}').val());
  282. value = me.element.find('#{$this->oField->GetGlobalId()}').val();
  283. return value;
  284. },
  285. 'set_current_value_callback': function(me, oEvent, oData){
  286. // When we have data (meaning that we picked objects from search)
  287. if(oData !== undefined && Object.keys(oData.values).length > 0)
  288. {
  289. // Showing loader while retrieving informations
  290. $('#page_overlay').fadeIn(200);
  291. // Retrieving new rows ids
  292. var aObjectIds = Object.keys(oData.values);
  293. // Retrieving rows informations so we can add them
  294. $.post(
  295. '{$sObjectInformationsUrl}',
  296. {
  297. sObjectClass: '{$this->oField->GetTargetClass()}',
  298. aObjectIds: aObjectIds,
  299. aObjectAttCodes: $sAttCodesToDisplayAsJson
  300. },
  301. function(oData){
  302. // Updating datatables
  303. if(oData.items !== undefined)
  304. {
  305. for(var i in oData.items)
  306. {
  307. // Adding target item id information
  308. oData.items[i].target_id = oData.items[i].id;
  309. // Adding item to table only if it's not already there
  310. if($('#{$sTableId} tr[role="row"] > td input[data-target-object-id="' + oData.items[i].target_id + '"], #{$sTableId} tr[role="row"] > td input[data-target-object-id="' + (oData.items[i].target_id*-1) + '"]').length === 0)
  311. {
  312. // Making id negative in order to recognize it when persisting
  313. oData.items[i].id = -1 * parseInt(oData.items[i].id);
  314. oTable_{$this->oField->GetGlobalId()}.row.add(oData.items[i]);
  315. }
  316. }
  317. oTable_{$this->oField->GetGlobalId()}.draw();
  318. // Updating input
  319. updateInputValue_{$this->oField->GetGlobalId()}();
  320. }
  321. }
  322. )
  323. .done(function(oData){
  324. // Updating items count
  325. updateItemCount_{$this->oField->GetGlobalId()}();
  326. // Updating global checkbox
  327. $('#{$this->oField->GetGlobalId()}_check_all').prop('checked', false);
  328. })
  329. .always(function(oData){
  330. // Hiding loader
  331. $('#page_overlay').fadeOut(200);
  332. });
  333. }
  334. // We come from a button
  335. else
  336. {
  337. // Updating input
  338. updateInputValue_{$this->oField->GetGlobalId()}();
  339. // Updating items count
  340. updateItemCount_{$this->oField->GetGlobalId()}();
  341. // Updating global checkbox
  342. $('#{$this->oField->GetGlobalId()}_check_all').prop('checked', false);
  343. }
  344. }
  345. });
  346. EOF
  347. );
  348. // Rendering table
  349. // - Vars
  350. $sButtonRemoveId = 'btn_remove_' . $this->oField->GetGlobalId();
  351. $sButtonAddId = 'btn_add_' . $this->oField->GetGlobalId();
  352. $sLabelRemove = Dict::S('UI:Button:Remove');
  353. $sLabelAdd = Dict::S('UI:Button:AddObject');
  354. // - Output
  355. $oOutput->AddHtml(
  356. <<<EOF
  357. <div class="row">
  358. <div class="col-xs-12">
  359. <div class="btn-group" role="group">
  360. <button type="button" class="btn btn-sm btn-danger" id="{$sButtonRemoveId}" title="{$sLabelRemove}" disabled><span class="glyphicon glyphicon-minus"></span></button>
  361. <button type="button" class="btn btn-sm btn-default" id="{$sButtonAddId}" title="{$sLabelAdd}"><span class="glyphicon glyphicon-plus"></span></button>
  362. </div>
  363. </div>
  364. </div>
  365. EOF
  366. );
  367. // Rendering table widget
  368. // - Vars
  369. $sAddButtonEndpoint = str_replace('-sMode-', 'from-attribute', $this->oField->GetSearchEndpoint());
  370. // - Output
  371. $oOutput->AddJs(
  372. <<<EOF
  373. // Handles items selection/deselection
  374. // - Remove button state handler
  375. var updateRemoveButtonState_{$this->oField->GetGlobalId()} = function()
  376. {
  377. var bIsDisabled = (Object.keys(oSelectedItems_{$this->oField->GetGlobalId()}).length == 0);
  378. $('#{$sButtonRemoveId}').prop('disabled', bIsDisabled);
  379. };
  380. // - Item count state handler
  381. var updateItemCount_{$this->oField->GetGlobalId()} = function()
  382. {
  383. $('#{$sCollapseTogglerId} > .text').text( oTable_{$this->oField->GetGlobalId()}.rows().count() );
  384. };
  385. // - Field input handler
  386. var updateInputValue_{$this->oField->GetGlobalId()} = function()
  387. {
  388. // Retrieving table rows
  389. var aData = oTable_{$this->oField->GetGlobalId()}.rows().data().toArray();
  390. // Retrieving input values
  391. var oValues = JSON.parse($('#{$this->oField->GetGlobalId()}').val());
  392. oValues.add = {};
  393. oValues.remove = {};
  394. // Checking removed objects
  395. for(var i in oValues.current)
  396. {
  397. if($('#{$sTableId} tr[role="row"] input[data-object-id="'+i+'"]').length === 0)
  398. {
  399. oValues.remove[i] = {};
  400. }
  401. }
  402. // Checking added objects
  403. for(var i in aData)
  404. {
  405. if(oValues.current[aData[i].id] === undefined)
  406. {
  407. oValues.add[aData[i].target_id] = {};
  408. }
  409. }
  410. // Setting input values
  411. $('#{$this->oField->GetGlobalId()}').val(JSON.stringify(oValues));
  412. };
  413. // Handles items remove/add
  414. $('#{$sButtonRemoveId}').off('click').on('click', function(){
  415. // Removing items from table
  416. oTable_{$this->oField->GetGlobalId()}.rows({selected: true}).remove().draw();
  417. // Resetting selected items
  418. oSelectedItems_{$this->oField->GetGlobalId()} = {};
  419. // Updating form value
  420. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").triggerHandler('set_current_value');
  421. // Updating global checkbox state
  422. $('#{$this->oField->GetGlobalId()}_check_all').prop('checked', false);
  423. // Updating remove button
  424. updateRemoveButtonState_{$this->oField->GetGlobalId()}();
  425. });
  426. $('#{$sButtonAddId}').off('click').on('click', function(){
  427. // Preparing current values
  428. var aObjectIdsToIgnore = [];
  429. $('#{$sTableId} tr[role="row"] > td input[data-target-object-id]').each(function(iIndex, oElem){
  430. aObjectIdsToIgnore.push( $(oElem).attr('data-target-object-id') );
  431. });
  432. // Creating a new modal
  433. var oModalElem;
  434. if($('.modal[data-source-element="{$sButtonAddId}"]').length === 0)
  435. {
  436. oModalElem = $('#modal-for-all').clone();
  437. oModalElem.attr('id', '').attr('data-source-element', '{$sButtonAddId}').appendTo('body');
  438. }
  439. else
  440. {
  441. oModalElem = $('.modal[data-source-element="{$sButtonAddId}"]').first();
  442. }
  443. // Resizing to small modal
  444. oModalElem.find('.modal-dialog').removeClass('modal-sm').addClass('modal-lg');
  445. // Loading content
  446. oModalElem.find('.modal-content').html($('#page_overlay .overlay_content').html());
  447. oModalElem.find('.modal-content').load(
  448. '{$sAddButtonEndpoint}',
  449. {
  450. sFormPath: '{$this->oField->GetFormPath()}',
  451. sFieldId: '{$this->oField->GetId()}',
  452. aObjectIdsToIgnore : aObjectIdsToIgnore
  453. },
  454. function(sResponseText, sStatus, oXHR){
  455. // Hiding modal in case of error as the general AJAX error handler will display a message
  456. if(sStatus === 'error')
  457. {
  458. oModalElem.modal('hide');
  459. }
  460. }
  461. );
  462. oModalElem.modal('show');
  463. });
  464. EOF
  465. );
  466. }
  467. }
  468. // ... and in hidden mode
  469. else
  470. {
  471. $oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="' . $sItemIdsAsJson . '" />');
  472. }
  473. // End of table rendering
  474. $oOutput->AddHtml('</div>');
  475. $oOutput->AddHtml('</div>');
  476. return $oOutput;
  477. }
  478. protected function PrepareItems(&$aItems, &$aItemIds)
  479. {
  480. $oValueSet = $this->oField->GetCurrentValue();
  481. $oValueSet->OptimizeColumnLoad(array($this->oField->GetTargetClass() => $this->oField->GetAttributesToDisplay(true)));
  482. while ($oItem = $oValueSet->Fetch())
  483. {
  484. // In case of indirect linked set, we must retrieve the remote object
  485. if ($this->oField->IsIndirect())
  486. {
  487. try{
  488. // Note : AllowAllData set to true here instead of checking scope's flag because we are displaying a value that has been set and validated
  489. $oRemoteItem = MetaModel::GetObject($this->oField->GetTargetClass(), $oItem->Get($this->oField->GetExtKeyToRemote()), true, true);
  490. }
  491. catch(Exception $e)
  492. {
  493. // In some cases we can't retrieve an object from a linkedset, eg. when the extkey to remote is 0 due to a database corruption.
  494. // Rather than crashing we rather just skip the object like in the administration console
  495. IssueLog::Error('Could not retrieve object of linkedset in form #'.$this->oField->GetFormPath().' for field #'.$this->oField->GetId().'. Message: '.$e->getMessage());
  496. continue;
  497. }
  498. }
  499. else
  500. {
  501. $oRemoteItem = $oItem;
  502. }
  503. $aItemProperties = array(
  504. 'id' => ($this->oField->IsIndirect() && $oItem->IsNew()) ? -1*$oRemoteItem->GetKey() : $oItem->GetKey(),
  505. 'target_id' => $oRemoteItem->GetKey(),
  506. 'name' => $oItem->GetName(),
  507. 'attributes' => array()
  508. );
  509. // Target object others attributes
  510. foreach ($this->oField->GetAttributesToDisplay(true) as $sAttCode)
  511. {
  512. if ($sAttCode !== 'id')
  513. {
  514. $aAttProperties = array(
  515. 'att_code' => $sAttCode
  516. );
  517. $oAttDef = MetaModel::GetAttributeDef($this->oField->GetTargetClass(), $sAttCode);
  518. if ($oAttDef->IsExternalKey())
  519. {
  520. $aAttProperties['value'] = $oRemoteItem->Get($sAttCode . '_friendlyname');
  521. }
  522. else
  523. {
  524. $aAttProperties['value'] = $oAttDef->GetValueLabel($oRemoteItem->Get($sAttCode));
  525. }
  526. $aItemProperties['attributes'][$sAttCode] = $aAttProperties;
  527. }
  528. }
  529. $aItems[] = $aItemProperties;
  530. $aItemIds[$aItemProperties['id']] = array();
  531. }
  532. }
  533. }