bsselectobjectfieldrenderer.class.inc.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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 \Exception;
  20. use \CoreException;
  21. use \utils;
  22. use \IssueLog;
  23. use \Dict;
  24. use \UserRights;
  25. use \InlineImage;
  26. use \DBObjectSet;
  27. use \MetaModel;
  28. use \Combodo\iTop\Renderer\FieldRenderer;
  29. use \Combodo\iTop\Renderer\RenderingOutput;
  30. use \Combodo\iTop\Form\Field\SelectObjectField;
  31. /**
  32. * Description of BsSelectObjectFieldRenderer
  33. *
  34. * @author Guillaume Lajarige <guillaume.lajarige@combodo.com>
  35. */
  36. class BsSelectObjectFieldRenderer extends FieldRenderer
  37. {
  38. /**
  39. * Returns a RenderingOutput for the FieldRenderer's Field
  40. *
  41. * @return \Combodo\iTop\Renderer\RenderingOutput
  42. */
  43. public function Render()
  44. {
  45. $oOutput = new RenderingOutput();
  46. $sFieldValueClass = $this->oField->GetSearch()->GetClass();
  47. $sFieldMandatoryClass = ($this->oField->GetMandatory()) ? 'form_mandatory' : '';
  48. $iFieldControlType = $this->oField->GetControlType();
  49. // TODO : Remove this when hierarchical search supported
  50. $this->oField->SetHierarchical(false);
  51. // Rendering field in edition mode
  52. if (!$this->oField->GetReadOnly() && !$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. // - As a select
  62. if ($iFieldControlType === SelectObjectField::CONTROL_SELECT)
  63. {
  64. // Checking if regular select or autocomplete
  65. $oSearch = $this->oField->GetSearch()->DeepClone();
  66. $oCountSet = new DBObjectSet($oSearch);
  67. $iSetCount = $oCountSet->Count();
  68. $bRegularSelect = ($iSetCount <= $this->oField->GetMaximumComboLength());
  69. unset($oCountSet);
  70. // - For regular select
  71. if ($bRegularSelect)
  72. {
  73. // HTML for select part
  74. // - Opening row
  75. $oOutput->AddHtml('<div class="row">');
  76. // - Rendering select
  77. $oOutput->AddHtml('<div class="col-xs-' . ( $this->oField->GetHierarchical() ? 10 : 12 ) . ' col-sm-' . ( $this->oField->GetHierarchical() ? 9 : 12 ) . ' col-md-' . ( $this->oField->GetHierarchical() ? 10 : 12 ) . '">');
  78. $oOutput->AddHtml('<select id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" class="form-control">');
  79. $oOutput->AddHtml('<option value="">')->AddHtml(Dict::S('UI:SelectOne'), false)->AddHtml('</option>');
  80. // - Retrieving choices
  81. $oChoicesSet = new DBObjectSet($oSearch);
  82. while ($oChoice = $oChoicesSet->Fetch())
  83. {
  84. // Note : The test is a double equal on purpose as the type of the value received from the XHR is not always the same as the type of the allowed values. (eg : string vs int)
  85. $sSelectedAtt = ($this->oField->GetCurrentValue() == $oChoice->GetKey()) ? 'selected' : '';
  86. $oOutput->AddHtml('<option value="' . $oChoice->GetKey() . '" ' . $sSelectedAtt . ' >')->AddHtml($oChoice->GetName(), false)->AddHtml('</option>');
  87. }
  88. unset($oChoicesSet);
  89. $oOutput->AddHtml('</select>');
  90. $oOutput->AddHtml('</div>');
  91. // - Closing col for autocomplete & opening col for hierarchy, rendering hierarchy button, closing col and row
  92. $oOutput->AddHtml('<div class="col-xs-' . ( $this->oField->GetHierarchical() ? 2 : 0 ) . ' col-sm-' . ( $this->oField->GetHierarchical() ? 3 : 0 ) . ' col-md-' . ( $this->oField->GetHierarchical() ? 2 : 0 ) . ' text-right">');
  93. $this->RenderHierarchicalSearch($oOutput);
  94. $oOutput->AddHtml('</div>');
  95. // - Closing row
  96. $oOutput->AddHtml('</div>');
  97. // JS FieldChange trigger (:input are not always at the same depth)
  98. $oOutput->AddJs(
  99. <<<EOF
  100. $("#{$this->oField->GetGlobalId()}").off("change keyup").on("change keyup", function(){
  101. var me = this;
  102. $(this).closest(".field_set").trigger("field_change", {
  103. id: $(me).attr("id"),
  104. name: $(me).closest(".form_field").attr("data-field-id"),
  105. value: $(me).val()
  106. });
  107. });
  108. EOF
  109. );
  110. // Attaching JS widget
  111. $oOutput->AddJs(
  112. <<<EOF
  113. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").portal_form_field({
  114. 'validators': {$this->GetValidatorsAsJson()}
  115. });
  116. EOF
  117. );
  118. }
  119. // - For autocomplete
  120. else
  121. {
  122. $sAutocompleteFieldId = 's_ac_' . $this->oField->GetGlobalId();
  123. $sEndpoint = str_replace('-sMode-', 'autocomplete', $this->oField->GetSearchEndpoint());
  124. $sNoResultText = Dict::S('Portal:Autocomplete:NoResult');
  125. // Retrieving field value
  126. if ($this->oField->GetCurrentValue() !== null && $this->oField->GetCurrentValue() !== 0)
  127. {
  128. try
  129. {
  130. $oFieldValue = MetaModel::GetObject($sFieldValueClass, $this->oField->GetCurrentValue());
  131. }
  132. catch (CoreException $e)
  133. {
  134. IssueLog::Error('Could not retrieve object ' . $sFieldValueClass . '::' . $this->oField->GetCurrentValue() . ' for "' . $this->oField->GetId() . '" field.');
  135. throw new Exception($e->getMessage(), $e->getCode(), $e->getPrevious());
  136. }
  137. $sFieldValue = $oFieldValue->GetName();
  138. }
  139. else
  140. {
  141. $sFieldValue = '';
  142. }
  143. // HTML for autocomplete part
  144. // - Opening row
  145. $oOutput->AddHtml('<div class="row">');
  146. // - Rendering autocomplete search
  147. $oOutput->AddHtml('<div class="col-xs-' . ( $this->oField->GetHierarchical() ? 9 : 10 ) . ' col-sm-' . ( $this->oField->GetHierarchical() ? 8 : 9 ) . ' col-md-' . ( $this->oField->GetHierarchical() ? 8 : 10 ) . ' col-lg-' . ( $this->oField->GetHierarchical() ? 9 : 10 ) . '">');
  148. $oOutput->AddHtml('<input type="text" id="' . $sAutocompleteFieldId . '" name="' . $sAutocompleteFieldId . '" value="')->AddHtml($sFieldValue)->AddHtml('" data-target-id="' . $this->oField->GetGlobalId() . ' "class="form-control" />');
  149. $oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="' . $this->oField->GetCurrentValue() . '" />');
  150. $oOutput->AddHtml('</div>');
  151. // - Rendering buttons
  152. $oOutput->AddHtml('<div class="col-xs-' . ( $this->oField->GetHierarchical() ? 3 : 2 ) . ' col-sm-' . ( $this->oField->GetHierarchical() ? 4 : 3 ) . ' col-md-' . ( $this->oField->GetHierarchical() ? 4 : 2 ) . ' col-lg-' . ( $this->oField->GetHierarchical() ? 3 : 2 ) . ' text-right">');
  153. $oOutput->AddHtml('<div class="btn-group" role="group">');
  154. // - Rendering hierarchy button
  155. $this->RenderHierarchicalSearch($oOutput);
  156. // - Rendering regular search
  157. $this->RenderRegularSearch($oOutput);
  158. $oOutput->AddHtml('</div>');
  159. $oOutput->AddHtml('</div>');
  160. // - Closing row
  161. $oOutput->AddHtml('</div>');
  162. // JS FieldChange trigger (:input are not always at the same depth)
  163. // Note : Not used for that field type
  164. // Attaching JS widget
  165. $oOutput->AddJs(
  166. <<<EOF
  167. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").portal_form_field({
  168. 'validators': {$this->GetValidatorsAsJson()},
  169. 'get_current_value_callback': function(me, oEvent, oData){
  170. var value = null;
  171. value = me.element.find('#{$this->oField->GetGlobalId()}').val();
  172. return value;
  173. },
  174. 'set_current_value_callback': function(me, oEvent, oData){
  175. var sItemId = Object.keys(oData.value)[0];
  176. var sItemName = oData.value[sItemId];
  177. // Updating autocomplete field
  178. me.element.find('#{$this->oField->GetGlobalId()}').val(sItemId);
  179. me.element.find('#{$sAutocompleteFieldId}').val(sItemName);
  180. oAutocompleteSource_{$this->oField->GetId()}.index.datums[sItemId] = {id: sItemId, name: sItemName};
  181. //console.log('callback', oData);
  182. // Triggering field change event
  183. me.element.closest(".field_set").trigger("field_change", {
  184. id: me.element.find('#{$this->oField->GetGlobalId()}').attr("id"),
  185. name: me.element.find('#{$this->oField->GetGlobalId()}').attr("name"),
  186. value: me.element.find('#{$this->oField->GetGlobalId()}').val()
  187. });
  188. }
  189. });
  190. EOF
  191. );
  192. // Preparing JS part for autocomplete
  193. $oOutput->AddJs(
  194. <<<EOF
  195. var oAutocompleteSource_{$this->oField->GetId()} = new Bloodhound({
  196. queryTokenizer: Bloodhound.tokenizers.whitespace,
  197. datumTokenizer: Bloodhound.tokenizers.whitespace,
  198. remote: {
  199. url : '{$sEndpoint}',
  200. prepare: function(query, settings){
  201. settings.type = "POST";
  202. settings.contentType = "application/json; charset=UTF-8";
  203. settings.data = {
  204. sQuery: query,
  205. formmanager_class: $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").closest('.portal_form_handler').portal_form_handler('getOptions').formmanager_class,
  206. formmanager_data: $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").closest('.portal_form_handler').portal_form_handler('getOptions').formmanager_data,
  207. current_values: $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").closest('.portal_form_handler').portal_form_handler('getCurrentValues')
  208. }
  209. return settings;
  210. },
  211. filter: function(response){
  212. var oItems = response.results.items;
  213. // Manualy adding data from remote to the index.datums so we can check data later
  214. for(var sItemKey in oItems)
  215. {
  216. oAutocompleteSource_{$this->oField->GetId()}.index.datums[oItems[sItemKey].id] = oItems[sItemKey];
  217. }
  218. return oItems;
  219. }
  220. }
  221. });
  222. $('#$sAutocompleteFieldId').typeahead({
  223. hint: true,
  224. hightlight: true,
  225. minLength: {$this->oField->GetMinAutoCompleteChars()}
  226. },{
  227. name: '{$this->oField->GetId()}',
  228. source: oAutocompleteSource_{$this->oField->GetId()},
  229. limit: 20,
  230. display: 'name',
  231. templates: {
  232. suggestion: Handlebars.compile('<div>{{name}}</div>'),
  233. pending: $("#page_overlay .content_loader").prop('outerHTML'),
  234. notFound: '<div class="no_result">{$sNoResultText}</div>'
  235. }
  236. })
  237. .off('typeahead:select').on('typeahead:select', function(oEvent, oSuggestion){
  238. $('#{$this->oField->GetGlobalId()}').val(oSuggestion.id);
  239. // Triggering set_current_value event
  240. var oValue = {};
  241. oValue[oSuggestion.id] = oSuggestion.name;
  242. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").trigger('set_current_value', {value: oValue});
  243. })
  244. .off('typeahead:change').on('typeahead:change', function(oEvent, oSuggestion){
  245. // Checking if the value is a correct value. This is necessary because the user could empty the field / remove some chars and typeahead would not update the hidden input
  246. var oDatums = oAutocompleteSource_{$this->oField->GetId()}.index.datums;
  247. var bFound = false;
  248. for(var i in oDatums)
  249. {
  250. if(oDatums[i].name == oSuggestion)
  251. {
  252. bFound = true;
  253. $('#{$this->oField->GetGlobalId()}').val(oDatums[i].id);
  254. break;
  255. }
  256. }
  257. // Emptying the fields if value is incorrect
  258. if(!bFound)
  259. {
  260. $('#{$this->oField->GetGlobalId()}').val(0);
  261. $('#{$sAutocompleteFieldId}').val('');
  262. }
  263. });
  264. EOF
  265. );
  266. }
  267. }
  268. $oOutput->AddHtml('</div>');
  269. }
  270. // ... and in read-only mode (or hidden)
  271. else
  272. {
  273. // Retrieving field value
  274. if ($this->oField->GetCurrentValue() !== null && $this->oField->GetCurrentValue() !== 0 && $this->oField->GetCurrentValue() !== '')
  275. {
  276. $oFieldValue = MetaModel::GetObject($sFieldValueClass, $this->oField->GetCurrentValue());
  277. $sFieldValue = $oFieldValue->GetName();
  278. }
  279. else
  280. {
  281. $sFieldValue = Dict::S('UI:UndefinedObject');
  282. }
  283. $oOutput->AddHtml('<div class="form-group">');
  284. // Showing label / value only if read-only but not hidden
  285. if (!$this->oField->GetHidden())
  286. {
  287. if ($this->oField->GetLabel() !== '')
  288. {
  289. $oOutput->AddHtml('<label for="' . $this->oField->GetGlobalId() . '" class="control-label">')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
  290. }
  291. $oOutput->AddHtml('<div class="form-control-static">' . $sFieldValue . '</div>');
  292. }
  293. $oOutput->AddHtml('<input type="hidden" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" value="' . $this->oField->GetCurrentValue() . '" class="form-control" />');
  294. $oOutput->AddHtml('</div>');
  295. // JS FieldChange trigger (:input are not always at the same depth)
  296. $oOutput->AddJs(
  297. <<<EOF
  298. $("#{$this->oField->GetGlobalId()}").off("change keyup").on("change keyup", function(){
  299. var me = this;
  300. $(this).closest(".field_set").trigger("field_change", {
  301. id: $(me).attr("id"),
  302. name: $(me).closest(".form_field").attr("data-field-id"),
  303. value: $(me).val()
  304. });
  305. });
  306. EOF
  307. );
  308. // Attaching JS widget
  309. $oOutput->AddJs(
  310. <<<EOF
  311. $("[data-field-id='{$this->oField->GetId()}'][data-form-path='{$this->oField->GetFormPath()}']").portal_form_field({
  312. 'validators': {$this->GetValidatorsAsJson()}
  313. });
  314. EOF
  315. );
  316. }
  317. return $oOutput;
  318. }
  319. /**
  320. * Renders an hierarchical search button
  321. *
  322. * @param RenderingOutput $oOutput
  323. */
  324. protected function RenderHierarchicalSearch(RenderingOutput &$oOutput)
  325. {
  326. if ($this->oField->GetHierarchical())
  327. {
  328. $sHierarchicalButtonId = 's_hi_' . $this->oField->GetGlobalId();
  329. $sEndpoint = str_replace('-sMode-', 'hierarchy', $this->oField->GetSearchEndpoint());
  330. $oOutput->AddHtml('<button type="button" class="btn btn-default" id="' . $sHierarchicalButtonId . '"><span class="glyphicon glyphicon-ext-hierarchy"></span></button>');
  331. $oOutput->AddJs(
  332. <<<EOF
  333. $('#{$sHierarchicalButtonId}').off('click').on('click', function(){
  334. // Creating a new modal
  335. // Note : This could be better if we check for an existing modal first instead of always creating a new one
  336. var oModalElem = $('#modal-for-all').clone();
  337. oModalElem.attr('id', '').attr('data-source-element', '{$sHierarchicalButtonId}').appendTo('body');
  338. // Resizing to small modal
  339. oModalElem.find('.modal-dialog').removeClass('modal-lg').addClass('modal-sm');
  340. // Loading content
  341. oModalElem.find('.modal-content').html($('#page_overlay .overlay_content').html());
  342. oModalElem.find('.modal-content').load(
  343. '{$sEndpoint}',
  344. {
  345. sFormPath: '{$this->oField->GetFormPath()}',
  346. sFieldId: '{$this->oField->GetId()}'
  347. }
  348. );
  349. oModalElem.modal('show');
  350. });
  351. EOF
  352. );
  353. }
  354. }
  355. /**
  356. * Renders an regular search button
  357. *
  358. * @param RenderingOutput $oOutput
  359. */
  360. protected function RenderRegularSearch(RenderingOutput &$oOutput)
  361. {
  362. $sSearchButtonId = 's_rg_' . $this->oField->GetGlobalId();
  363. $sEndpoint = str_replace('-sMode-', 'from-attribute', $this->oField->GetSearchEndpoint());
  364. $oOutput->AddHtml('<button type="button" class="btn btn-default" id="' . $sSearchButtonId . '"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>');
  365. $oOutput->AddJs(
  366. <<<EOF
  367. $('#{$sSearchButtonId}').off('click').on('click', function(){
  368. // Creating a new modal
  369. var oModalElem;
  370. if($('.modal[data-source-element="{$sSearchButtonId}"]').length === 0)
  371. {
  372. oModalElem = $('#modal-for-all').clone();
  373. oModalElem.attr('id', '').attr('data-source-element', '{$sSearchButtonId}').appendTo('body');
  374. }
  375. else
  376. {
  377. oModalElem = $('.modal[data-source-element="{$sSearchButtonId}"]').first();
  378. }
  379. // Resizing to small modal
  380. oModalElem.find('.modal-dialog').removeClass('modal-sm').addClass('modal-lg');
  381. // Loading content
  382. oModalElem.find('.modal-content').html($('#page_overlay .overlay_content').html());
  383. oModalElem.find('.modal-content').load(
  384. '{$sEndpoint}',
  385. {
  386. sFormPath: '{$this->oField->GetFormPath()}',
  387. sFieldId: '{$this->oField->GetId()}',
  388. formmanager_class: $(this).closest('.portal_form_handler').portal_form_handler('getOptions').formmanager_class,
  389. formmanager_data: JSON.stringify($(this).closest('.portal_form_handler').portal_form_handler('getOptions').formmanager_data),
  390. current_values: $(this).closest('.portal_form_handler').portal_form_handler('getCurrentValues')
  391. }
  392. );
  393. oModalElem.modal('show');
  394. });
  395. EOF
  396. );
  397. }
  398. }