Completed
Branch develop (caae7e)
by
unknown
25:30
created

journals_list.php ➔ fieldList()   F

Complexity

Conditions 17
Paths 520

Size

Total Lines 34
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
eloc 30
nc 520
nop 4
dl 0
loc 34
rs 2.9062
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2017		Alexandre Spangaro   <[email protected]>
3
 *
4
 * This program is free software; you can redistribute it and/or modify
5
 * it under the terms of the GNU General Public License as published by
6
 * the Free Software Foundation; either version 3 of the License, or
7
 * (at your option) any later version.
8
 *
9
 * This program is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16
 *
17
 */
18
19
/**
20
 * \file		htdocs/accountancy/admin/journals_list.php
21
 * \ingroup		Advanced accountancy
22
 * \brief		Setup page to configure journals
23
 */
24
require '../../main.inc.php';
25
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
26
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
27
require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
28
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
29
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
30
require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
31
require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
32
33
$langs->load("admin");
34
$langs->load("compta");
35
$langs->load("accountancy");
36
37
$action=GETPOST('action','alpha')?GETPOST('action','alpha'):'view';
38
$confirm=GETPOST('confirm','alpha');
39
$id=GETPOST('id','int');
40
$rowid=GETPOST('rowid','alpha');
41
42
// Security access
43
if (! empty($user->rights->accountancy->chartofaccount))
44
{
45
	accessforbidden();
46
}
47
48
$acts[0] = "activate";
49
$acts[1] = "disable";
50
$actl[0] = img_picto($langs->trans("Disabled"),'switch_off');
51
$actl[1] = img_picto($langs->trans("Activated"),'switch_on');
52
53
$listoffset=GETPOST('listoffset');
54
$listlimit=GETPOST('listlimit')>0?GETPOST('listlimit'):1000;
55
$active = 1;
56
57
$sortfield = GETPOST("sortfield",'alpha');
58
$sortorder = GETPOST("sortorder",'alpha');
59
$page = GETPOST("page",'int');
60
if ($page == -1) { $page = 0 ; }
61
$offset = $listlimit * $page ;
62
$pageprev = $page - 1;
63
$pagenext = $page + 1;
64
if (empty($sortfield)) $sortfield='code';
65
if (empty($sortorder)) $sortorder='ASC';
66
67
$error = 0;
68
69
// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
70
$hookmanager->initHooks(array('admin'));
71
72
// This page is a generic page to edit dictionaries
73
// Put here declaration of dictionaries properties
74
75
// Sort order to show dictionary (0 is space). All other dictionaries (added by modules) will be at end of this.
76
$taborder=array(35);
77
78
// Name of SQL tables of dictionaries
79
$tabname=array();
80
$tabname[35]= MAIN_DB_PREFIX."accounting_journal";
81
82
// Dictionary labels
83
$tablib=array();
84
$tablib[35]= "DictionaryAccountancyJournal";
85
86
// Requests to extract data
87
$tabsql=array();
88
$tabsql[35]= "SELECT a.rowid as rowid, a.code as code, a.label, a.nature, a.active FROM ".MAIN_DB_PREFIX."accounting_journal as a";
89
90
// Criteria to sort dictionaries
91
$tabsqlsort=array();
92
$tabsqlsort[35]="code ASC";
93
94
// Nom des champs en resultat de select pour affichage du dictionnaire
95
$tabfield=array();
96
$tabfield[35]= "code,label,nature";
97
98
// Nom des champs d'edition pour modification d'un enregistrement
99
$tabfieldvalue=array();
100
$tabfieldvalue[35]= "code,label,nature";
101
102
// Nom des champs dans la table pour insertion d'un enregistrement
103
$tabfieldinsert=array();
104
$tabfieldinsert[35]= "code,label,nature";
105
106
// Nom du rowid si le champ n'est pas de type autoincrement
107
// Example: "" if id field is "rowid" and has autoincrement on
108
//          "nameoffield" if id field is not "rowid" or has not autoincrement on
109
$tabrowid=array();
110
$tabrowid[35]= "";
111
112
// Condition to show dictionary in setup page
113
$tabcond=array();
114
$tabcond[35]= ! empty($conf->accounting->enabled);
115
116
// List of help for fields
117
$tabhelp=array();
118
$tabhelp[35] = array('code'=>$langs->trans("EnterAnyCode"));
119
120
// List of check for fields (NOT USED YET)
121
$tabfieldcheck=array();
122
$tabfieldcheck[35] = array();
123
124
// Complete all arrays with entries found into modules
125
complete_dictionary_with_modules($taborder,$tabname,$tablib,$tabsql,$tabsqlsort,$tabfield,$tabfieldvalue,$tabfieldinsert,$tabrowid,$tabcond,$tabhelp,$tabfieldcheck);
126
127
128
// Define elementList and sourceList (used for dictionary type of contacts "llx_c_type_contact")
129
$elementList = array();
130
    // Must match ids defined into eldy.lib.php 
131
    $sourceList = array(
132
			'1' => $langs->trans('AccountingJournalType1'),
133
			'2' => $langs->trans('AccountingJournalType2'),
134
			'3' => $langs->trans('AccountingJournalType3'),
135
			'4' => $langs->trans('AccountingJournalType4'),
136
			'9' => $langs->trans('AccountingJournalType9')
137
	);
138
139
/*
140
 * Actions
141
 */
142
143
if (GETPOST('button_removefilter') || GETPOST('button_removefilter.x') || GETPOST('button_removefilter_x'))
144
{
145
    $search_country_id = '';    
146
}
147
148
// Actions add or modify an entry into a dictionary
149
if (GETPOST('actionadd') || GETPOST('actionmodify'))
150
{
151
    $listfield=explode(',', str_replace(' ', '',$tabfield[$id]));
152
    $listfieldinsert=explode(',',$tabfieldinsert[$id]);
153
    $listfieldmodify=explode(',',$tabfieldinsert[$id]);
154
    $listfieldvalue=explode(',',$tabfieldvalue[$id]);
155
156
    // Check that all fields are filled
157
    $ok=1;
158
    foreach ($listfield as $f => $value)
159
    {
160
		if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label'))  $fieldnamekey='Label';
161
        if ($fieldnamekey == 'code') $fieldnamekey = 'Code';
162
		if ($fieldnamekey == 'nature') $fieldnamekey = 'Nature';
163
    }
164
    // Other checks
165
    if (isset($_POST["code"]))
166
    {
167
    	if ($_POST["code"]=='0')
168
    	{
169
        	$ok=0;
170
    		setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors');
171
        }
172
        /*if (!is_numeric($_POST['code']))	// disabled, code may not be in numeric base
173
    	{
174
	    	$ok = 0;
175
	    	$msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'<br />';
176
	    }*/
177
    }
178
179
	// Clean some parameters
180
    if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"]='';	// If empty, we force to null
181
	if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"]='';	// If empty, we force to null
182
	if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"]='';	// If empty, we force to null
183
184
    // Si verif ok et action add, on ajoute la ligne
185
    if ($ok && GETPOST('actionadd'))
186
    {
187
        if ($tabrowid[$id])
188
        {
189
            // Recupere id libre pour insertion
190
            $newid=0;
191
            $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id];
192
            $result = $db->query($sql);
193
            if ($result)
194
            {
195
                $obj = $db->fetch_object($result);
196
                $newid=($obj->newid + 1);
197
198
            } else {
199
                dol_print_error($db);
200
            }
201
        }
202
203
        // Add new entry
204
        $sql = "INSERT INTO ".$tabname[$id]." (";
205
        // List of fields
206
        if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert))
207
        	$sql.= $tabrowid[$id].",";
208
        $sql.= $tabfieldinsert[$id];
209
        $sql.=",active)";
210
        $sql.= " VALUES(";
211
212
        // List of values
213
        if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldinsert))
214
        	$sql.= $newid.",";
215
        $i=0;
216
        foreach ($listfieldinsert as $f => $value)
217
        {
218
            if ($value == 'entity') {
219
            	$_POST[$listfieldvalue[$i]] = $conf->entity;
220
            }
221
            if ($i) $sql.=",";
222
            if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null";  // For vat, we want/accept code = ''
223
            else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'";
224
            $i++;
225
        }
226
        $sql.=",1)";
227
228
        dol_syslog("actionadd", LOG_DEBUG);
229
        $result = $db->query($sql);
230
        if ($result)	// Add is ok
231
        {
232
            setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs');
233
        	$_POST=array('id'=>$id);	// Clean $_POST array, we keep only
234
        }
235
        else
236
        {
237
            if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
238
                setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors');
239
            }
240
            else {
241
                dol_print_error($db);
242
            }
243
        }
244
    }
245
246
    // Si verif ok et action modify, on modifie la ligne
247
    if ($ok && GETPOST('actionmodify'))
248
    {
249
        if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; }
250
        else { $rowidcol="rowid"; }
251
252
        // Modify entry
253
        $sql = "UPDATE ".$tabname[$id]." SET ";
254
        // Modifie valeur des champs
255
        if ($tabrowid[$id] && ! in_array($tabrowid[$id],$listfieldmodify))
256
        {
257
            $sql.= $tabrowid[$id]."=";
258
            $sql.= "'".$db->escape($rowid)."', ";
259
        }
260
        $i = 0;
261
        foreach ($listfieldmodify as $field)
262
        {
263
            if ($field == 'price' || preg_match('/^amount/i',$field) || $field == 'taux') {
264
            	$_POST[$listfieldvalue[$i]] = price2num($_POST[$listfieldvalue[$i]],'MU');
265
            }
266
            else if ($field == 'entity') {
267
            	$_POST[$listfieldvalue[$i]] = $conf->entity;
268
            }
269
            if ($i) $sql.=",";
270
            $sql.= $field."=";
271
            if ($_POST[$listfieldvalue[$i]] == '' && ! ($listfieldvalue[$i] == 'code' && $id == 10)) $sql.="null";  // For vat, we want/accept code = ''
272
            else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'";
273
            $i++;
274
        }
275
        $sql.= " WHERE ".$rowidcol." = '".$rowid."'";
276
277
        dol_syslog("actionmodify", LOG_DEBUG);
278
        //print $sql;
279
        $resql = $db->query($sql);
280
        if (! $resql)
281
        {
282
            setEventMessages($db->error(), null, 'errors');
283
        }
284
    }
285
    //$_GET["id"]=GETPOST('id', 'int');       // Force affichage dictionnaire en cours d'edition
286
}
287
288
if (GETPOST('actioncancel'))
289
{
290
    //$_GET["id"]=GETPOST('id', 'int');       // Force affichage dictionnaire en cours d'edition
291
}
292
293
if ($action == 'confirm_delete' && $confirm == 'yes')       // delete
294
{
295
    if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; }
296
    else { $rowidcol="rowid"; }
297
298
    $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'";
299
300
    dol_syslog("delete", LOG_DEBUG);
301
    $result = $db->query($sql);
302
    if (! $result)
303
    {
304
        if ($db->errno() == 'DB_ERROR_CHILD_EXISTS')
305
        {
306
            setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors');
307
        }
308
        else
309
        {
310
            dol_print_error($db);
311
        }
312
    }
313
}
314
315
// activate
316
if ($action == $acts[0])
317
{
318
    if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; }
319
    else { $rowidcol="rowid"; }
320
321
    if ($rowid) {
322
        $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'";
323
    }
324
    elseif ($_GET["code"]) {
325
        $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".$_GET["code"]."'";
326
    }
327
328
    $result = $db->query($sql);
329
    if (!$result)
330
    {
331
        dol_print_error($db);
332
    }
333
}
334
335
// disable
336
if ($action == $acts[1])
337
{
338
    if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; }
339
    else { $rowidcol="rowid"; }
340
341
    if ($rowid) {
342
        $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'";
343
    }
344
    elseif ($_GET["code"]) {
345
        $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".$_GET["code"]."'";
346
    }
347
348
    $result = $db->query($sql);
349
    if (!$result)
350
    {
351
        dol_print_error($db);
352
    }
353
}
354
355
/*
356
 * View
357
 */
358
359
$form = new Form($db);
360
$formadmin=new FormAdmin($db);
361
362
llxHeader();
363
364
$titre=$langs->trans("DictionarySetup");
365
$linkback='';
366
if ($id)
367
{
368
    $titre.=' - '.$langs->trans($tablib[$id]);
369
    $titlepicto='title_accountancy';
370
}
371
372
print load_fiche_titre($titre,$linkback,$titlepicto);
373
374
if (empty($id))
375
{
376
    print $langs->trans("DictionaryDesc");
377
    print " ".$langs->trans("OnlyActiveElementsAreShown")."<br>\n";
378
}
379
print "<br>\n";
380
381
382
// Confirmation de la suppression de la ligne
383
if ($action == 'delete')
384
{
385
    print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid.'&code='.$_GET["code"].'&id='.$id, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete','',0,1);
386
}
387
//var_dump($elementList);
388
389
/*
390
 * Show a dictionary
391
 */
392
if ($id)
393
{
394
    // Complete requete recherche valeurs avec critere de tri
395
    $sql=$tabsql[$id];
396
397
    if ($search_country_id > 0)
398
    {
399
        if (preg_match('/ WHERE /',$sql)) $sql.= " AND ";
400
        else $sql.=" WHERE ";
401
        $sql.= " c.rowid = ".$search_country_id;
402
    }
403
    
404
    if ($sortfield)
405
    {
406
        // If sort order is "country", we use country_code instead
407
    	if ($sortfield == 'country') $sortfield='country_code';
408
        $sql.= " ORDER BY ".$sortfield;
409
        if ($sortorder)
410
        {
411
            $sql.=" ".strtoupper($sortorder);
412
        }
413
        $sql.=", ";
414
        // Clear the required sort criteria for the tabsqlsort to be able to force it with selected value
415
        $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.' '.$sortorder.',/i','',$tabsqlsort[$id]);
416
        $tabsqlsort[$id]=preg_replace('/([a-z]+\.)?'.$sortfield.',/i','',$tabsqlsort[$id]);
417
    }
418
    else {
419
        $sql.=" ORDER BY ";
420
    }
421
    $sql.=$tabsqlsort[$id];
422
    $sql.=$db->plimit($listlimit+1,$offset);
423
    //print $sql;
424
425
    $fieldlist=explode(',',$tabfield[$id]);
426
427
    print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$id.'" method="POST">';
428
    print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
429
    print '<input type="hidden" name="from" value="'.dol_escape_htmltag(GETPOST('from','alpha')).'">';
430
    
431
    print '<table class="noborder" width="100%">';
432
433
    // Form to add a new line
434
    if ($tabname[$id])
435
    {
436
        $alabelisused=0;
437
        $var=false;
438
439
        $fieldlist=explode(',',$tabfield[$id]);
440
441
        // Line for title
442
        print '<tr class="liste_titre">';
443
        foreach ($fieldlist as $field => $value)
444
        {
445
            // Determine le nom du champ par rapport aux noms possibles
446
            // dans les dictionnaires de donnees
447
            $valuetoshow=ucfirst($fieldlist[$field]);   // Par defaut
448
            $valuetoshow=$langs->trans($valuetoshow);   // try to translate
449
            $align="left";
450
            if ($fieldlist[$field]=='code')            { $valuetoshow=$langs->trans("Code"); }
451
            if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label')
452
            {
453
            	$valuetoshow=$langs->trans("Label");
454
            }
455
            if ($fieldlist[$field]=='nature')          { $valuetoshow=$langs->trans("Nature"); }
456
				
457
            if ($valuetoshow != '')
458
            {
459
                print '<td align="'.$align.'">';
460
            	if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i',$tabhelp[$id][$value])) print '<a href="'.$tabhelp[$id][$value].'" target="_blank">'.$valuetoshow.' '.img_help(1,$valuetoshow).'</a>';
461
            	else if (! empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow,$tabhelp[$id][$value]);
462
            	else print $valuetoshow;
463
                print '</td>';
464
             }
465
             if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1;
466
        }
467
468
        print '<td>';
469
        print '<input type="hidden" name="id" value="'.$id.'">';
470
        print '</td>';
471
        print '<td style="min-width: 26px;"></td>';
472
        print '<td style="min-width: 26px;"></td>';
473
        print '<td style="min-width: 26px;"></td>';
474
        print '</tr>';
475
476
        // Line to enter new values
477
        print '<tr class="oddeven nodrag nodrap nohover">';
478
479
        $obj = new stdClass();
480
        // If data was already input, we define them in obj to populate input fields.
481
        if (GETPOST('actionadd'))
482
        {
483
            foreach ($fieldlist as $key=>$val)
484
            {
485
                if (GETPOST($val) != '')
486
                	$obj->$val=GETPOST($val);
487
            }
488
        }
489
490
        $tmpaction = 'create';
491
        $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
492
        $reshook=$hookmanager->executeHooks('createDictionaryFieldlist',$parameters, $obj, $tmpaction);    // Note that $action and $object may have been modified by some hooks
493
        $error=$hookmanager->error; $errors=$hookmanager->errors;
494
495
        if (empty($reshook))
496
        {
497
       		fieldList($fieldlist,$obj,$tabname[$id],'add');
498
        }
499
500
        print '<td colspan="4" align="right">';
501
       	print '<input type="submit" class="button" name="actionadd" value="'.$langs->trans("Add").'">';
502
        print '</td>';
503
        print "</tr>";
504
505
        print '<tr><td colspan="7">&nbsp;</td></tr>';	// Keep &nbsp; to have a line with enough height
506
    }
507
508
509
510
    // List of available record in database
511
    dol_syslog("htdocs/admin/dict", LOG_DEBUG);
512
    $resql=$db->query($sql);
513
    if ($resql)
514
    {
515
        $num = $db->num_rows($resql);
516
        $i = 0;
517
        $var=true;
518
519
        $param = '&id='.$id;
520
        if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id;
521
        $paramwithsearch = $param;
522
        if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder;
523
        if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield;
524
        if (GETPOST('from')) $paramwithsearch.= '&from='.GETPOST('from','alpha');
525
        
526
        // There is several pages
527
        if ($num > $listlimit)
528
        {
529
            print '<tr class="none"><td align="right" colspan="'.(3+count($fieldlist)).'">';
530
            print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), '<li class="pagination"><span>'.$langs->trans("Page").' '.($page+1).'</span></li>');
531
            print '</td></tr>';
532
        }
533
534
        // Title of lines
535
        print '<tr class="liste_titre liste_titre_add">';
536
        foreach ($fieldlist as $field => $value)
537
        {
538
            // Determine le nom du champ par rapport aux noms possibles
539
            // dans les dictionnaires de donnees
540
            $showfield=1;							  	// By defaut
541
            $align="left";
542
            $sortable=1;
543
            $valuetoshow='';
544
            /*
545
            $tmparray=getLabelOfField($fieldlist[$field]);
546
            $showfield=$tmp['showfield'];
547
            $valuetoshow=$tmp['valuetoshow'];
548
            $align=$tmp['align'];
549
            $sortable=$tmp['sortable'];
550
			*/
551
            $valuetoshow=ucfirst($fieldlist[$field]);   // By defaut
552
            $valuetoshow=$langs->trans($valuetoshow);   // try to translate
553
            if ($fieldlist[$field]=='code')            { $valuetoshow=$langs->trans("Code"); }
554
            if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') { $valuetoshow=$langs->trans("Label"); }
555
            if ($fieldlist[$field]=='nature')          { $valuetoshow=$langs->trans("Nature"); }
556
557
            // Affiche nom du champ
558
            if ($showfield)
559
            {
560
                print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), $param, "align=".$align, $sortfield, $sortorder);
561
            }
562
        }
563
		print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page?'page='.$page.'&':''), $param, 'align="center"', $sortfield, $sortorder);
564
        print getTitleFieldOfList('');
565
        print getTitleFieldOfList('');
566
        print getTitleFieldOfList('');
567
        print '</tr>';
568
569
        // Title line with search boxes
570
        print '<tr class="liste_titre_filter">';
571
        print '<td class="liste_titre"></td>';
572
        print '<td class="liste_titre"></td>';
573
        print '<td class="liste_titre"></td>';
574
        print '<td class="liste_titre"></td>';
575
        print '<td class="liste_titre"></td>';
576
        print '<td class="liste_titre"></td>';
577
        print '<td class="liste_titre" align="center">';
578
    	if ($filterfound)
579
    	{
580
        	$searchpitco=$form->showFilterAndCheckAddButtons(0);
581
        	print $searchpitco;
582
    	}
583
    	print '</td>';
584
    	print '</tr>';
585
            
586
        if ($num)
587
        {
588
            // Lines with values
589
            while ($i < $num)
590
            {
591
                $obj = $db->fetch_object($resql);
592
                //print_r($obj);
593
                print '<tr class="oddeven" id="rowid-'.$obj->rowid.'">';
594
                if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code)))
595
                {
596
                    $tmpaction='edit';
597
                    $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
598
                    $reshook=$hookmanager->executeHooks('editDictionaryFieldlist',$parameters,$obj, $tmpaction);    // Note that $action and $object may have been modified by some hooks
599
                    $error=$hookmanager->error; $errors=$hookmanager->errors;
600
601
                    // Show fields
602
                    if (empty($reshook)) fieldList($fieldlist,$obj,$tabname[$id],'edit');
603
604
                    print '<td align="center" colspan="4">';
605
                    print '<input type="hidden" name="page" value="'.$page.'">';
606
                    print '<input type="hidden" name="rowid" value="'.$rowid.'">';
607
                    print '<input type="submit" class="button" name="actionmodify" value="'.$langs->trans("Modify").'">';
608
                    print '<input type="submit" class="button" name="actioncancel" value="'.$langs->trans("Cancel").'">';
609
                    print '<div name="'.(! empty($obj->rowid)?$obj->rowid:$obj->code).'"></div>';
610
                    print '</td>';
611
                }
612
                else
613
                {
614
	              	$tmpaction = 'view';
615
                    $parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]);
616
                    $reshook=$hookmanager->executeHooks('viewDictionaryFieldlist',$parameters,$obj, $tmpaction);    // Note that $action and $object may have been modified by some hooks
617
618
                    $error=$hookmanager->error; $errors=$hookmanager->errors;
619
620
                    if (empty($reshook))
621
                    {
622
                        foreach ($fieldlist as $field => $value)
623
                        {
624
                            
625
                            $showfield=1;
626
                        	$align="left";
627
                            $valuetoshow=$obj->{$fieldlist[$field]};
628
                            if ($valuetoshow=='all') {
629
                                $valuetoshow=$langs->trans('All');
630
                            }
631
                            else if ($fieldlist[$field]=='nature' && $tabname[$id]==MAIN_DB_PREFIX.'accounting_journal') {
632
                                $langs->load("accountancy");
633
                                $key=$langs->trans("AccountingJournalType".strtoupper($obj->nature));
634
                                $valuetoshow=($obj->nature && $key != "AccountingJournalType".strtoupper($obj->nature)?$key:$obj->{$fieldlist[$field]});
635
                            }
636
637
                            $class='tddict';
638
							// Show value for field
639
							if ($showfield) print '<!-- '.$fieldlist[$field].' --><td align="'.$align.'" class="'.$class.'">'.$valuetoshow.'</td>';
640
                        }
641
                    }
642
643
                    // Can an entry be erased or disabled ?
644
                    $iserasable=1;$canbedisabled=1;$canbemodified=1;	// true by default
645
                    if (isset($obj->code) && $id != 10)
646
                    {
647
                    	if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i',$obj->code))) { $iserasable = 0; $canbedisabled = 0; }
648
                    	else if ($obj->code == 'RECEP') { $iserasable = 0; $canbedisabled = 0; }
649
                    	else if ($obj->code == 'EF0')   { $iserasable = 0; $canbedisabled = 0; }
650
                    }
651
652
                    $canbemodified=$iserasable;
653
654
                    $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):'');
655
                    if ($param) $url .= '&'.$param;
656
                    $url.='&';
657
658
                    // Active
659
                    print '<td align="center" class="nowrap">';
660
                    if ($canbedisabled) print '<a href="'.$url.'action='.$acts[$obj->active].'">'.$actl[$obj->active].'</a>';
661
                    else
662
                 	{
663
                 		if (in_array($obj->code, array('AC_OTH','AC_OTH_AUTO'))) print $langs->trans("AlwaysActive");
664
                 		else if (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated");
665
                  		else if (isset($obj->type) && in_array($obj->type, array('system')) && ! empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption");
666
                    	else print $langs->trans("AlwaysActive");
667
                    }
668
                    print "</td>";
669
670
                    // Modify link
671
                    if ($canbemodified) print '<td align="center"><a class="reposition" href="'.$url.'action=edit">'.img_edit().'</a></td>';
672
                    else print '<td>&nbsp;</td>';
673
674
                    // Delete link
675
                    if ($iserasable)
676
                    {
677
                        print '<td align="center">';
678
                        if ($user->admin) print '<a href="'.$url.'action=delete">'.img_delete().'</a>';
679
                        //else print '<a href="#">'.img_delete().'</a>';    // Some dictionnary can be edited by other profile than admin
680
                        print '</td>';
681
                    }
682
                    else print '<td>&nbsp;</td>';
683
684
                    print '<td></td>';
685
                                         
686
                    print '</td>';
687
                }
688
                
689
                print "</tr>\n";
690
                $i++;
691
            }
692
        }
693
    }
694
    else {
695
        dol_print_error($db);
696
    }
697
698
    print '</table>';
699
700
    print '</form>';
701
}
702
703
print '<br>';
704
705
706
llxFooter();
707
$db->close();
708
709
710
/**
711
 *	Show fields in insert/edit mode
712
 *
713
 * 	@param		array	$fieldlist		Array of fields
714
 * 	@param		Object	$obj			If we show a particular record, obj is filled with record fields
715
 *  @param		string	$tabname		Name of SQL table
716
 *  @param		string	$context		'add'=Output field for the "add form", 'edit'=Output field for the "edit form", 'hide'=Output field for the "add form" but we dont want it to be rendered
717
 *	@return		void
718
 */
719
function fieldList($fieldlist, $obj='', $tabname='', $context='')
720
{
721
	global $conf,$langs,$db;
722
	global $form, $mysoc;
723
	global $region_id;
724
	global $elementList,$sourceList,$localtax_typeList;
725
	global $bc;
726
727
	$formadmin = new FormAdmin($db);
728
	$formcompany = new FormCompany($db);
729
730
	foreach ($fieldlist as $field => $value)
731
	{
732
		if ($fieldlist[$field] == 'nature')
733
		{
734
			print '<td>';
735
			print $form->selectarray('nature', $sourceList,(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''));
736
			print '</td>';
737
		}
738
		elseif ($fieldlist[$field] == 'code' && isset($obj->{$fieldlist[$field]})) {
739
			print '<td><input type="text" class="flat minwidth100" value="'.(! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'').'" name="'.$fieldlist[$field].'"></td>';
740
		}
741
		else
742
		{
743
			print '<td>';
744
			$size=''; $class='';
745
			if ($fieldlist[$field]=='code')  $class='maxwidth100';
746
			if ($fieldlist[$field]=='label') $class='quatrevingtpercent';
747
			if ($fieldlist[$field]=='sortorder' || $fieldlist[$field]=='sens' || $fieldlist[$field]=='category_type') $size='size="2" ';
748
			print '<input type="text" '.$size.'class="flat'.($class?' '.$class:'').'" value="'.(isset($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'').'" name="'.$fieldlist[$field].'">';
749
			print '</td>';
750
		}
751
	}
752
}