Passed
Push — master ( c3ec36...621f87 )
by Julito
07:00
created

ExtraFieldOption::translateDisplayName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\ExtraFieldOptions;
6
7
/**
8
 * Handles the extra fields for various objects (users, sessions, courses).
9
 */
10
class ExtraFieldOption extends Model
11
{
12
    public $columns = [
13
        'id',
14
        'field_id',
15
        'option_value',
16
        'display_text',
17
        'option_order',
18
        'priority',
19
        'priority_message',
20
        'tms',
21
    ];
22
23
    public $extraField;
24
    public $fieldId;
25
26
    /**
27
     * Gets the table for the type of object for which we are using an extra field.
28
     *
29
     * @param string $type Type of object (course, user or session)
30
     */
31
    public function __construct($type)
32
    {
33
        parent::__construct();
34
        $this->type = $type;
35
        $extraField = new ExtraField($this->type);
36
        $this->extraField = $extraField;
37
        $this->table = Database::get_main_table(TABLE_EXTRA_FIELD_OPTIONS);
38
        $this->tableExtraField = Database::get_main_table(TABLE_EXTRA_FIELD);
39
    }
40
41
    /**
42
     * @return ExtraField
43
     */
44
    public function getExtraField()
45
    {
46
        return $this->extraField;
47
    }
48
49
    /**
50
     * Gets the number of options available for this field.
51
     *
52
     * @param int $fieldId
53
     *
54
     * @return int Number of options
55
     * @assert ('') === false
56
     * @assert (-1) == 0
57
     * @assert (0) == 0
58
     */
59
    public function get_count_by_field_id($fieldId)
60
    {
61
        if (empty($fieldId)) {
62
            return false;
63
        }
64
        $extraFieldType = $this->getExtraField()->getExtraFieldType();
65
        $fieldId = (int) $fieldId;
66
67
        $sql = "SELECT count(*) as count
68
                FROM $this->table o
69
                INNER JOIN $this->tableExtraField e
70
                ON o.field_id = e.id
71
                WHERE
72
                    o.field_id = $fieldId AND
73
                    e.extra_field_type = $extraFieldType ";
74
        $result = Database::query($sql);
75
        $result = Database::fetch_array($result);
76
77
        return $result['count'];
78
    }
79
80
    /**
81
     * Returns a list of options for a specific field, separated by ";".
82
     *
83
     * @param int    $field_id
84
     * @param bool   $add_id_in_array Indicates whether we want the results to be given with their id
85
     * @param string $ordered_by      Order by clause (without the "order by") to be added to the SQL query
86
     *
87
     * @return string List of options separated by ;
88
     * @assert (-1, false, null) == ''
89
     */
90
    public function getFieldOptionsToString($field_id, $add_id_in_array = false, $ordered_by = null)
91
    {
92
        $options = self::get_field_options_by_field($field_id, $add_id_in_array, $ordered_by);
0 ignored issues
show
Bug Best Practice introduced by
The method ExtraFieldOption::get_field_options_by_field() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

92
        /** @scrutinizer ignore-call */ 
93
        $options = self::get_field_options_by_field($field_id, $add_id_in_array, $ordered_by);
Loading history...
93
        $new_options = [];
94
        if (!empty($options)) {
95
            foreach ($options as $option) {
96
                $new_options[] = $option['option_value'].':'.$option['display_text'];
97
            }
98
            $string = implode(';', $new_options);
99
100
            return $string;
101
        }
102
103
        return '';
104
    }
105
106
    /**
107
     * Delete all the options of a specific field.
108
     *
109
     * @param int $field_id
110
     *
111
     * @assert (-1) === false
112
     */
113
    public function delete_all_options_by_field_id($field_id)
114
    {
115
        $field_id = (int) $field_id;
116
        $sql = "DELETE FROM {$this->table} WHERE field_id = $field_id";
117
118
        return Database::query($sql);
119
    }
120
121
    /**
122
     * @param array $params
123
     * @param bool  $showQuery
124
     *
125
     * @return int|bool
126
     */
127
    public function saveOptions($params, $showQuery = false)
128
    {
129
        $optionInfo = $this->get_field_option_by_field_and_option(
130
            $params['field_id'],
131
            $params['option_value']
132
        );
133
134
        if (false == $optionInfo) {
135
            $optionValue = api_replace_dangerous_char($params['option_value']);
136
            $order = $this->get_max_order($params['field_id']);
137
            $newParams = [
138
                'field_id' => $params['field_id'],
139
                'value' => trim($optionValue),
140
                'display_text' => trim($params['display_text']),
141
                'option_order' => $order,
142
            ];
143
144
            return parent::save($newParams, $showQuery);
145
        }
146
147
        return false;
148
    }
149
150
    /**
151
     * Saves an option into the corresponding *_field_options table.
152
     *
153
     * @param array $params    Parameters to be considered for the insertion
154
     * @param bool  $showQuery Whether to show the query (sent to the parent save() method)
155
     *
156
     * @return bool True on success, false on error
157
     * @assert (array('field_id'=>0), false) === false
158
     * @assert (array('field_id'=>1), false) === true
159
     */
160
    public function save($params, $showQuery = false)
161
    {
162
        $field_id = (int) $params['field_id'];
163
164
        if (empty($field_id)) {
165
            return false;
166
        }
167
168
        $parseOptions = in_array(
169
            $params['field_type'],
170
            [
171
                ExtraField::FIELD_TYPE_RADIO,
172
                ExtraField::FIELD_TYPE_SELECT,
173
                ExtraField::FIELD_TYPE_SELECT_MULTIPLE,
174
                ExtraField::FIELD_TYPE_DOUBLE_SELECT,
175
                ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD,
176
                ExtraField::FIELD_TYPE_TRIPLE_SELECT,
177
            ]
178
        );
179
180
        if (empty($params['field_options']) || !$parseOptions) {
181
            return true;
182
        }
183
184
        switch ($params['field_type']) {
185
            case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
186
                //$params['field_options'] = France:Paris;Bretagne;Marseilles;Lyon|Belgique:Bruxelles;Namur;Liège;Bruges|Peru:Lima;Piura;
187
            case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
188
                //$params['field_options'] = Option 1|Option 2|Option 3
189
                $options_parsed = ExtraField::extra_field_double_select_convert_string_to_array(
190
                    $params['field_options']
191
                );
192
193
                if (empty($options_parsed)) {
194
                    break;
195
                }
196
197
                foreach ($options_parsed as $key => $option) {
198
                    $new_params = [
199
                        'field_id' => $field_id,
200
                        'option_value' => 0,
201
                        'display_text' => $option['label'],
202
                        'option_order' => 0,
203
                    ];
204
                    // Looking if option already exists:
205
                    $option_info = $this->get_field_option_by_field_id_and_option_display_text(
206
                        $field_id,
207
                        $option['label']
208
                    );
209
210
                    if (empty($option_info)) {
211
                        $sub_id = parent::save($new_params, $showQuery);
212
                    } else {
213
                        $sub_id = $option_info['id'];
214
                        $new_params['id'] = $sub_id;
215
                        parent::update($new_params, $showQuery);
216
                    }
217
218
                    if (ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD == $params['field_type']) {
219
                        continue;
220
                    }
221
222
                    foreach ($option['options'] as $sub_option) {
223
                        if (empty($sub_option)) {
224
                            continue;
225
                        }
226
227
                        $new_params = [
228
                            'field_id' => $field_id,
229
                            'option_value' => $sub_id,
230
                            'display_text' => $sub_option,
231
                            'option_order' => 0,
232
                        ];
233
                        $option_info = $this->getFieldOptionByFieldIdAndOptionDisplayTextAndOptionValue(
234
                            $field_id,
235
                            $sub_option,
236
                            $sub_id
237
                        );
238
239
                        if (empty($option_info)) {
240
                            parent::save($new_params, $showQuery);
241
242
                            continue;
243
                        }
244
245
                        $new_params['id'] = $option_info['id'];
246
                        parent::update($new_params, $showQuery);
247
                    }
248
                }
249
                break;
250
            case ExtraField::FIELD_TYPE_TRIPLE_SELECT:
251
                //Format: Option1\Option11:Option111;Option112\Option12:Option121|Option2\Option21:Option211
252
                $options = ExtraField::tripleSelectConvertStringToArray($params['field_options']);
253
254
                if (!$options) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $options of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
255
                    break;
256
                }
257
258
                foreach ($options as $level1) {
259
                    $level1Params = [
260
                        'field_id' => $field_id,
261
                        'option_value' => 0,
262
                        'display_text' => $level1['label'],
263
                        'option_order' => 0,
264
                    ];
265
                    $optionInfo = $this->get_field_option_by_field_id_and_option_display_text(
266
                        $field_id,
267
                        $level1['label']
268
                    );
269
270
                    if (empty($optionInfo)) {
271
                        $level1Id = parent::save($level1Params);
272
                    } else {
273
                        $level1Id = $optionInfo['id'];
274
                        $level1Params['id'] = $level1Id;
275
                        parent::update($level1Params);
276
                    }
277
278
                    foreach ($level1['options'] as $level2) {
279
                        $level2Params = [
280
                            'field_id' => $field_id,
281
                            'option_value' => $level1Id,
282
                            'display_text' => $level2['label'],
283
                            'display_order' => 0,
284
                        ];
285
                        $optionInfo = $this->getFieldOptionByFieldIdAndOptionDisplayTextAndOptionValue(
286
                            $field_id,
287
                            $level2['label'],
288
                            $level1Id
289
                        );
290
291
                        if (empty($optionInfo)) {
292
                            $level2Id = parent::save($level2Params);
293
                        } else {
294
                            $level2Id = $optionInfo['id'];
295
                            $level2Params['id'] = $level2Id;
296
                            parent::update($level2Params);
297
                        }
298
299
                        foreach ($level2['options'] as $level3) {
300
                            foreach ($level3 as $item) {
301
                                $level3Params = [
302
                                    'field_id' => $field_id,
303
                                    'option_value' => $level2Id,
304
                                    'display_text' => $item,
305
                                    'display_order' => 0,
306
                                ];
307
                                $optionInfo = $this->getFieldOptionByFieldIdAndOptionDisplayTextAndOptionValue(
308
                                    $field_id,
309
                                    $item,
310
                                    $level2Id
311
                                );
312
313
                                if (empty($optionInfo)) {
314
                                    parent::save($level3Params);
315
                                } else {
316
                                    $level3Params['id'] = $optionInfo['id'];
317
                                    parent::update($level3Params);
318
                                }
319
                            }
320
                        }
321
                    }
322
                }
323
                break;
324
            default:
325
                $list = explode(';', $params['field_options']);
326
327
                foreach ($list as $option) {
328
                    $option_info = $this->get_field_option_by_field_and_option($field_id, $option);
329
330
                    // Use URLify only for new items
331
                    $optionValue = api_replace_dangerous_char($option);
332
                    $option = trim($option);
333
334
                    if (false != $option_info) {
335
                        continue;
336
                    }
337
338
                    $order = $this->get_max_order($field_id);
339
340
                    $new_params = [
341
                        'field_id' => $field_id,
342
                        'option_value' => trim($optionValue),
343
                        'display_text' => trim($option),
344
                        'option_order' => $order,
345
                    ];
346
                    parent::save($new_params, $showQuery);
347
                }
348
                break;
349
        }
350
351
        return true;
352
    }
353
354
    /**
355
     * Save one option item at a time.
356
     *
357
     * @param array $params          Parameters specific to the option
358
     * @param bool  $show_query      Whether to show the query (sent to parent save() method)
359
     * @param bool  $insert_repeated Whether to insert even if the option already exists
360
     *
361
     * @return bool True on success, false on failure
362
     * @assert (array('field_id'=>0),false) === false
363
     * @assert (array('field_id'=>0),false) === true
364
     */
365
    public function save_one_item($params, $show_query = false, $insert_repeated = true)
366
    {
367
        $field_id = intval($params['field_id']);
368
        if (empty($field_id)) {
369
            return false;
370
        }
371
372
        if (isset($params['option_value'])) {
373
            $params['option_value'] = trim($params['option_value']);
374
        }
375
376
        if (isset($params['display_text'])) {
377
            $params['display_text'] = trim($params['display_text']);
378
        }
379
380
        if (empty($params['option_order'])) {
381
            $order = $this->get_max_order($field_id);
382
            $params['option_order'] = $order;
383
        }
384
        if ($insert_repeated) {
385
            parent::save($params, $show_query);
386
        } else {
387
            $check = $this->get_field_option_by_field_and_option(
388
                $field_id,
389
                $params['option_value']
390
            );
391
            if (false == $check) {
392
                parent::save($params, $show_query);
393
            }
394
        }
395
396
        return true;
397
    }
398
399
    /**
400
     * Get the complete row of a specific option of a specific field.
401
     *
402
     * @param int    $field_id
403
     * @param string $option_value Value of the option
404
     *
405
     * @return mixed The row on success or false on failure
406
     * @assert (0,'') === false
407
     */
408
    public function get_field_option_by_field_and_option($field_id, $option_value)
409
    {
410
        $field_id = (int) $field_id;
411
        $option_value = Database::escape_string($option_value);
412
        $extraFieldType = $this->getExtraField()->getExtraFieldType();
413
414
        $sql = "SELECT s.* FROM {$this->table} s
415
                INNER JOIN {$this->tableExtraField} sf
416
                ON (s.field_id = sf.id)
417
                WHERE
418
                    field_id = $field_id AND
419
                    option_value = '".$option_value."' AND
420
                    sf.extra_field_type = $extraFieldType
421
                ";
422
        $result = Database::query($sql);
423
        if (Database::num_rows($result) > 0) {
424
            return Database::store_result($result, 'ASSOC');
425
        }
426
427
        return false;
428
    }
429
430
    /**
431
     * Get the complete row of a specific option's display text of a specific field.
432
     *
433
     * @param int    $field_id
434
     * @param string $option_display_text Display value of the option
435
     *
436
     * @return mixed The row on success or false on failure
437
     * @assert (0, '') === false
438
     */
439
    public function get_field_option_by_field_id_and_option_display_text($field_id, $option_display_text)
440
    {
441
        $field_id = (int) $field_id;
442
        $option_display_text = Database::escape_string($option_display_text);
443
        $extraFieldType = $this->getExtraField()->getExtraFieldType();
444
445
        $sql = "SELECT s.* FROM {$this->table} s
446
                INNER JOIN {$this->tableExtraField} sf
447
                ON (s.field_id = sf.id)
448
                WHERE
449
                    field_id = $field_id AND
450
                    s.display_text = '".$option_display_text."' AND
451
                    sf.extra_field_type = $extraFieldType
452
                ";
453
        $result = Database::query($sql);
454
        if (Database::num_rows($result) > 0) {
455
            return Database::fetch_array($result, 'ASSOC');
456
        }
457
458
        return false;
459
    }
460
461
    /**
462
     * Get the complete row of a specific option's display text of a specific field.
463
     *
464
     * @param int    $field_id
465
     * @param string $option_display_text Display value of the option
466
     * @param string $option_value        Value of the option
467
     *
468
     * @return mixed The row on success or false on failure
469
     * @assert (0, '', '') === false
470
     */
471
    public function getFieldOptionByFieldIdAndOptionDisplayTextAndOptionValue(
472
        $field_id,
473
        $option_display_text,
474
        $option_value
475
    ) {
476
        $field_id = (int) $field_id;
477
        $option_display_text = Database::escape_string($option_display_text);
478
        $option_value = Database::escape_string($option_value);
479
        $extraFieldType = $this->getExtraField()->getExtraFieldType();
480
481
        $sql = "SELECT s.* FROM {$this->table} s
482
                INNER JOIN {$this->tableExtraField} sf
483
                ON (s.field_id = sf.id)
484
                WHERE
485
                    field_id = $field_id AND
486
                    sf.display_text = '".$option_display_text."' AND
487
                    option_value = '$option_value' AND
488
                    sf.extra_field_type = ".$extraFieldType."
489
                ";
490
        $result = Database::query($sql);
491
        if (Database::num_rows($result) > 0) {
492
            return Database::fetch_array($result, 'ASSOC');
493
        }
494
495
        return false;
496
    }
497
498
    /**
499
     * Gets an array of options for a specific field.
500
     *
501
     * @param int  $field_id        The field ID
502
     * @param bool $add_id_in_array Whether to add the row ID in the result
503
     * @param null $ordered_by      Extra ordering query bit
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $ordered_by is correct as it would always require null to be passed?
Loading history...
504
     *
505
     * @return array The options if they exists. Otherwise return false
506
     */
507
    public function get_field_options_by_field($field_id, $add_id_in_array = false, $ordered_by = null)
508
    {
509
        $field_id = (int) $field_id;
510
511
        $orderBy = null;
512
        switch ($ordered_by) {
513
            case 'id':
514
                $orderBy = ['id' => 'ASC'];
515
                break;
516
            case 'field_id':
517
                $orderBy = ['field' => 'ASC'];
518
                break;
519
            case 'option_value':
520
                $orderBy = ['optionValue' => 'ASC'];
521
                break;
522
            case 'display_text':
523
                $orderBy = ['displayText' => 'ASC'];
524
                break;
525
            case 'priority':
526
                $orderBy = ['priority' => 'ASC'];
527
                break;
528
            case 'priority_message':
529
                $orderBy = ['priorityMessage' => 'ASC'];
530
                break;
531
            case 'option_order':
532
                $orderBy = ['optionOrder' => 'ASC'];
533
                break;
534
        }
535
536
        $result = Database::getManager()
537
            ->getRepository(ExtraFieldOptions::class)
538
            ->findBy(['field' => $field_id], $orderBy);
539
540
        if (!$result) {
541
            return false;
542
        }
543
544
        $options = [];
545
        /** @var ExtraFieldOptions $row */
546
        foreach ($result as $row) {
547
            $option = [
548
                'id' => $row->getId(),
549
                'field_id' => $row->getField()->getId(),
550
                'option_value' => $row->getValue(),
551
                'display_text' => \ExtraField::translateDisplayName($row->getValue(), $row->getDisplayText()),
552
                'priority' => $row->getPriority(),
553
                'priority_message' => $row->getPriorityMessage(),
554
                'option_order' => $row->getOptionOrder(),
555
            ];
556
557
            if ($add_id_in_array) {
558
                $options[$row->getId()] = $option;
559
                continue;
560
            }
561
            $options[] = $option;
562
        }
563
564
        return $options;
565
    }
566
567
    /**
568
     * Get options for a specific field as array or in JSON format suited for the double-select format.
569
     *
570
     * @param int  $option_value_id Option value ID
571
     * @param bool $to_json         Return format (whether it should be formatted to JSON or not)
572
     *
573
     * @return mixed Row/JSON on success
574
     */
575
    public function get_second_select_field_options_by_field($option_value_id, $to_json = false)
576
    {
577
        $em = Database::getManager();
578
        $option = $em->find(ExtraFieldOptions::class, $option_value_id);
579
580
        if (!$option) {
581
            return !$to_json ? [] : '{}';
582
        }
583
584
        $subOptions = $em->getRepository(ExtraFieldOptions::class)->findSecondaryOptions($option);
585
586
        $optionsInfo = [];
587
        /** @var ExtraFieldOptions $subOption */
588
        foreach ($subOptions as $subOption) {
589
            $optionsInfo[] = [
590
                'id' => $subOption->getId(),
591
                'field_id' => $subOption->getField()->getId(),
592
                'option_value' => $subOption->getValue(),
593
                'display_text' => $subOption->getDisplayText(),
594
                'priority' => $subOption->getPriority(),
595
                'priority_message' => $subOption->getPriorityMessage(),
596
                'option_order' => $subOption->getOptionOrder(),
597
            ];
598
        }
599
600
        if (!$to_json) {
601
            return $optionsInfo;
602
        }
603
604
        $json = [];
605
606
        foreach ($optionsInfo as $optionInfo) {
607
            $json[$optionInfo['id']] = $optionInfo['display_text'];
608
        }
609
610
        return json_encode($json);
611
    }
612
613
    /**
614
     * Get options for a specific field as string split by ;.
615
     *
616
     * @param int    $field_id
617
     * @param string $ordered_by Extra query bit for reordering
618
     *
619
     * @return string HTML string of options
620
     * @assert (0, '') === null
621
     */
622
    public function get_field_options_by_field_to_string($field_id, $ordered_by = null)
623
    {
624
        $field = new ExtraField($this->type);
625
        $field_info = $field->get($field_id);
626
        $options = self::get_field_options_by_field($field_id, false, $ordered_by);
0 ignored issues
show
Bug Best Practice introduced by
The method ExtraFieldOption::get_field_options_by_field() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

626
        /** @scrutinizer ignore-call */ 
627
        $options = self::get_field_options_by_field($field_id, false, $ordered_by);
Loading history...
627
        $elements = [];
628
        if (!empty($options)) {
629
            switch ($field_info['field_type']) {
630
                case ExtraField::FIELD_TYPE_DOUBLE_SELECT:
631
                    $html = ExtraField::extra_field_double_select_convert_array_to_string($options);
632
                    break;
633
                case ExtraField::FIELD_TYPE_SELECT_WITH_TEXT_FIELD:
634
                    $html = ExtraField::extraFieldSelectWithTextConvertArrayToString($options);
635
                    break;
636
                case ExtraField::FIELD_TYPE_TRIPLE_SELECT:
637
                    $html = ExtraField::tripleSelectConvertArrayToString($options);
638
                    break;
639
                default:
640
                    foreach ($options as $option) {
641
                        $elements[] = $option['option_value'];
642
                    }
643
                    $html = implode(';', $elements);
644
                    break;
645
            }
646
647
            return $html;
648
        }
649
650
        return null;
651
    }
652
653
    /**
654
     * Get the maximum order value for a specific field.
655
     *
656
     * @param int $field_id
657
     *
658
     * @return int Current max ID + 1 (we start from 0)
659
     * @assert (0, '') === 1
660
     */
661
    public function get_max_order($field_id)
662
    {
663
        $field_id = (int) $field_id;
664
        $sql = "SELECT MAX(option_order)
665
                FROM {$this->table}
666
                WHERE field_id = $field_id";
667
        $res = Database::query($sql);
668
        $max = 1;
669
        if (Database::num_rows($res) > 0) {
670
            $row = Database::fetch_array($res);
671
            $max = $row[0] + 1;
672
        }
673
674
        return $max;
675
    }
676
677
    /**
678
     * Display a form with the options for the field_id given in REQUEST.
679
     */
680
    public function display()
681
    {
682
        // action links
683
        echo '<div class="actions">';
684
        $field_id = isset($_REQUEST['field_id']) ? intval($_REQUEST['field_id']) : null;
685
        echo '<a href="'.api_get_self().'?action=add&type='.$this->type.'&field_id='.$field_id.'">'.
686
                Display::return_icon('add_user_fields.png', get_lang('Add'), '', ICON_SIZE_MEDIUM).'</a>';
687
        echo '</div>';
688
        echo Display::grid_html('extra_field_options');
689
    }
690
691
    /**
692
     * @return array
693
     */
694
    public function getPriorityOptions()
695
    {
696
        return [
697
            '' => get_lang('Please select an option'),
698
            1 => get_lang('Success'),
699
            2 => get_lang('Information'),
700
            3 => get_lang('Warning !'),
701
            4 => get_lang('Error'),
702
        ];
703
    }
704
705
    /**
706
     * @param $priority
707
     *
708
     * @return string|null
709
     */
710
    public function getPriorityMessageType($priority)
711
    {
712
        switch ($priority) {
713
            case 1:
714
                return 'success';
715
            case 2:
716
                return 'info';
717
            case 3:
718
                return 'warning';
719
            case 4:
720
                return 'error';
721
        }
722
723
        return null;
724
    }
725
726
    /**
727
     * Returns an HTML form for the current field.
728
     *
729
     * @param string URL to send the form to (action=...)
730
     * @param string Type of action to offer through the form (edit, usually)
731
     *
732
     * @return FormValidator
733
     */
734
    public function return_form($url, $action)
735
    {
736
        $form_name = $this->type.'_field';
737
        $form = new FormValidator($form_name, 'post', $url);
738
        // Setting the form elements
739
        $header = get_lang('Add');
740
        if ('edit' == $action) {
741
            $header = get_lang('Edit');
742
        }
743
744
        $form->addElement('header', $header);
745
        $id = isset($_GET['id']) ? (int) $_GET['id'] : '';
746
747
        $form->addElement('hidden', 'id', $id);
748
        $form->addElement('hidden', 'type', $this->type);
749
        $form->addElement('hidden', 'field_id', $this->fieldId);
750
751
        if ('edit' == $action) {
752
            $translateUrl = api_get_path(WEB_CODE_PATH).'extrafield/translate.php?'.http_build_query([
753
                'extra_field_option' => $id,
754
            ]);
755
            $translateButton = Display::toolbarButton(
756
                get_lang('Translate this term'),
757
                $translateUrl,
758
                'language',
759
                'link'
760
            );
761
762
            $form->addText(
763
                'display_text',
764
                [get_lang('Name'), $translateButton]
765
            );
766
        } else {
767
            $form->addElement('text', 'display_text', get_lang('Name'));
768
        }
769
770
        $form->addElement('text', 'option_value', get_lang('Value'));
771
        $form->addElement('text', 'option_order', get_lang('Order'));
772
        $form->addSelect('priority', get_lang('Priority'), $this->getPriorityOptions());
773
        $form->addElement('textarea', 'priority_message', get_lang('Message type'));
774
775
        $defaults = [];
776
777
        if ('edit' == $action) {
778
            // Setting the defaults
779
            $defaults = $this->get($id, false);
780
            $form->freeze('option_value');
781
            $form->addButtonUpdate(get_lang('Edit'));
782
        } else {
783
            $form->addButtonCreate(get_lang('Add'));
784
        }
785
786
        $form->setDefaults($defaults);
787
788
        // Setting the rules
789
        $form->addRule('display_text', get_lang('Required field'), 'required');
790
        $form->addRule('option_value', get_lang('Required field'), 'required');
791
792
        return $form;
793
    }
794
795
    /**
796
     * @param string $tag
797
     * @param int    $field_id
798
     * @param int    $limit
799
     *
800
     * @return array
801
     */
802
    public function searchByField($tag, $field_id, $limit = 10)
803
    {
804
        $field_id = (int) $field_id;
805
        $limit = (int) $limit;
806
        $tag = Database::escape_string($tag);
807
808
        $sql = "SELECT DISTINCT id, option_display_text
809
                FROM {$this->table}
810
                WHERE
811
                    field_id = '".$field_id."' AND
812
                    option_value LIKE '%$tag%'
813
                ORDER BY option_value
814
                LIMIT 0, $limit
815
                ";
816
        $result = Database::query($sql);
817
        $values = [];
818
        if (Database::num_rows($result)) {
819
            $values = Database::store_result($result, 'ASSOC');
820
        }
821
822
        return $values;
823
    }
824
825
    /**
826
     * @param string $tag
827
     * @param int    $field_id
828
     * @param int    $limit
829
     *
830
     * @return string
831
     */
832
    public function getSearchOptionsByField($tag, $field_id, $limit = 10)
833
    {
834
        $result = $this->searchByField($tag, $field_id, $limit = 10);
835
        $values = [];
836
        $json = null;
837
        if (!empty($result)) {
838
            foreach ($result as $item) {
839
                $values[] = [
840
                    'value' => $item['id'],
841
                    'caption' => $item['option_display_text'],
842
                ];
843
            }
844
            $json = json_encode($values);
845
        }
846
847
        return $json;
848
    }
849
850
    /**
851
     * Gets an element.
852
     *
853
     * @param int  $id
854
     * @param bool $translateDisplayText Optional
855
     *
856
     * @return array
857
     */
858
    public function get($id, $translateDisplayText = true)
859
    {
860
        $info = parent::get($id);
861
862
        if ($translateDisplayText) {
863
            $info['display_text'] = ExtraField::translateDisplayName($info['option_value'], $info['display_text']);
864
        }
865
866
        return $info;
867
    }
868
869
    /**
870
     * @param null $options
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $options is correct as it would always require null to be passed?
Loading history...
871
     *
872
     * @return array
873
     */
874
    public function get_all($options = null)
875
    {
876
        $result = parent::get_all($options);
877
878
        foreach ($result as &$row) {
879
            $row['display_text'] = ExtraField::translateDisplayName($row['option_value'], $row['display_text']);
880
        }
881
882
        return $result;
883
    }
884
885
    /**
886
     * @param string $variable
887
     *
888
     * @return array|ExtraFieldOptions[]
889
     */
890
    public function getOptionsByFieldVariable($variable)
891
    {
892
        $extraFieldType = $this->getExtraField()->getExtraFieldType();
893
894
        $dql = "SELECT o FROM ChamiloCoreBundle:ExtraFieldOptions o
895
            INNER JOIN ChamiloCoreBundle:ExtraField f WITH o.field = f.id
896
            WHERE f.variable = :variable AND f.extraFieldType = :extra_field_type
897
            ORDER BY o.value ASC";
898
899
        $result = Database::getManager()
900
            ->createQuery($dql)
901
            ->setParameters(['variable' => $variable, 'extra_field_type' => $extraFieldType])
902
            ->getResult();
903
904
        return $result;
905
    }
906
}
907