bsselectobjectfieldrenderer.class.inc.php 15 KB

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