field.php 15 KB

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