PageRenderTime 25ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/fuel/core/classes/fieldset/field.php

https://bitbucket.org/sriedel/iccrm-wip
PHP | 604 lines | 327 code | 79 blank | 198 comment | 30 complexity | 4b3e5e4069e88d853811786a63f89450 MD5 | raw file
Possible License(s): MIT
  1. <?php
  2. /**
  3. * Part of the Fuel framework.
  4. *
  5. * @package Fuel
  6. * @version 1.0
  7. * @author Fuel Development Team
  8. * @license MIT License
  9. * @copyright 2010 - 2012 Fuel Development Team
  10. * @link http://fuelphp.com
  11. */
  12. namespace Fuel\Core;
  13. /**
  14. * Fieldset Class
  15. *
  16. * Define a set of fields that can be used to generate a form or to validate input.
  17. *
  18. * @package Fuel
  19. * @category Core
  20. */
  21. class Fieldset_Field
  22. {
  23. /**
  24. * @var Fieldset Fieldset this field belongs to
  25. */
  26. protected $fieldset;
  27. /**
  28. * @var string Name of this field
  29. */
  30. protected $name = '';
  31. /**
  32. * @var string Field type for form generation, false to prevent it showing
  33. */
  34. protected $type = 'text';
  35. /**
  36. * @var string Field label for validation errors and form label generation
  37. */
  38. protected $label = '';
  39. /**
  40. * @var mixed (Default) value of this field
  41. */
  42. protected $value;
  43. /**
  44. * @var string Description text to show with the field
  45. */
  46. protected $description = '';
  47. /**
  48. * @var array Rules for validation
  49. */
  50. protected $rules = array();
  51. /**
  52. * @var array Attributes for form generation
  53. */
  54. protected $attributes = array();
  55. /**
  56. * @var array Options, only available for select, radio & checkbox types
  57. */
  58. protected $options = array();
  59. /**
  60. * @var string Template for form building
  61. */
  62. protected $template;
  63. /**
  64. * @var array overwrites for default error messages
  65. */
  66. protected $error_messages = array();
  67. /**
  68. * Constructor
  69. *
  70. * @param string
  71. * @param string
  72. * @param array
  73. * @param array
  74. * @param Fieldset
  75. */
  76. public function __construct($name, $label = '', array $attributes = array(), array $rules = array(), $fieldset = null)
  77. {
  78. $this->name = (string) $name;
  79. $this->fieldset = $fieldset instanceof Fieldset ? $fieldset : null;
  80. // Don't allow name in attributes
  81. unset($attributes['name']);
  82. // Take rules out of attributes
  83. unset($attributes['rules']);
  84. // Use specific setter when available
  85. foreach ($attributes as $attr => $val)
  86. {
  87. if (method_exists($this, $method = 'set_'.$attr))
  88. {
  89. $this->{$method}($val);
  90. unset($attributes[$attr]);
  91. }
  92. }
  93. // Add default "type" attribute if not specified
  94. empty($attributes['type']) and $this->set_type($this->type);
  95. // only when non-empty, will supersede what was given in $attributes
  96. $label and $this->set_label($label);
  97. $this->attributes = array_merge($this->attributes, $attributes);
  98. foreach ($rules as $rule)
  99. {
  100. call_user_func_array(array($this, 'add_rule'), (array) $rule);
  101. }
  102. }
  103. /**
  104. * @param Fieldset Fieldset to assign the field to
  105. * @return Fieldset_Field
  106. * @throws \RuntimeException
  107. */
  108. public function set_fieldset(Fieldset $fieldset)
  109. {
  110. if ($this->fieldset)
  111. {
  112. throw new \RuntimeException('Field already belongs to a fieldset, cannot be reassigned.');
  113. }
  114. $this->fieldset = $fieldset;
  115. return $this;
  116. }
  117. /**
  118. * Change the field label
  119. *
  120. * @param string
  121. * @return Fieldset_Field this, to allow chaining
  122. */
  123. public function set_label($label)
  124. {
  125. $this->label = $label;
  126. $this->set_attribute('label', $label);
  127. return $this;
  128. }
  129. /**
  130. * Change the field type for form generation
  131. *
  132. * @param string
  133. * @return Fieldset_Field this, to allow chaining
  134. */
  135. public function set_type($type)
  136. {
  137. $this->type = $type;
  138. $this->set_attribute('type', $type);
  139. return $this;
  140. }
  141. /**
  142. * Change the field's current or default value
  143. *
  144. * @param string
  145. * @param bool
  146. * @return Fieldset_Field this, to allow chaining
  147. */
  148. public function set_value($value, $repopulate = false)
  149. {
  150. // Repopulation is handled slightly different in some cases
  151. if ($repopulate)
  152. {
  153. if (($this->type == 'radio' or $this->type == 'checkbox') and empty($this->options))
  154. {
  155. if ($this->value == $value)
  156. {
  157. $this->set_attribute('checked', 'checked');
  158. }
  159. return $this;
  160. }
  161. }
  162. $this->value = $value;
  163. $this->set_attribute('value', $value);
  164. return $this;
  165. }
  166. /**
  167. * Change the field description
  168. *
  169. * @param string
  170. * @return Fieldset_Field this, to allow chaining
  171. */
  172. public function set_description($description)
  173. {
  174. $this->description = strval($description);
  175. return $this;
  176. }
  177. /**
  178. * Template the output
  179. *
  180. * @param string
  181. * @return Fieldset_Field this, to allow chaining
  182. */
  183. public function set_template($template = null)
  184. {
  185. $this->template = $template;
  186. return $this;
  187. }
  188. /**
  189. * Overwrite a default error message
  190. *
  191. * @param string $rule
  192. * @param string $msg
  193. * @return Fieldset_Field
  194. */
  195. public function set_error_message($rule, $msg)
  196. {
  197. empty($rule) and $rule = 0;
  198. $this->error_messages[$rule] = strval($msg);
  199. return $this;
  200. }
  201. /**
  202. * Check if a rule has an error message overwrite
  203. *
  204. * @param string $rule
  205. * @return null|string
  206. */
  207. public function get_error_message($rule)
  208. {
  209. if (isset($this->error_messages[$rule]))
  210. {
  211. return $this->error_messages[$rule];
  212. }
  213. elseif (isset($this->error_messages[0]))
  214. {
  215. return $this->error_messages[0];
  216. }
  217. return null;
  218. }
  219. /**
  220. * Add a validation rule
  221. * any further arguements after the callback will be used as arguements for the callback
  222. *
  223. * @param string|Callback either a validation rule or full callback
  224. * @return Fieldset_Field this, to allow chaining
  225. */
  226. public function add_rule($callback)
  227. {
  228. $args = array_slice(func_get_args(), 1);
  229. $this->rules[] = array($callback, $args);
  230. // Set required setting for forms when rule was applied
  231. if ($callback === 'required')
  232. {
  233. $this->set_attribute('required', 'required');
  234. }
  235. return $this;
  236. }
  237. /**
  238. * Sets an attribute on the field
  239. *
  240. * @param string
  241. * @param mixed new value or null to unset
  242. * @return Fieldset_Field this, to allow chaining
  243. */
  244. public function set_attribute($config, $value = null)
  245. {
  246. $config = is_array($config) ? $config : array($config => $value);
  247. foreach ($config as $key => $value)
  248. {
  249. if ($value === null)
  250. {
  251. unset($this->attributes[$key]);
  252. }
  253. else
  254. {
  255. $this->attributes[$key] = $value;
  256. }
  257. }
  258. return $this;
  259. }
  260. /**
  261. * Get a single or multiple attributes by key
  262. *
  263. * @param string|array a single key or multiple in an array, empty to fetch all
  264. * @param mixed default output when attribute wasn't set
  265. * @return mixed|array a single attribute or multiple in an array when $key input was an array
  266. */
  267. public function get_attribute($key = null, $default = null)
  268. {
  269. if ($key === null)
  270. {
  271. return $this->attributes;
  272. }
  273. if (is_array($key))
  274. {
  275. $output = array();
  276. foreach ($key as $k)
  277. {
  278. $output[$k] = array_key_exists($k, $this->attributes) ? $this->attributes[$k] : $default;
  279. }
  280. return $output;
  281. }
  282. return array_key_exists($key, $this->attributes) ? $this->attributes[$key] : $default;
  283. }
  284. /**
  285. * Add an option value with label
  286. *
  287. * @param string|array one option value, or multiple value=>label pairs in an array
  288. * @param string
  289. * @param bool Whether or not to replace the current options
  290. * @return Fieldset_Field this, to allow chaining
  291. */
  292. public function set_options($value, $label = null, $replace_options = false)
  293. {
  294. if ( ! is_array($value))
  295. {
  296. \Arr::set($this->options, $value, $label);
  297. return $this;
  298. }
  299. $merge = function(&$array, $new, $merge)
  300. {
  301. foreach ($new as $k => $v)
  302. {
  303. if (isset($array[$k]) and is_array($array[$k]) and is_array($v))
  304. {
  305. $merge($array[$k], $v);
  306. }
  307. else
  308. {
  309. $array[$k] = $v;
  310. }
  311. }
  312. };
  313. ($replace_options or empty($this->options)) ? $this->options = $value : $merge($this->options, $value, $merge);
  314. return $this;
  315. }
  316. /**
  317. * Magic get method to allow getting class properties but still having them protected
  318. * to disallow writing.
  319. *
  320. * @return mixed
  321. */
  322. public function __get($property)
  323. {
  324. return $this->$property;
  325. }
  326. /**
  327. * Build the field
  328. *
  329. * @return string
  330. */
  331. public function __toString()
  332. {
  333. try
  334. {
  335. return $this->build();
  336. }
  337. catch (\Exception $e)
  338. {
  339. return $e->getMessage();
  340. }
  341. }
  342. /**
  343. * Return the parent Fieldset object
  344. *
  345. * @return Fieldset
  346. */
  347. public function fieldset()
  348. {
  349. return $this->fieldset;
  350. }
  351. /**
  352. * Alias for $this->fieldset->add() to allow chaining
  353. *
  354. * @return Fieldset_Field
  355. */
  356. public function add($name, $label = '', array $attributes = array(), array $rules = array())
  357. {
  358. return $this->fieldset()->add($name, $label, $attributes, $rules);
  359. }
  360. /**
  361. * Alias for $this->fieldset->add_before() to allow chaining
  362. *
  363. * @return Fieldset_Field
  364. */
  365. public function add_before($name, $label = '', array $attributes = array(), array $rules = array(), $fieldname = null)
  366. {
  367. return $this->fieldset()->add_before($name, $label, $attributes, $rules, $fieldname);
  368. }
  369. /**
  370. * Alias for $this->fieldset->add_after() to allow chaining
  371. *
  372. * @return Fieldset_Field
  373. */
  374. public function add_after($name, $label = '', array $attributes = array(), array $rules = array(), $fieldname = null)
  375. {
  376. return $this->fieldset()->add_after($name, $label, $attributes, $rules, $fieldname);
  377. }
  378. /**
  379. * Build the field
  380. *
  381. * @return string
  382. */
  383. public function build()
  384. {
  385. $form = $this->fieldset()->form();
  386. // Add IDs when auto-id is on
  387. if ($form->get_config('auto_id', false) === true and $this->get_attribute('id') == '')
  388. {
  389. $auto_id = $form->get_config('auto_id_prefix', '')
  390. .str_replace(array('[', ']'), array('-', ''), $this->name);
  391. $this->set_attribute('id', $auto_id);
  392. }
  393. switch( ! empty($this->attributes['tag']) ? $this->attributes['tag'] : $this->type)
  394. {
  395. case 'hidden':
  396. $build_field = $form->hidden($this->name, $this->value, $this->attributes);
  397. break;
  398. case 'radio': case 'checkbox':
  399. if ($this->options)
  400. {
  401. $build_field = array();
  402. $i = 0;
  403. foreach ($this->options as $value => $label)
  404. {
  405. $attributes = $this->attributes;
  406. $attributes['name'] = $this->name;
  407. $this->type == 'checkbox' and $attributes['name'] .= '['.$i.']';
  408. $attributes['value'] = $value;
  409. $attributes['label'] = $label;
  410. if (is_array($this->value) ? in_array($value, $this->value) : $value == $this->value)
  411. {
  412. $attributes['checked'] = 'checked';
  413. }
  414. if( ! empty($attributes['id']))
  415. {
  416. $attributes['id'] .= '_'.$i;
  417. }
  418. else
  419. {
  420. $attributes['id'] = null;
  421. }
  422. $build_field[$form->label($label, $attributes['id'])] = $this->type == 'radio'
  423. ? $form->radio($attributes)
  424. : $form->checkbox($attributes);
  425. $i++;
  426. }
  427. }
  428. else
  429. {
  430. $build_field = $this->type == 'radio'
  431. ? $form->radio($this->name, $this->value, $this->attributes)
  432. : $form->checkbox($this->name, $this->value, $this->attributes);
  433. }
  434. break;
  435. case 'select':
  436. $attributes = $this->attributes;
  437. $name = $this->name;
  438. unset($attributes['type']);
  439. array_key_exists('multiple', $attributes) and $name .= '[]';
  440. $build_field = $form->select($name, $this->value, $this->options, $attributes);
  441. break;
  442. case 'textarea':
  443. $attributes = $this->attributes;
  444. unset($attributes['type']);
  445. $build_field = $form->textarea($this->name, $this->value, $attributes);
  446. break;
  447. case 'button':
  448. $build_field = $form->button($this->name, $this->value, $this->attributes);
  449. break;
  450. case false:
  451. $build_field = '';
  452. break;
  453. default:
  454. $build_field = $form->input($this->name, $this->value, $this->attributes);
  455. break;
  456. }
  457. if (empty($build_field) or $this->type == 'hidden')
  458. {
  459. return $build_field;
  460. }
  461. return $this->template($build_field);
  462. }
  463. protected function template($build_field)
  464. {
  465. $form = $this->fieldset()->form();
  466. $required_mark = $this->get_attribute('required', null) ? $form->get_config('required_mark', null) : null;
  467. $label = $this->label ? $form->label($this->label, null, array('for' => $this->get_attribute('id', null))) : '';
  468. $error_template = $form->get_config('error_template', '');
  469. $error_msg = ($form->get_config('inline_errors') && $this->error()) ? str_replace('{error_msg}', $this->error(), $error_template) : '';
  470. $error_class = $this->error() ? $form->get_config('error_class') : '';
  471. if (is_array($build_field))
  472. {
  473. $label = $this->label ? $form->label($this->label) : '';
  474. $template = $this->template ?: $form->get_config('multi_field_template', "\t\t<tr>\n\t\t\t<td class=\"{error_class}\">{group_label}{required}</td>\n\t\t\t<td class=\"{error_class}\">{fields}\n\t\t\t\t{field} {label}<br />\n{fields}\t\t\t{error_msg}\n\t\t\t</td>\n\t\t</tr>\n");
  475. if ($template && preg_match('#\{fields\}(.*)\{fields\}#Dus', $template, $match) > 0)
  476. {
  477. $build_fields = '';
  478. foreach ($build_field as $lbl => $bf)
  479. {
  480. $bf_temp = str_replace('{label}', $lbl, $match[1]);
  481. $bf_temp = str_replace('{required}', $required_mark, $bf_temp);
  482. $bf_temp = str_replace('{field}', $bf, $bf_temp);
  483. $build_fields .= $bf_temp;
  484. }
  485. $template = str_replace($match[0], '{fields}', $template);
  486. $template = str_replace(array('{group_label}', '{required}', '{fields}', '{error_msg}', '{error_class}', '{description}'), array($label, $required_mark, $build_fields, $error_msg, $error_class, $this->description), $template);
  487. return $template;
  488. }
  489. // still here? wasn't a multi field template available, try the normal one with imploded $build_field
  490. $build_field = implode(' ', $build_field);
  491. }
  492. $template = $this->template ?: $form->get_config('field_template', "\t\t<tr>\n\t\t\t<td class=\"{error_class}\">{label}{required}</td>\n\t\t\t<td class=\"{error_class}\">{field} {description} {error_msg}</td>\n\t\t</tr>\n");
  493. $template = str_replace(array('{label}', '{required}', '{field}', '{error_msg}', '{error_class}', '{description}'),
  494. array($label, $required_mark, $build_field, $error_msg, $error_class, $this->description),
  495. $template);
  496. return $template;
  497. }
  498. /**
  499. * Alias for $this->fieldset->validation->input() for this field
  500. *
  501. * @return mixed
  502. */
  503. public function input()
  504. {
  505. return $this->fieldset()->validation()->input($this->name);
  506. }
  507. /**
  508. * Alias for $this->fieldset->validation->validated() for this field
  509. *
  510. * @return mixed
  511. */
  512. public function validated()
  513. {
  514. return $this->fieldset()->validation()->validated($this->name);
  515. }
  516. /**
  517. * Alias for $this->fieldset->validation->error() for this field
  518. *
  519. * @return Validation_Error
  520. */
  521. public function error()
  522. {
  523. return $this->fieldset()->validation()->error($this->name);
  524. }
  525. }