extra_field_option.lib.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\ExtraFieldOptions;
  4. /**
  5. * Class ExtraFieldOption
  6. * Handles the extra fields for various objects (users, sessions, courses).
  7. */
  8. class ExtraFieldOption extends Model
  9. {
  10. public $columns = [
  11. 'id',
  12. 'field_id',
  13. 'option_value',
  14. 'display_text',
  15. 'option_order',
  16. 'priority',
  17. 'priority_message',
  18. 'tms',
  19. ];
  20. public $extraField;
  21. public $fieldId;
  22. /**
  23. * Gets the table for the type of object for which we are using an extra field.
  24. *
  25. * @param string $type Type of object (course, user or session)
  26. */
  27. public function __construct($type)
  28. {
  29. parent::__construct();
  30. $this->type = $type;
  31. $extraField = new ExtraField($this->type);
  32. $this->extraField = $extraField;
  33. $this->table = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
  34. $this->tableExtraField = Database::get_main_table(TABLE_EXTRA_FIELD);
  35. }
  36. /**
  37. * @return ExtraField
  38. */
  39. public function getExtraField()
  40. {
  41. return $this->extraField;
  42. }
  43. /**
  44. * Gets the number of options already available in the table for this item type.
  45. *
  46. * @return int Number of options available
  47. * @assert () >= 0
  48. */
  49. /*public function get_count()
  50. {
  51. $row = Database::select('count(*) as count', $this->table, array(), 'first');
  52. return $row['count'];
  53. }*/
  54. /**
  55. * Gets the number of options available for this field.
  56. *
  57. * @param int $fieldId
  58. *
  59. * @return int Number of options
  60. * @assert ('') === false
  61. * @assert (-1) == 0
  62. * @assert (0) == 0
  63. */
  64. public function get_count_by_field_id($fieldId)
  65. {
  66. if (empty($fieldId)) {
  67. return false;
  68. }
  69. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  70. $fieldId = intval($fieldId);
  71. $sql = "SELECT count(*) as count
  72. FROM $this->table o
  73. INNER JOIN $this->tableExtraField e
  74. ON o.field_id = e.id
  75. WHERE
  76. o.field_id = $fieldId AND
  77. e.extra_field_type = $extraFieldType ";
  78. $result = Database::query($sql);
  79. $result = Database::fetch_array($result);
  80. return $result['count'];
  81. }
  82. /**
  83. * Returns a list of options for a specific field, separated by ";".
  84. *
  85. * @param int $field_id
  86. * @param bool $add_id_in_array Indicates whether we want the results to be given with their id
  87. * @param string $ordered_by Order by clause (without the "order by") to be added to the SQL query
  88. *
  89. * @return string List of options separated by ;
  90. * @assert (-1, false, null) == ''
  91. */
  92. public function getFieldOptionsToString($field_id, $add_id_in_array = false, $ordered_by = null)
  93. {
  94. $options = self::get_field_options_by_field($field_id, $add_id_in_array, $ordered_by);
  95. $new_options = [];
  96. if (!empty($options)) {
  97. foreach ($options as $option) {
  98. $new_options[] = $option['option_value'].':'.$option['display_text'];
  99. }
  100. $string = implode(';', $new_options);
  101. return $string;
  102. }
  103. return '';
  104. }
  105. /**
  106. * Delete all the options of a specific field.
  107. *
  108. * @param int $field_id
  109. *
  110. * @assert (-1) === false
  111. */
  112. public function delete_all_options_by_field_id($field_id)
  113. {
  114. $field_id = intval($field_id);
  115. $sql = "DELETE FROM {$this->table} WHERE field_id = $field_id";
  116. $r = Database::query($sql);
  117. return $r;
  118. }
  119. /**
  120. * @param array $params
  121. * @param bool $showQuery
  122. *
  123. * @return int|bool
  124. */
  125. public function saveOptions($params, $showQuery = false)
  126. {
  127. $optionInfo = $this->get_field_option_by_field_and_option(
  128. $params['field_id'],
  129. $params['option_value']
  130. );
  131. if ($optionInfo == false) {
  132. $optionValue = api_replace_dangerous_char($params['option_value']);
  133. $order = $this->get_max_order($params['field_id']);
  134. $newParams = [
  135. 'field_id' => $params['field_id'],
  136. 'value' => trim($optionValue),
  137. 'display_text' => trim($params['display_text']),
  138. 'option_order' => $order,
  139. ];
  140. return parent::save($newParams, $showQuery);
  141. }
  142. return false;
  143. }
  144. /**
  145. * Saves an option into the corresponding *_field_options table.
  146. *
  147. * @param array $params Parameters to be considered for the insertion
  148. * @param bool $showQuery Whether to show the query (sent to the parent save() method)
  149. *
  150. * @return bool True on success, false on error
  151. * @assert (array('field_id'=>0), false) === false
  152. * @assert (array('field_id'=>1), false) === true
  153. */
  154. public function save($params, $showQuery = false)
  155. {
  156. $field_id = intval($params['field_id']);
  157. if (empty($field_id)) {
  158. return false;
  159. }
  160. $parseOptions = in_array(
  161. $params['field_type'],
  162. [
  163. ExtraField::FIELD_TYPE_RADIO,
  164. ExtraField::FIELD_TYPE_SELECT,
  165. ExtraField::FIELD_TYPE_SELECT_MULTIPLE,
  166. ExtraField::FIELD_TYPE_DOUBLE_SELECT,
  167. ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD,
  168. ExtraField::FIELD_TYPE_TRIPLE_SELECT,
  169. ]
  170. );
  171. if (empty($params['field_options']) || !$parseOptions) {
  172. return true;
  173. }
  174. switch ($params['field_type']) {
  175. case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
  176. //$params['field_options'] = France:Paris;Bretagne;Marseilles;Lyon|Belgique:Bruxelles;Namur;Liège;Bruges|Peru:Lima;Piura;
  177. case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
  178. //$params['field_options'] = Option 1|Option 2|Option 3
  179. $options_parsed = ExtraField::extra_field_double_select_convert_string_to_array(
  180. $params['field_options']
  181. );
  182. if (empty($options_parsed)) {
  183. break;
  184. }
  185. foreach ($options_parsed as $key => $option) {
  186. $new_params = [
  187. 'field_id' => $field_id,
  188. 'option_value' => 0,
  189. 'display_text' => $option['label'],
  190. 'option_order' => 0,
  191. ];
  192. // Looking if option already exists:
  193. $option_info = self::get_field_option_by_field_id_and_option_display_text(
  194. $field_id,
  195. $option['label']
  196. );
  197. if (empty($option_info)) {
  198. $sub_id = parent::save($new_params, $showQuery);
  199. } else {
  200. $sub_id = $option_info['id'];
  201. $new_params['id'] = $sub_id;
  202. parent::update($new_params, $showQuery);
  203. }
  204. if ($params['field_type'] == ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD) {
  205. continue;
  206. }
  207. foreach ($option['options'] as $sub_option) {
  208. if (empty($sub_option)) {
  209. continue;
  210. }
  211. $new_params = [
  212. 'field_id' => $field_id,
  213. 'option_value' => $sub_id,
  214. 'display_text' => $sub_option,
  215. 'option_order' => 0,
  216. ];
  217. $option_info = self::getFieldOptionByFieldIdAndOptionDisplayTextAndOptionValue(
  218. $field_id,
  219. $sub_option,
  220. $sub_id
  221. );
  222. if (empty($option_info)) {
  223. parent::save($new_params, $showQuery);
  224. continue;
  225. }
  226. $new_params['id'] = $option_info['id'];
  227. parent::update($new_params, $showQuery);
  228. }
  229. }
  230. break;
  231. case ExtraField::FIELD_TYPE_TRIPLE_SELECT:
  232. //Format: Option1\Option11:Option111;Option112\Option12:Option121|Option2\Option21:Option211
  233. $options = ExtraField::tripleSelectConvertStringToArray($params['field_options']);
  234. if (!$options) {
  235. break;
  236. }
  237. foreach ($options as $level1) {
  238. $level1Params = [
  239. 'field_id' => $field_id,
  240. 'option_value' => 0,
  241. 'display_text' => $level1['label'],
  242. 'option_order' => 0,
  243. ];
  244. $optionInfo = self::get_field_option_by_field_id_and_option_display_text(
  245. $field_id,
  246. $level1['label']
  247. );
  248. if (empty($optionInfo)) {
  249. $level1Id = parent::save($level1Params);
  250. } else {
  251. $level1Id = $optionInfo['id'];
  252. $level1Params['id'] = $level1Id;
  253. parent::update($level1Params);
  254. }
  255. foreach ($level1['options'] as $level2) {
  256. $level2Params = [
  257. 'field_id' => $field_id,
  258. 'option_value' => $level1Id,
  259. 'display_text' => $level2['label'],
  260. 'display_order' => 0,
  261. ];
  262. $optionInfo = self::getFieldOptionByFieldIdAndOptionDisplayTextAndOptionValue(
  263. $field_id,
  264. $level2['label'],
  265. $level1Id
  266. );
  267. if (empty($optionInfo)) {
  268. $level2Id = parent::save($level2Params);
  269. } else {
  270. $level2Id = $optionInfo['id'];
  271. $level2Params['id'] = $level2Id;
  272. parent::update($level2Params);
  273. }
  274. foreach ($level2['options'] as $level3) {
  275. foreach ($level3 as $item) {
  276. $level3Params = [
  277. 'field_id' => $field_id,
  278. 'option_value' => $level2Id,
  279. 'display_text' => $item,
  280. 'display_order' => 0,
  281. ];
  282. $optionInfo = self::getFieldOptionByFieldIdAndOptionDisplayTextAndOptionValue(
  283. $field_id,
  284. $item,
  285. $level2Id
  286. );
  287. if (empty($optionInfo)) {
  288. parent::save($level3Params);
  289. } else {
  290. $level3Params['id'] = $optionInfo['id'];
  291. parent::update($level3Params);
  292. }
  293. }
  294. }
  295. }
  296. }
  297. break;
  298. default:
  299. $list = explode(';', $params['field_options']);
  300. foreach ($list as $option) {
  301. $option_info = $this->get_field_option_by_field_and_option($field_id, $option);
  302. // Use URLify only for new items
  303. $optionValue = api_replace_dangerous_char($option);
  304. $option = trim($option);
  305. if ($option_info != false) {
  306. continue;
  307. }
  308. $order = $this->get_max_order($field_id);
  309. $new_params = [
  310. 'field_id' => $field_id,
  311. 'option_value' => trim($optionValue),
  312. 'display_text' => trim($option),
  313. 'option_order' => $order,
  314. ];
  315. parent::save($new_params, $showQuery);
  316. }
  317. break;
  318. }
  319. return true;
  320. }
  321. /**
  322. * Save one option item at a time.
  323. *
  324. * @param array $params Parameters specific to the option
  325. * @param bool $show_query Whether to show the query (sent to parent save() method)
  326. * @param bool $insert_repeated Whether to insert even if the option already exists
  327. *
  328. * @return bool True on success, false on failure
  329. * @assert (array('field_id'=>0),false) === false
  330. * @assert (array('field_id'=>0),false) === true
  331. */
  332. public function save_one_item($params, $show_query = false, $insert_repeated = true)
  333. {
  334. $field_id = intval($params['field_id']);
  335. if (empty($field_id)) {
  336. return false;
  337. }
  338. if (isset($params['option_value'])) {
  339. $params['option_value'] = trim($params['option_value']);
  340. }
  341. if (isset($params['display_text'])) {
  342. $params['display_text'] = trim($params['display_text']);
  343. }
  344. if (empty($params['option_order'])) {
  345. $order = $this->get_max_order($field_id);
  346. $params['option_order'] = $order;
  347. }
  348. if ($insert_repeated) {
  349. parent::save($params, $show_query);
  350. } else {
  351. $check = $this->get_field_option_by_field_and_option(
  352. $field_id,
  353. $params['option_value']
  354. );
  355. if ($check == false) {
  356. parent::save($params, $show_query);
  357. }
  358. }
  359. return true;
  360. }
  361. /**
  362. * Get the complete row of a specific option of a specific field.
  363. *
  364. * @param int $field_id
  365. * @param string $option_value Value of the option
  366. *
  367. * @return mixed The row on success or false on failure
  368. * @assert (0,'') === false
  369. */
  370. public function get_field_option_by_field_and_option($field_id, $option_value)
  371. {
  372. $field_id = intval($field_id);
  373. $option_value = Database::escape_string($option_value);
  374. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  375. $sql = "SELECT s.* FROM {$this->table} s
  376. INNER JOIN {$this->tableExtraField} sf
  377. ON (s.field_id = sf.id)
  378. WHERE
  379. field_id = $field_id AND
  380. option_value = '".$option_value."' AND
  381. sf.extra_field_type = $extraFieldType
  382. ";
  383. $result = Database::query($sql);
  384. if (Database::num_rows($result) > 0) {
  385. return Database::store_result($result, 'ASSOC');
  386. }
  387. return false;
  388. }
  389. /**
  390. * Get the complete row of a specific option's display text of a specific field.
  391. *
  392. * @param int $field_id
  393. * @param string $option_display_text Display value of the option
  394. *
  395. * @return mixed The row on success or false on failure
  396. * @assert (0, '') === false
  397. */
  398. public function get_field_option_by_field_id_and_option_display_text($field_id, $option_display_text)
  399. {
  400. $field_id = intval($field_id);
  401. $option_display_text = Database::escape_string($option_display_text);
  402. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  403. $sql = "SELECT s.* FROM {$this->table} s
  404. INNER JOIN {$this->tableExtraField} sf
  405. ON (s.field_id = sf.id)
  406. WHERE
  407. field_id = $field_id AND
  408. s.display_text = '".$option_display_text."' AND
  409. sf.extra_field_type = $extraFieldType
  410. ";
  411. $result = Database::query($sql);
  412. if (Database::num_rows($result) > 0) {
  413. return Database::fetch_array($result, 'ASSOC');
  414. }
  415. return false;
  416. }
  417. /**
  418. * Get the complete row of a specific option's display text of a specific field.
  419. *
  420. * @param int $field_id
  421. * @param string $option_display_text Display value of the option
  422. * @param string $option_value Value of the option
  423. *
  424. * @return mixed The row on success or false on failure
  425. * @assert (0, '', '') === false
  426. */
  427. public function getFieldOptionByFieldIdAndOptionDisplayTextAndOptionValue(
  428. $field_id,
  429. $option_display_text,
  430. $option_value
  431. ) {
  432. $field_id = intval($field_id);
  433. $option_display_text = Database::escape_string($option_display_text);
  434. $option_value = Database::escape_string($option_value);
  435. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  436. $sql = "SELECT s.* FROM {$this->table} s
  437. INNER JOIN {$this->tableExtraField} sf
  438. ON (s.field_id = sf.id)
  439. WHERE
  440. field_id = $field_id AND
  441. sf.display_text = '".$option_display_text."' AND
  442. option_value = '$option_value' AND
  443. sf.extra_field_type = ".$extraFieldType."
  444. ";
  445. $result = Database::query($sql);
  446. if (Database::num_rows($result) > 0) {
  447. return Database::fetch_array($result, 'ASSOC');
  448. }
  449. return false;
  450. }
  451. /**
  452. * Gets an array of options for a specific field.
  453. *
  454. * @param int $field_id The field ID
  455. * @param bool $add_id_in_array Whether to add the row ID in the result
  456. * @param null $ordered_by Extra ordering query bit
  457. *
  458. * @return array The options if they exists. Otherwise return false
  459. */
  460. public function get_field_options_by_field($field_id, $add_id_in_array = false, $ordered_by = null)
  461. {
  462. $field_id = intval($field_id);
  463. $orderBy = null;
  464. switch ($ordered_by) {
  465. case 'id':
  466. $orderBy = ['id' => 'ASC'];
  467. break;
  468. case 'field_id':
  469. $orderBy = ['fieldId' => 'ASC'];
  470. break;
  471. case 'option_value':
  472. $orderBy = ['optionValue' => 'ASC'];
  473. break;
  474. case 'display_text':
  475. $orderBy = ['displayText' => 'ASC'];
  476. break;
  477. case 'priority':
  478. $orderBy = ['priority' => 'ASC'];
  479. break;
  480. case 'priority_message':
  481. $orderBy = ['priorityMessage' => 'ASC'];
  482. break;
  483. case 'option_order':
  484. $orderBy = ['optionOrder' => 'ASC'];
  485. break;
  486. }
  487. $result = Database::getManager()
  488. ->getRepository('ChamiloCoreBundle:ExtraFieldOptions')
  489. ->findBy(['field' => $field_id], $orderBy);
  490. if (!$result) {
  491. return false;
  492. }
  493. $options = [];
  494. /** @var ExtraFieldOptions $row */
  495. foreach ($result as $row) {
  496. $option = [
  497. 'id' => $row->getId(),
  498. 'field_id' => $row->getField()->getId(),
  499. 'option_value' => $row->getValue(),
  500. 'display_text' => self::translateDisplayName($row->getDisplayText()),
  501. 'priority' => $row->getPriority(),
  502. 'priority_message' => $row->getPriorityMessage(),
  503. 'option_order' => $row->getOptionOrder(),
  504. ];
  505. if ($add_id_in_array) {
  506. $options[$row->getId()] = $option;
  507. continue;
  508. }
  509. $options[] = $option;
  510. }
  511. return $options;
  512. }
  513. /**
  514. * Get options for a specific field as array or in JSON format suited for the double-select format.
  515. *
  516. * @param int $option_value_id Option value ID
  517. * @param bool $to_json Return format (whether it should be formatted to JSON or not)
  518. *
  519. * @return mixed Row/JSON on success
  520. */
  521. public function get_second_select_field_options_by_field($option_value_id, $to_json = false)
  522. {
  523. $em = Database::getManager();
  524. $option = $em->find('ChamiloCoreBundle:ExtraFieldOptions', intval($option_value_id));
  525. if (!$option) {
  526. return !$to_json ? [] : '{}';
  527. }
  528. $subOptions = $em
  529. ->getRepository('ChamiloCoreBundle:ExtraFieldOptions')
  530. ->findSecondaryOptions($option);
  531. $optionsInfo = [];
  532. /** @var ExtraFieldOptions $subOption */
  533. foreach ($subOptions as $subOption) {
  534. $optionsInfo[] = [
  535. 'id' => $subOption->getId(),
  536. 'field_id' => $subOption->getField()->getId(),
  537. 'option_value' => $subOption->getValue(),
  538. 'display_text' => $subOption->getDisplayText(),
  539. 'priority' => $subOption->getPriority(),
  540. 'priority_message' => $subOption->getPriorityMessage(),
  541. 'option_order' => $subOption->getOptionOrder(),
  542. ];
  543. }
  544. if (!$to_json) {
  545. return $optionsInfo;
  546. }
  547. $json = [];
  548. foreach ($optionsInfo as $optionInfo) {
  549. $json[$optionInfo['id']] = $optionInfo['display_text'];
  550. }
  551. return json_encode($json);
  552. }
  553. /**
  554. * Get options for a specific field as string split by ;.
  555. *
  556. * @param int $field_id
  557. * @param string $ordered_by Extra query bit for reordering
  558. *
  559. * @return string HTML string of options
  560. * @assert (0, '') === null
  561. */
  562. public function get_field_options_by_field_to_string($field_id, $ordered_by = null)
  563. {
  564. $field = new ExtraField($this->type);
  565. $field_info = $field->get($field_id);
  566. $options = self::get_field_options_by_field($field_id, false, $ordered_by);
  567. $elements = [];
  568. if (!empty($options)) {
  569. switch ($field_info['field_type']) {
  570. case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
  571. $html = ExtraField::extra_field_double_select_convert_array_to_string($options);
  572. break;
  573. case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
  574. $html = ExtraField::extraFieldSelectWithTextConvertArrayToString($options);
  575. break;
  576. case ExtraField::FIELD_TYPE_TRIPLE_SELECT:
  577. $html = ExtraField::tripleSelectConvertArrayToString($options);
  578. break;
  579. default:
  580. foreach ($options as $option) {
  581. $elements[] = $option['option_value'];
  582. }
  583. $html = implode(';', $elements);
  584. break;
  585. }
  586. return $html;
  587. }
  588. return null;
  589. }
  590. /**
  591. * Get the maximum order value for a specific field.
  592. *
  593. * @param int $field_id
  594. *
  595. * @return int Current max ID + 1 (we start from 0)
  596. * @assert (0, '') === 1
  597. */
  598. public function get_max_order($field_id)
  599. {
  600. $field_id = intval($field_id);
  601. $sql = "SELECT MAX(option_order)
  602. FROM {$this->table}
  603. WHERE field_id = $field_id";
  604. $res = Database::query($sql);
  605. $max = 1;
  606. if (Database::num_rows($res) > 0) {
  607. $row = Database::fetch_array($res);
  608. $max = $row[0] + 1;
  609. }
  610. return $max;
  611. }
  612. /**
  613. * Display a form with the options for the field_id given in REQUEST.
  614. */
  615. public function display()
  616. {
  617. // action links
  618. echo '<div class="actions">';
  619. $field_id = isset($_REQUEST['field_id']) ? intval($_REQUEST['field_id']) : null;
  620. echo '<a href="'.api_get_self().'?action=add&type='.$this->type.'&field_id='.$field_id.'">'.
  621. Display::return_icon('add_user_fields.png', get_lang('Add'), '', ICON_SIZE_MEDIUM).'</a>';
  622. echo '</div>';
  623. echo Display::grid_html('extra_field_options');
  624. }
  625. /**
  626. * @return array
  627. */
  628. public function getPriorityOptions()
  629. {
  630. return [
  631. '' => get_lang('Please select an option'),
  632. 1 => get_lang('Success'),
  633. 2 => get_lang('Information'),
  634. 3 => get_lang('Warning !'),
  635. 4 => get_lang('Error'),
  636. ];
  637. }
  638. /**
  639. * @param $priority
  640. *
  641. * @return string|null
  642. */
  643. public function getPriorityMessageType($priority)
  644. {
  645. switch ($priority) {
  646. case 1:
  647. return 'success';
  648. case 2:
  649. return 'info';
  650. case 3:
  651. return 'warning';
  652. case 4:
  653. return 'error';
  654. }
  655. return null;
  656. }
  657. /**
  658. * Returns an HTML form for the current field.
  659. *
  660. * @param string URL to send the form to (action=...)
  661. * @param string Type of action to offer through the form (edit, usually)
  662. *
  663. * @return FormValidator
  664. */
  665. public function return_form($url, $action)
  666. {
  667. $form_name = $this->type.'_field';
  668. $form = new FormValidator($form_name, 'post', $url);
  669. // Setting the form elements
  670. $header = get_lang('Add');
  671. if ($action == 'edit') {
  672. $header = get_lang('Edit');
  673. }
  674. $form->addElement('header', $header);
  675. $id = isset($_GET['id']) ? intval($_GET['id']) : '';
  676. $form->addElement('hidden', 'id', $id);
  677. $form->addElement('hidden', 'type', $this->type);
  678. $form->addElement('hidden', 'field_id', $this->fieldId);
  679. if ($action == 'edit') {
  680. $translateUrl = api_get_path(WEB_CODE_PATH).'extrafield/translate.php?'.http_build_query([
  681. 'extra_field_option' => $id,
  682. ]);
  683. $translateButton = Display::toolbarButton(
  684. get_lang('Translate this term'),
  685. $translateUrl,
  686. 'language',
  687. 'link'
  688. );
  689. $form->addText(
  690. 'display_text',
  691. [get_lang('Name'), $translateButton]
  692. );
  693. } else {
  694. $form->addElement('text', 'display_text', get_lang('Name'));
  695. }
  696. $form->addElement('text', 'option_value', get_lang('Value'));
  697. $form->addElement('text', 'option_order', get_lang('Order'));
  698. $form->addElement('select', 'priority', get_lang('Priority'), $this->getPriorityOptions());
  699. $form->addElement('textarea', 'priority_message', get_lang('Message type'));
  700. $defaults = [];
  701. if ($action == 'edit') {
  702. // Setting the defaults
  703. $defaults = $this->get($id, false);
  704. $form->freeze('option_value');
  705. $form->addButtonUpdate(get_lang('Edit'));
  706. } else {
  707. $form->addButtonCreate(get_lang('Add'));
  708. }
  709. $form->setDefaults($defaults);
  710. // Setting the rules
  711. $form->addRule('display_text', get_lang('Required field'), 'required');
  712. $form->addRule('option_value', get_lang('Required field'), 'required');
  713. return $form;
  714. }
  715. /**
  716. * @param string $tag
  717. * @param int $field_id
  718. * @param int $limit
  719. *
  720. * @return array
  721. */
  722. public function searchByField($tag, $field_id, $limit = 10)
  723. {
  724. $field_id = intval($field_id);
  725. $limit = intval($limit);
  726. $tag = Database::escape_string($tag);
  727. $sql = "SELECT DISTINCT id, option_display_text
  728. FROM {$this->table}
  729. WHERE
  730. field_id = '".$field_id."' AND
  731. option_value LIKE '%$tag%'
  732. ORDER BY option_value
  733. LIMIT 0, $limit
  734. ";
  735. $result = Database::query($sql);
  736. $values = [];
  737. if (Database::num_rows($result)) {
  738. $values = Database::store_result($result, 'ASSOC');
  739. }
  740. return $values;
  741. }
  742. /**
  743. * @param string $tag
  744. * @param int $field_id
  745. * @param int $limit
  746. *
  747. * @return string
  748. */
  749. public function getSearchOptionsByField($tag, $field_id, $limit = 10)
  750. {
  751. $result = $this->searchByField($tag, $field_id, $limit = 10);
  752. $values = [];
  753. $json = null;
  754. if (!empty($result)) {
  755. foreach ($result as $item) {
  756. $values[] = [
  757. 'value' => $item['id'],
  758. 'caption' => $item['option_display_text'],
  759. ];
  760. }
  761. $json = json_encode($values);
  762. }
  763. return $json;
  764. }
  765. /**
  766. * Gets an element.
  767. *
  768. * @param int $id
  769. * @param bool $translateDisplayText Optional
  770. *
  771. * @return array
  772. */
  773. public function get($id, $translateDisplayText = true)
  774. {
  775. $info = parent::get($id);
  776. if ($translateDisplayText) {
  777. $info['display_text'] = self::translateDisplayName($info['display_text']);
  778. }
  779. return $info;
  780. }
  781. /**
  782. * Translate the display text for a extra field option.
  783. *
  784. * @param string $defaultDisplayText
  785. *
  786. * @return string
  787. */
  788. public static function translateDisplayName($defaultDisplayText)
  789. {
  790. $variableLanguage = self::getLanguageVariable($defaultDisplayText);
  791. return isset($GLOBALS[$variableLanguage]) ? $GLOBALS[$variableLanguage] : $defaultDisplayText;
  792. }
  793. /**
  794. * @param $defaultDisplayText
  795. *
  796. * @return mixed|string
  797. */
  798. public static function getLanguageVariable($defaultDisplayText)
  799. {
  800. $variableLanguage = api_replace_dangerous_char($defaultDisplayText);
  801. $variableLanguage = str_replace('-', '_', $variableLanguage);
  802. $variableLanguage = api_underscore_to_camel_case($variableLanguage);
  803. return $variableLanguage;
  804. }
  805. /**
  806. * @param null $options
  807. *
  808. * @return array
  809. */
  810. public function get_all($options = null)
  811. {
  812. $result = parent::get_all($options);
  813. foreach ($result as &$row) {
  814. $row['display_text'] = self::translateDisplayName($row['display_text']);
  815. }
  816. return $result;
  817. }
  818. /**
  819. * @param string $variable
  820. *
  821. * @return array|\Chamilo\CoreBundle\Entity\ExtraFieldOptions[]
  822. */
  823. public function getOptionsByFieldVariable($variable)
  824. {
  825. $extraFieldType = $this->getExtraField()->getExtraFieldType();
  826. $dql = "SELECT o FROM ChamiloCoreBundle:ExtraFieldOptions o
  827. INNER JOIN ChamiloCoreBundle:ExtraField f WITH o.field = f.id
  828. WHERE f.variable = :variable AND f.extraFieldType = :extra_field_type
  829. ORDER BY o.value ASC";
  830. $result = Database::getManager()
  831. ->createQuery($dql)
  832. ->setParameters(['variable' => $variable, 'extra_field_type' => $extraFieldType])
  833. ->getResult();
  834. return $result;
  835. }
  836. }