Completed
Branch develop (7622d3)
by
unknown
24:52
created

FormCompany::form_prospect_level()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 39
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 25
nc 6
nop 4
dl 0
loc 39
rs 6.7272
c 0
b 0
f 0
1
<?php
2
/* Copyright (C) 2008-2012	Laurent Destailleur	<[email protected]>
3
 * Copyright (C) 2008-2012	Regis Houssin		<[email protected]>
4
 * Copyright (C) 2014		Juanjo Menent		<[email protected]>
5
 *
6
 * This program is free software; you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18
 */
19
20
/**
21
 *	\file       htdocs/core/class/html.formcompany.class.php
22
 *  \ingroup    core
23
 *	\brief      File of class to build HTML component for third parties management
24
 */
25
26
27
/**
28
 *	Class to build HTML component for third parties management
29
 *	Only common components are here.
30
 */
31
class FormCompany
32
{
33
	var $db;
34
	var $error;
35
36
37
38
	/**
39
	 *	Constructor
40
	 *
41
	 *	@param	DoliDB	$db		Database handler
42
	 */
43
	function __construct($db)
44
	{
45
		$this->db = $db;
46
47
		return 1;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
48
	}
49
50
51
	/**
52
	 *    	Return list of labels (translated) of third parties type
53
	 *
54
	 *		@param	int		$mode		0=Return id+label, 1=Return code+label
55
	 *      @param  string	$filter     Add a SQL filter to select
56
	 *    	@return array      			Array of types
57
	 */
58
	function typent_array($mode=0, $filter='')
59
	{
60
		global $langs,$mysoc;
61
62
		$effs = array();
63
64
		$sql = "SELECT id, code, libelle";
65
		$sql.= " FROM ".MAIN_DB_PREFIX."c_typent";
66
		$sql.= " WHERE active = 1 AND (fk_country IS NULL OR fk_country = ".(empty($mysoc->country_id)?'0':$mysoc->country_id).")";
67
		if ($filter) $sql.=" ".$filter;
68
		$sql.= " ORDER by position, id";
69
		dol_syslog(get_class($this).'::typent_array', LOG_DEBUG);
70
		$resql=$this->db->query($sql);
71
		if ($resql)
72
		{
73
			$num = $this->db->num_rows($resql);
74
			$i = 0;
75
76
			while ($i < $num)
77
			{
78
				$objp = $this->db->fetch_object($resql);
79
				if (! $mode) $key=$objp->id;
80
				else $key=$objp->code;
81
				if ($langs->trans($objp->code) != $objp->code) $effs[$key] = $langs->trans($objp->code);
82
				else $effs[$key] = $objp->libelle;
83
				if ($effs[$key]=='-') $effs[$key]='';
84
				$i++;
85
			}
86
			$this->db->free($resql);
87
		}
88
89
		return $effs;
90
	}
91
92
	/**
93
	 *	Renvoie la liste des types d'effectifs possibles (pas de traduction car nombre)
94
	 *
95
	 *	@param	int		$mode		0=renvoi id+libelle, 1=renvoi code+libelle
96
	 *	@param  string	$filter     Add a SQL filter to select
97
	 *  @return array				Array of types d'effectifs
98
	 */
99
	function effectif_array($mode=0, $filter='')
100
	{
101
		$effs = array();
102
103
		$sql = "SELECT id, code, libelle";
104
		$sql .= " FROM ".MAIN_DB_PREFIX."c_effectif";
105
		$sql.= " WHERE active = 1";
106
		if ($filter) $sql.=" ".$filter;
107
		$sql .= " ORDER BY id ASC";
108
		dol_syslog(get_class($this).'::effectif_array', LOG_DEBUG);
109
		$resql=$this->db->query($sql);
110
		if ($resql)
111
		{
112
			$num = $this->db->num_rows($resql);
113
			$i = 0;
114
115
			while ($i < $num)
116
			{
117
				$objp = $this->db->fetch_object($resql);
118
				if (! $mode) $key=$objp->id;
119
				else $key=$objp->code;
120
121
				$effs[$key] = $objp->libelle!='-'?$objp->libelle:'';
122
				$i++;
123
			}
124
			$this->db->free($resql);
125
		}
126
		return $effs;
127
	}
128
129
130
	/**
131
	 *  Affiche formulaire de selection des modes de reglement
132
	 *
133
	 *  @param	int		$page        	Page
134
	 *  @param  int		$selected    	Id or code preselected
135
	 *  @param  string	$htmlname   	Nom du formulaire select
136
	 *	@param	int		$empty			Add empty value in list
137
	 *	@return	void
138
	 */
139
	function form_prospect_level($page, $selected='', $htmlname='prospect_level_id', $empty=0)
140
	{
141
		global $user, $langs;
142
143
		print '<form method="post" action="'.$page.'">';
144
		print '<input type="hidden" name="action" value="setprospectlevel">';
145
		print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
146
147
		dol_syslog(get_class($this).'::form_prospect_level',LOG_DEBUG);
148
		$sql = "SELECT code, label";
149
		$sql.= " FROM ".MAIN_DB_PREFIX."c_prospectlevel";
150
		$sql.= " WHERE active > 0";
151
		$sql.= " ORDER BY sortorder";
152
		$resql = $this->db->query($sql);
153
		if ($resql)
154
		{
155
			$options = array();
156
157
			if ($empty) {
158
				$options[''] = '';
159
			}
160
161
			while ($obj = $this->db->fetch_object($resql)) {
162
				$level = $langs->trans($obj->code);
163
164
				if ($level == $obj->code) {
165
					$level = $langs->trans($obj->label);
166
				}
167
168
				$options[$obj->code] = $level;
169
			}
170
171
			print Form::selectarray($htmlname, $options, $selected);
172
		}
173
		else dol_print_error($this->db);
174
		if (! empty($htmlname) && $user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
175
		print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
176
		print '</form>';
177
	}
178
179
	/**
180
	 *   Retourne la liste deroulante des departements/province/cantons tout pays confondu ou pour un pays donne.
181
	 *   Dans le cas d'une liste tout pays confondus, l'affichage fait une rupture sur le pays.
182
	 *   La cle de la liste est le code (il peut y avoir plusieurs entree pour
183
	 *   un code donnee mais dans ce cas, le champ pays differe).
184
	 *   Ainsi les liens avec les departements se font sur un departement independemment de son nom.
185
	 *
186
	 *   @param     string	$selected        	Code state preselected
187
	 *   @param     int		$country_codeid     0=list for all countries, otherwise country code or country rowid to show
188
	 *   @param     string	$htmlname			Id of department
189
	 *   @return	void
190
	 */
191
	function select_departement($selected='',$country_codeid=0, $htmlname='state_id')
192
	{
193
		print $this->select_state($selected,$country_codeid, $htmlname);
194
	}
195
196
	/**
197
	 *    Retourne la liste deroulante des departements/province/cantons tout pays confondu ou pour un pays donne.
198
	 *    Dans le cas d'une liste tout pays confondus, l'affichage fait une rupture sur le pays.
199
	 *    La cle de la liste est le code (il peut y avoir plusieurs entree pour
200
	 *    un code donnee mais dans ce cas, le champ pays differe).
201
	 *    Ainsi les liens avec les departements se font sur un departement independemment de son nom.
202
	 *
203
	 *    @param	string	$selected        	Code state preselected (mus be state id)
204
	 *    @param    integer	$country_codeid    	Country code or id: 0=list for all countries, otherwise country code or country rowid to show
205
	 *    @param    string	$htmlname			Id of department
206
	 * 	  @return	string						String with HTML select
207
	 *    @see select_country
208
	 */
209
	function select_state($selected='',$country_codeid=0, $htmlname='state_id')
210
	{
211
		global $conf,$langs,$user;
212
213
		dol_syslog(get_class($this)."::select_departement selected=".$selected.", country_codeid=".$country_codeid,LOG_DEBUG);
214
215
		$langs->load("dict");
216
217
		$out='';
218
219
		// On recherche les departements/cantons/province active d'une region et pays actif
220
		$sql = "SELECT d.rowid, d.code_departement as code, d.nom as name, d.active, c.label as country, c.code as country_code FROM";
221
		$sql .= " ".MAIN_DB_PREFIX ."c_departements as d, ".MAIN_DB_PREFIX."c_regions as r,".MAIN_DB_PREFIX."c_country as c";
222
		$sql .= " WHERE d.fk_region=r.code_region and r.fk_pays=c.rowid";
223
		$sql .= " AND d.active = 1 AND r.active = 1 AND c.active = 1";
224
		if ($country_codeid && is_numeric($country_codeid))   $sql .= " AND c.rowid = '".$country_codeid."'";
225
		if ($country_codeid && ! is_numeric($country_codeid)) $sql .= " AND c.code = '".$country_codeid."'";
226
		$sql .= " ORDER BY c.code, d.code_departement";
227
228
		dol_syslog(get_class($this)."::select_departement", LOG_DEBUG);
229
		$result=$this->db->query($sql);
230
		if ($result)
231
		{
232
			if (!empty($htmlname)) $out.= '<select id="'.$htmlname.'" class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'">';
233
			if ($country_codeid) $out.= '<option value="0">&nbsp;</option>';
234
			$num = $this->db->num_rows($result);
235
			$i = 0;
236
			dol_syslog(get_class($this)."::select_departement num=".$num,LOG_DEBUG);
237
			if ($num)
238
			{
239
				$country='';
240
				while ($i < $num)
241
				{
242
					$obj = $this->db->fetch_object($result);
243
					if ($obj->code == '0')		// Le code peut etre une chaine
244
					{
245
						$out.= '<option value="0">&nbsp;</option>';
246
					}
247
					else {
248
						if (! $country || $country != $obj->country)
249
						{
250
							// Affiche la rupture si on est en mode liste multipays
251
							if (! $country_codeid && $obj->country_code)
252
							{
253
								$out.= '<option value="-1" disabled>----- '.$obj->country." -----</option>\n";
254
								$country=$obj->country;
255
							}
256
						}
257
258
						if ((! empty($selected) && $selected == $obj->rowid)
259
						 || (empty($selected) && ! empty($conf->global->MAIN_FORCE_DEFAULT_STATE_ID) && $conf->global->MAIN_FORCE_DEFAULT_STATE_ID == $obj->rowid))
260
						{
261
							$out.= '<option value="'.$obj->rowid.'" selected>';
262
						}
263
						else
264
						{
265
							$out.= '<option value="'.$obj->rowid.'">';
266
						}
267
						// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
268
						$out.= $obj->code . ' - ' . ($langs->trans($obj->code)!=$obj->code?$langs->trans($obj->code):($obj->name!='-'?$obj->name:''));
269
						$out.= '</option>';
270
					}
271
					$i++;
272
				}
273
			}
274
			if (! empty($htmlname)) $out.= '</select>';
275
			if (! empty($htmlname) && $user->admin) $out.= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
276
		}
277
		else
278
		{
279
			dol_print_error($this->db);
280
		}
281
282
        // Make select dynamic
283
        include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
284
        $out .= ajax_combobox($htmlname);
285
286
		return $out;
287
	}
288
289
290
	/**
291
	 *   Retourne la liste deroulante des regions actives dont le pays est actif
292
	 *   La cle de la liste est le code (il peut y avoir plusieurs entree pour
293
	 *   un code donnee mais dans ce cas, le champ pays et lang differe).
294
	 *   Ainsi les liens avec les regions se font sur une region independemment de son name.
295
	 *
296
	 *   @param		string		$selected		Preselected value
297
	 *   @param		string		$htmlname		Name of HTML select field
298
	 *   @return	void
299
	 */
300
	function select_region($selected='',$htmlname='region_id')
301
	{
302
		global $conf,$langs;
303
		$langs->load("dict");
304
305
		$sql = "SELECT r.rowid, r.code_region as code, r.nom as label, r.active, c.code as country_code, c.label as country";
306
		$sql.= " FROM ".MAIN_DB_PREFIX."c_regions as r, ".MAIN_DB_PREFIX."c_country as c";
307
		$sql.= " WHERE r.fk_pays=c.rowid AND r.active = 1 and c.active = 1";
308
		$sql.= " ORDER BY c.code, c.label ASC";
309
310
		dol_syslog(get_class($this)."::select_region", LOG_DEBUG);
311
		$resql=$this->db->query($sql);
312
		if ($resql)
313
		{
314
			print '<select class="flat" name="'.$htmlname.'">';
315
			$num = $this->db->num_rows($resql);
316
			$i = 0;
317
			if ($num)
318
			{
319
				$country='';
320
				while ($i < $num)
321
				{
322
					$obj = $this->db->fetch_object($resql);
323
					if ($obj->code == 0) {
324
						print '<option value="0">&nbsp;</option>';
325
					}
326
					else {
327
						if ($country == '' || $country != $obj->country)
328
						{
329
							// Show break
330
							$key=$langs->trans("Country".strtoupper($obj->country_code));
331
							$valuetoshow=($key != "Country".strtoupper($obj->country_code))?$obj->country_code." - ".$key:$obj->country;
332
							print '<option value="-1" disabled>----- '.$valuetoshow." -----</option>\n";
333
							$country=$obj->country;
334
						}
335
336
						if ($selected > 0 && $selected == $obj->code)
337
						{
338
							print '<option value="'.$obj->code.'" selected>'.$obj->label.'</option>';
339
						}
340
						else
341
						{
342
							print '<option value="'.$obj->code.'">'.$obj->label.'</option>';
343
						}
344
					}
345
					$i++;
346
				}
347
			}
348
			print '</select>';
349
		}
350
		else
351
		{
352
			dol_print_error($this->db);
353
		}
354
	}
355
356
	/**
357
	 *  Return combo list with people title
358
	 *
359
	 *  @param  string	$selected   	Title preselected
360
	 * 	@param	string	$htmlname		Name of HTML select combo field
361
	 *  @param  string  $morecss        Add more css on SELECT element      
362
	 *  @return	string					String with HTML select
363
	 */
364
	function select_civility($selected='',$htmlname='civility_id',$morecss='maxwidth100')
365
	{
366
		global $conf,$langs,$user;
367
		$langs->load("dict");
368
369
		$out='';
370
371
		$sql = "SELECT rowid, code, label, active FROM ".MAIN_DB_PREFIX."c_civility";
372
		$sql.= " WHERE active = 1";
373
374
		dol_syslog("Form::select_civility", LOG_DEBUG);
375
		$resql=$this->db->query($sql);
376
		if ($resql)
377
		{
378
			$out.= '<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
379
			$out.= '<option value="">&nbsp;</option>';
380
			$num = $this->db->num_rows($resql);
381
			$i = 0;
382
			if ($num)
383
			{
384
				while ($i < $num)
385
				{
386
					$obj = $this->db->fetch_object($resql);
387
					if ($selected == $obj->code)
388
					{
389
						$out.= '<option value="'.$obj->code.'" selected>';
390
					}
391
					else
392
					{
393
						$out.= '<option value="'.$obj->code.'">';
394
					}
395
					// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
396
					$out.= ($langs->trans("Civility".$obj->code)!="Civility".$obj->code ? $langs->trans("Civility".$obj->code) : ($obj->label!='-'?$obj->label:''));
397
					$out.= '</option>';
398
					$i++;
399
				}
400
			}
401
			$out.= '</select>';
402
			if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
403
		}
404
		else
405
		{
406
			dol_print_error($this->db);
407
		}
408
409
		return $out;
410
	}
411
412
	/**
413
	 *    Retourne la liste deroulante des formes juridiques tous pays confondus ou pour un pays donne.
414
	 *    Dans le cas d'une liste tous pays confondu, on affiche une rupture sur le pays.
415
	 *
416
	 *    @param	string		$selected        	Code forme juridique a pre-selectionne
417
	 *    @param    mixed		$country_codeid		0=liste tous pays confondus, sinon code du pays a afficher
418
	 *    @param    string		$filter          	Add a SQL filter on list
419
	 *    @return	void
420
	 *    @deprecated Use print xxx->select_juridicalstatus instead
421
	 *    @see select_juridicalstatus()
422
	 */
423
	function select_forme_juridique($selected='', $country_codeid=0, $filter='')
424
	{
425
		print $this->select_juridicalstatus($selected, $country_codeid, $filter);
426
	}
427
428
	/**
429
	 *    Retourne la liste deroulante des formes juridiques tous pays confondus ou pour un pays donne.
430
	 *    Dans le cas d'une liste tous pays confondu, on affiche une rupture sur le pays
431
	 *
432
	 *    @param	string		$selected        	Preselected code of juridical type
433
	 *    @param    int			$country_codeid     0=list for all countries, otherwise list only country requested
434
     *    @param    string		$filter          	Add a SQL filter on list
435
     *    @param	string		$htmlname			HTML name of select
436
     *    @return	string							String with HTML select
437
	 */
438
	function select_juridicalstatus($selected='', $country_codeid=0, $filter='', $htmlname='forme_juridique_code')
439
	{
440
		global $conf,$langs,$user;
441
		$langs->load("dict");
442
443
		$out='';
444
445
		// On recherche les formes juridiques actives des pays actifs
446
		$sql  = "SELECT f.rowid, f.code as code , f.libelle as label, f.active, c.label as country, c.code as country_code";
447
		$sql .= " FROM ".MAIN_DB_PREFIX."c_forme_juridique as f, ".MAIN_DB_PREFIX."c_country as c";
448
		$sql .= " WHERE f.fk_pays=c.rowid";
449
		$sql .= " AND f.active = 1 AND c.active = 1";
450
		if ($country_codeid) $sql .= " AND c.code = '".$country_codeid."'";
451
		if ($filter) $sql .= " ".$filter;
452
		$sql .= " ORDER BY c.code";
453
454
		dol_syslog(get_class($this)."::select_juridicalstatus", LOG_DEBUG);
455
		$resql=$this->db->query($sql);
456
		if ($resql)
457
		{
458
			$out.= '<div id="particulier2" class="visible">';
459
			$out.= '<select class="flat minwidth200" name="'.$htmlname.'" id="'.$htmlname.'">';
460
			if ($country_codeid) $out.= '<option value="0">&nbsp;</option>';	// When country_codeid is set, we force to add an empty line because it does not appears from select. When not set, we already get the empty line from select.
461
462
			$num = $this->db->num_rows($resql);
463
			if ($num)
464
			{
465
				$i = 0;
466
				$country=''; $arraydata=array();
467
				while ($i < $num)
468
				{
469
					$obj = $this->db->fetch_object($resql);
470
471
					if ($obj->code)		// We exclude empty line, we will add it later
472
					{
473
						$labelcountry=(($langs->trans("Country".$obj->country_code)!="Country".$obj->country_code) ? $langs->trans("Country".$obj->country_code) : $obj->country);
474
						$labeljs=(($langs->trans("JuridicalStatus".$obj->code)!="JuridicalStatus".$obj->code) ? $langs->trans("JuridicalStatus".$obj->code) : ($obj->label!='-'?$obj->label:''));	// $obj->label is already in output charset (converted by database driver)
475
						$arraydata[$obj->code]=array('code'=>$obj->code, 'label'=>$labeljs, 'label_sort'=>$labelcountry.'_'.$labeljs, 'country_code'=>$obj->country_code, 'country'=>$labelcountry);
476
					}
477
					$i++;
478
				}
479
480
				$arraydata=dol_sort_array($arraydata, 'label_sort', 'ASC');
481
				if (empty($country_codeid))	// Introduce empty value (if $country_codeid not empty, empty value was already added)
482
				{
483
					$arraydata[0]=array('code'=>0, 'label'=>'', 'label_sort'=>'_', 'country_code'=>'', 'country'=>'');
484
				}
485
486
				foreach($arraydata as $key => $val)
487
				{
488
					if (! $country || $country != $val['country'])
489
					{
490
						// Show break when we are in multi country mode
491
						if (empty($country_codeid) && $val['country_code'])
492
						{
493
							$out.= '<option value="0" disabled class="selectoptiondisabledwhite">----- '.$val['country']." -----</option>\n";
494
							$country=$val['country'];
495
						}
496
					}
497
498
					if ($selected > 0 && $selected == $val['code'])
499
					{
500
						$out.= '<option value="'.$val['code'].'" selected>';
501
					}
502
					else
503
					{
504
						$out.= '<option value="'.$val['code'].'">';
505
					}
506
					// If translation exists, we use it, otherwise we use default label in database
507
					$out.= $val['label'];
508
					$out.= '</option>';
509
				}
510
			}
511
			$out.= '</select>';
512
			if ($user->admin) $out.= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
513
514
		    // Make select dynamic
515
        	include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
516
	        $out .= ajax_combobox($htmlname);
517
518
			$out.= '</div>';
519
		}
520
		else
521
		{
522
			dol_print_error($this->db);
523
		}
524
525
		return $out;
526
	}
527
528
529
	/**
530
	 *  Output list of third parties.
531
	 *
532
	 *  @param  object		$object         Object we try to find contacts
533
	 *  @param  string		$var_id         Name of id field
534
	 *  @param  string		$selected       Pre-selected third party
535
	 *  @param  string		$htmlname       Name of HTML form
536
	 * 	@param	array		$limitto		Disable answers that are not id in this array list
537
	 *  @param	int			$forceid		This is to force another object id than object->id
538
     *  @param	string		$moreparam		String with more param to add into url when noajax search is used.
539
	 * 	@return int 						The selected third party ID
540
	 */
541
	function selectCompaniesForNewContact($object, $var_id, $selected='', $htmlname='newcompany', $limitto='', $forceid=0, $moreparam='')
542
	{
543
		global $conf, $langs;
544
545
		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
546
		{
547
			// Use Ajax search
548
			$minLength = (is_numeric($conf->global->COMPANY_USE_SEARCH_TO_SELECT)?$conf->global->COMPANY_USE_SEARCH_TO_SELECT:2);
549
550
			$socid=0; $name='';
551
			if ($selected > 0)
552
			{
553
				$tmpthirdparty=new Societe($this->db);
554
				$result = $tmpthirdparty->fetch($selected);
555
				if ($result > 0)
556
				{
557
					$socid = $selected;
558
					$name = $tmpthirdparty->name;
559
				}
560
			}
561
562
563
			$events=array();
564
			// Add an entry 'method' to say 'yes, we must execute url with param action = method';
565
			// Add an entry 'url' to say which url to execute
566
			// Add an entry htmlname to say which element we must change once url is called 
567
			// Add entry params => array('cssid' => 'attr') to say to remov or add attribute attr if answer of url return  0 or >0 lines 
568
			// To refresh contacts list on thirdparty list change
569
			$events[]=array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php',1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled'));
570
			
571
			if (count($events))	// If there is some ajax events to run once selection is done, we add code here to run events
572
			{
573
				print '<script type="text/javascript">
574
				jQuery(document).ready(function() {
575
					$("#search_'.$htmlname.'").change(function() {
576
					    console.log("Call runJsCodeForEvent'.$htmlname.'");
577
						var obj = '.json_encode($events).';
578
						$.each(obj, function(key,values) {
579
							if (values.method.length) {
580
								runJsCodeForEvent'.$htmlname.'(values);
581
							}
582
						});
583
						/* Clean contact */
584
						$("div#s2id_contactid>a>span").html(\'\');
585
					});
586
								    
587
					// Function used to execute events when search_htmlname change
588
					function runJsCodeForEvent'.$htmlname.'(obj) {
589
						var id = $("#'.$htmlname.'").val();
590
						var method = obj.method;
591
						var url = obj.url;
592
						var htmlname = obj.htmlname;
593
						$.getJSON(url,
594
							{
595
								action: method,
596
								id: id,
597
								htmlname: htmlname
598
							},
599
							function(response) {
600
								if (response != null)
601
								{
602
									$.each(obj.params, function(key,action) {
603
										if (key.length) {
604
											var num = response.num;
605
											if (num > 0) {
606
												$("#" + key).removeAttr(action);
607
											} else {
608
												$("#" + key).attr(action, action);
609
											}
610
										}
611
									});
612
						            /* console.log("Change select#"+htmlname+" with content "+response.value) */
613
									$("select#" + htmlname).html(response.value);
614
								}
615
							}
616
						);
617
					};
618
				});
619
				</script>';
620
			}
621
622
			print "\n".'<!-- Input text for third party with Ajax.Autocompleter (selectCompaniesForNewContact) -->'."\n";
623
			print '<input type="text" size="30" id="search_'.$htmlname.'" name="search_'.$htmlname.'" value="'.$name.'" />';
624
			print ajax_autocompleter(($socid?$socid:-1), $htmlname, DOL_URL_ROOT.'/societe/ajaxcompanies.php', '', $minLength, 0);
625
			return $socid;
626
		}
627
		else
628
		{
629
			// Search to list thirdparties
630
			$sql = "SELECT s.rowid, s.nom as name FROM";
631
			$sql.= " ".MAIN_DB_PREFIX."societe as s";
632
			$sql.= " WHERE s.entity IN (".getEntity('societe', 1).")";
633
			// For ajax search we limit here. For combo list, we limit later
634
			if (is_array($limitto) && count($limitto))
635
			{
636
				$sql.= " AND s.rowid IN (".join(',',$limitto).")";
637
			}
638
			$sql.= " ORDER BY s.nom ASC";
639
640
			$resql = $this->db->query($sql);
641
			if ($resql)
642
			{
643
				print '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'"';
644
				if ($conf->use_javascript_ajax)
645
				{
646
					$javaScript = "window.location='".$_SERVER['PHP_SELF']."?".$var_id."=".($forceid>0?$forceid:$object->id).$moreparam."&".$htmlname."=' + form.".$htmlname.".options[form.".$htmlname.".selectedIndex].value;";
647
					print ' onChange="'.$javaScript.'"';
648
				}
649
				print '>';
650
				$num = $this->db->num_rows($resql);
651
				$i = 0;
652
				if ($num)
653
				{
654
					while ($i < $num)
655
					{
656
						$obj = $this->db->fetch_object($resql);
657
						if ($i == 0) $firstCompany = $obj->rowid;
658
						$disabled=0;
659
						if (is_array($limitto) && count($limitto) && ! in_array($obj->rowid,$limitto)) $disabled=1;
660
						if ($selected > 0 && $selected == $obj->rowid)
661
						{
662
							print '<option value="'.$obj->rowid.'"';
663
							if ($disabled) print ' disabled';
664
							print ' selected>'.dol_trunc($obj->name,24).'</option>';
665
							$firstCompany = $obj->rowid;
666
						}
667
						else
668
						{
669
							print '<option value="'.$obj->rowid.'"';
670
							if ($disabled) print ' disabled';
671
							print '>'.dol_trunc($obj->name,24).'</option>';
672
						}
673
						$i ++;
674
					}
675
				}
676
				print "</select>\n";
677
				return $firstCompany;
0 ignored issues
show
Bug introduced by
The variable $firstCompany does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
678
			}
679
			else
680
			{
681
				dol_print_error($this->db);
682
				print 'Error sql';
683
			}
684
		}
685
	}
686
687
    /**
688
     *  Return a select list with types of contacts
689
     *
690
     *  @param	object		$object         Object to use to find type of contact
691
     *  @param  string		$selected       Default selected value
692
     *  @param  string		$htmlname		HTML select name
693
     *  @param  string		$source			Source ('internal' or 'external')
694
     *  @param  string		$sortorder		Sort criteria ('position', 'code', ...)
695
     *  @param  int			$showempty      1=Add en empty line
696
     *  @return	void
697
     */
698
	function selectTypeContact($object, $selected, $htmlname = 'type', $source='internal', $sortorder='position', $showempty=0)
699
	{
700
	    global $user, $langs;
701
	    
702
		if (is_object($object) && method_exists($object, 'liste_type_contact'))
703
		{
704
			$lesTypes = $object->liste_type_contact($source, $sortorder, 0, 1);
705
			print '<select class="flat valignmiddle" name="'.$htmlname.'" id="'.$htmlname.'">';
706
			if ($showempty) print '<option value="0"></option>';
707
			foreach($lesTypes as $key=>$value)
708
			{
709
				print '<option value="'.$key.'"';
710
				if ($key == $selected) print ' selected';
711
				print '>'.$value.'</option>';
712
			}
713
			print "</select>";
714
			if ($user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
715
			print "\n";
716
		}
717
	}
718
719
	/**
720
	 *    Return a select list with zip codes and their town
721
	 *
722
	 *    @param	string		$selected				Preselected value
723
	 *    @param    string		$htmlname				HTML select name
724
	 *    @param    string		$fields					Fields
725
	 *    @param    int			$fieldsize				Field size
726
	 *    @param    int			$disableautocomplete    1 To disable ajax autocomplete features (browser autocomplete may still occurs)
727
	 *    @param	string		$moreattrib				Add more attribute on HTML input field
728
	 *    @param    string      $morecss                More css
729
	 *    @return	string
730
	 */
731
	function select_ziptown($selected='', $htmlname='zipcode', $fields='', $fieldsize=0, $disableautocomplete=0, $moreattrib='',$morecss='')
732
	{
733
		global $conf;
734
735
		$out='';
736
737
		$size='';
738
		if (!empty($fieldsize)) $size='size="'.$fieldsize.'"';
739
740
		if ($conf->use_javascript_ajax && empty($disableautocomplete))
741
		{
742
			$out.= ajax_multiautocompleter($htmlname,$fields,DOL_URL_ROOT.'/core/ajax/ziptown.php')."\n";
743
			$moreattrib.=' autocomplete="off"';
744
		}
745
		$out.= '<input id="'.$htmlname.'" class="maxwidthonsmartphone'.($morecss?' '.$morecss:'').'" type="text"'.($moreattrib?' '.$moreattrib:'').' name="'.$htmlname.'" '.$size.' value="'.$selected.'">'."\n";
746
747
		return $out;
748
	}
749
750
    /**
751
     *  Return HTML string to use as input of professional id into a HTML page (siren, siret, etc...)
752
     *
753
     *  @param	int		$idprof         1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm)
754
     *  @param  string	$htmlname       Name of HTML select
755
     *  @param  string	$preselected    Default value to show
756
     *  @param  string	$country_code   FR, IT, ...
757
     *  @param  string  $morecss        More css
758
     *  @return	string					HTML string with prof id
759
     */
760
    function get_input_id_prof($idprof,$htmlname,$preselected,$country_code,$morecss='maxwidth100onsmartphone quatrevingtpercent')
761
    {
762
        global $conf,$langs;
763
764
        $formlength=0;
765
        if (empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
766
        	if ($country_code == 'FR')
767
        	{
768
        		if (isset($idprof)) {
769
        			if ($idprof==1) $formlength=9;
770
        			else if ($idprof==2) $formlength=14;
771
        			else if ($idprof==3) $formlength=5;      // 4 chiffres et 1 lettre depuis janvier
772
        			else if ($idprof==4) $formlength=32;     // No maximum as we need to include a town name in this id
773
        		}
774
        	}
775
        	else if ($country_code == 'ES')
776
        	{
777
        		if ($idprof==1) $formlength=9;  //CIF/NIF/NIE 9 digits
778
        		if ($idprof==2) $formlength=12; //NASS 12 digits without /
779
        		if ($idprof==3) $formlength=5;  //CNAE 5 digits
780
        		if ($idprof==4) $formlength=32; //depend of college
781
        	}
782
        }
783
784
        $selected=$preselected;
785
        if (! $selected && isset($idprof)) {
786
        	if ($idprof==1 && ! empty($this->idprof1)) $selected=$this->idprof1;
787
        	else if ($idprof==2 && ! empty($this->idprof2)) $selected=$this->idprof2;
788
        	else if ($idprof==3 && ! empty($this->idprof3)) $selected=$this->idprof3;
789
        	else if ($idprof==4 && ! empty($this->idprof4)) $selected=$this->idprof4;
790
        }
791
792
        $maxlength=$formlength;
793
        if (empty($formlength)) { $formlength=24; $maxlength=128; }
794
        
795
        $out = '<input type="text" '.($morecss?'class="'.$morecss.'" ':'').'name="'.$htmlname.'" id="'.$htmlname.'" maxlength="'.$maxlength.'" value="'.$selected.'">';
796
797
        return $out;
798
    }
799
800
    /**
801
     * Return a HTML select with localtax values for thirdparties
802
     *
803
     * @param 	int 		$local			LocalTax
804
     * @param 	int 		$selected		Preselected value
805
     * @param 	string      $htmlname		HTML select name
806
     * @return	void
807
     */
808
    function select_localtax($local, $selected, $htmlname)
809
    {
810
    	$tax=get_localtax_by_third($local);
811
812
    	$num = $this->db->num_rows($tax);
813
    	$i = 0;
814
    	if ($num)
815
    	{
816
    		$valors=explode(":", $tax);
817
818
    		if (count($valors) > 1)
819
    		{
820
    			//montar select
821
    			print '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
822
    			while ($i <= (count($valors))-1)
823
    			{
824
    				if ($selected == $valors[$i])
825
    				{
826
    					print '<option value="'.$valors[$i].'" selected>';
827
    				}
828
    				else
829
    				{
830
    					print '<option value="'.$valors[$i].'">';
831
    				}
832
    				print $valors[$i];
833
    				print '</option>';
834
    				$i++;
835
    			}
836
    			print'</select>';
837
    		}
838
    	}
839
    }
840
841
}
842
843