3 * A helper for constructing web forms
5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, this is free software
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class WebFormHelper extends BaseWebHelper implements HelpableTemplate {
26 * Wether the form tag is opened (keep at false or else your forms will
29 private $formOpened = false;
34 private $formName = "";
37 * Wether form tag is enabled (default: true)
39 private $formEnabled = true;
42 const EXCEPTION_FORM_NAME_INVALID = 0x120;
43 const EXCEPTION_CLOSED_FORM = 0x121;
44 const EXCEPTION_OPENED_FORM = 0x122;
45 const EXCEPTION_UNEXPECTED_CLOSED_GROUP = 0x123;
48 * Protected constructor
52 protected function __construct () {
53 // Call parent constructor
54 parent::__construct(__CLASS__);
58 * Creates the helper class with the given template engine instance and form name
60 * @param $templateInstance An instance of a valid template engine
61 * @param $formName Name of the form
62 * @param $formId Value for "id" attribute (default: $formName)
63 * @param $withForm Wether include the form tag
64 * @return $helperInstance A preparedf instance of this helper
66 public final static function createWebFormHelper (CompileableTemplate $templateInstance, $formName, $formId = false, $withForm = true) {
68 $helperInstance = new WebFormHelper();
70 // Set template instance
71 $helperInstance->setTemplateInstance($templateInstance);
73 // Is the form id not set?
74 if ($formId === false) {
75 // Use form id from form name
80 $helperInstance->setFormName($formName);
82 // A form-less field may say "false" here...
83 if ($withForm === true) {
85 $helperInstance->addFormTag($formName, $formId);
88 $helperInstance->enableForm(false);
91 // Return the prepared instance
92 return $helperInstance;
96 * Add the form tag or close it an already opened form tag
98 * @param $formName Name of the form (default: false)
99 * @param $formId Id of the form (attribute "id"; default: false)
101 * @throws InvalidFormNameException If the form name is invalid (=false)
102 * @todo Add some unique PIN here to bypass problems with some browser and/or extensions
104 public function addFormTag ($formName = false, $formId = false) {
105 // When the form is not yet opened at least form name must be valid
106 if (($this->formOpened === false) && ($formName === false)) {
107 // Thrown an exception
108 throw new InvalidFormNameException ($this, self::EXCEPTION_FORM_NAME_INVALID);
111 // Close the form is default
112 $formContent = "</form>";
114 // Check wether we shall open or close the form
115 if (($this->formOpened === false) && ($this->formEnabled === true)) {
117 $formContent = sprintf("<form name=\"%s\" class=\"forms\" action=\"%s/%s\" method=\"%s\" target=\"%s\"",
119 $this->getConfigInstance()->readConfig('base_url'),
120 $this->getConfigInstance()->readConfig('form_action'),
121 $this->getConfigInstance()->readConfig('form_method'),
122 $this->getConfigInstance()->readConfig('form_target')
125 // Add form id as well
126 $formContent .= sprintf(" id=\"%s_form\"",
133 // Open the form and remeber the form name
134 $this->formOpened = true;
136 // Add it to the content
137 $this->addHeaderContent($formContent);
139 // Add the hidden field required to identify safely this form
140 $this->addInputHiddenField('form', $this->getFormName());
143 if ($this->ifGroupOpenedPreviously()) {
144 // Then automatically close it here
145 $this->addFormGroup();
149 $this->formOpened = false;
151 // Add it to the content
152 $this->addFooterContent($formContent);
157 * Add a text input tag to the form or throw an exception if it is not yet
158 * opened. The field's name will be set as id.
160 * @param $fieldName Input field name
161 * @param $fieldValue Input default value (default: empty)
163 * @throws FormClosedException If the form is not yet opened
165 public function addInputTextField ($fieldName, $fieldValue = "") {
166 // Is the form opened?
167 if (($this->formOpened === false) && ($this->formEnabled === true)) {
168 // Throw an exception
169 throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
172 // Generate the content
173 $inputContent = sprintf("<input type=\"text\" class=\"textfield %s_field\" name=\"%s\" value=\"%s\" />",
179 // And add it maybe with a "li" tag
180 $this->addContentToPreviousGroup($inputContent);
184 * Add a text input tag to the form with pre-loaded default value
186 * @param $fieldName Input field name
189 public function addInputTextFieldWithDefault ($fieldName) {
190 // Get the value from instance
191 $fieldValue = $this->getValueField($fieldName);
192 //* DEBUG: */ echo __METHOD__.":".$fieldName."=".$fieldValue."<br />\n";
194 // Add the text field
195 $this->addInputTextField($fieldName, $fieldValue);
199 * Add a password input tag to the form or throw an exception if it is not
200 * yet opened. The field's name will be set as id.
202 * @param $fieldName Input field name
203 * @param $fieldValue Input default value (default: empty)
205 * @throws FormClosedException If the form is not yet opened
207 public function addInputPasswordField ($fieldName, $fieldValue = "") {
208 // Is the form opened?
209 if (($this->formOpened === false) && ($this->formEnabled === true)) {
210 // Throw an exception
211 throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
214 // Generate the content
215 $inputContent = sprintf("<input type=\"password\" class=\"password %s_field\" name=\"%s\" value=\"%s\" />",
222 $this->addContentToPreviousGroup($inputContent);
226 * Add a hidden input tag to the form or throw an exception if it is not
227 * yet opened. The field's name will be set as id.
229 * @param $fieldName Input field name
230 * @param $fieldValue Input default value (default: empty)
232 * @throws FormClosedException If the form is not yet opened
234 public function addInputHiddenField ($fieldName, $fieldValue = "") {
235 // Is the form opened?
236 if (($this->formOpened === false) && ($this->formEnabled === true)) {
237 // Throw an exception
238 throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
241 // Generate the content
242 $inputContent = sprintf("<input type=\"hidden\" name=\"%s\" value=\"%s\" />",
248 $this->addContentToPreviousGroup($inputContent);
252 * Add a hidden input tag to the form with pre-loaded default value
254 * @param $fieldName Input field name
257 public function addInputHiddenFieldWithDefault ($fieldName) {
258 // Get the value from instance
259 $fieldValue = $this->getValueField($fieldName);
260 //* DEBUG: */ echo __METHOD__.":".$fieldName."=".$fieldValue."<br />\n";
262 // Add the text field
263 $this->addInputHiddenField($fieldName, $fieldValue);
267 * Add a hidden input tag to the form with configuration value
269 * @param $fieldName Input field name
270 * @param $prefix Prefix for configuration without trailing _
273 public function addInputHiddenConfiguredField ($fieldName, $prefix) {
274 // Get the value from instance
275 $fieldValue = $this->getConfigInstance()->readConfig("{$prefix}_{$fieldName}");
276 //* DEBUG: */ echo __METHOD__.":".$fieldName."=".$fieldValue."<br />\n";
278 // Add the text field
279 $this->addInputHiddenField($fieldName, $fieldValue);
283 * Add a checkbox input tag to the form or throw an exception if it is not
284 * yet opened. The field's name will be set as id.
286 * @param $fieldName Input field name
287 * @param $fieldChecked Wether the field is checked (defaut: checked)
289 * @throws FormClosedException If the form is not yet opened
291 public function addInputCheckboxField ($fieldName, $fieldChecked = true) {
292 // Is the form opened?
293 if (($this->formOpened === false) && ($this->formEnabled === true)) {
294 // Throw an exception
295 throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
298 // Set wether the check box is checked...
299 $checked = " checked=\"checked\"";
300 if ($fieldChecked === false) $checked = " ";
302 // Generate the content
303 $inputContent = sprintf("<input type=\"checkbox\" name=\"%s\" class=\"checkbox %s_field\" value=\"1\"%s/>",
310 $this->addContentToPreviousGroup($inputContent);
314 * Add a reset input tag to the form or throw an exception if it is not
315 * yet opened. The field's name will be set as id.
317 * @param $buttonText Text displayed on the button
319 * @throws FormClosedException If the form is not yet opened
321 public function addInputResetButton ($buttonText) {
322 // Is the form opened?
323 if (($this->formOpened === false) && ($this->formEnabled === true)) {
324 // Throw an exception
325 throw new FormClosedException (array($this, "reset"), self::EXCEPTION_CLOSED_FORM);
328 // Generate the content
329 $inputContent = sprintf("<input type=\"reset\" class=\"reset_button\" id=\"%s_reset\" value=\"%s\" />",
330 $this->getFormName(),
335 $this->addContentToPreviousGroup($inputContent);
339 * Add a reset input tag to the form or throw an exception if it is not
340 * yet opened. The field's name will be set as id.
342 * @param $buttonText Text displayed on the button
344 * @throws FormClosedException If the form is not yet opened
346 public function addInputSubmitButton ($buttonText) {
347 // Is the form opened?
348 if (($this->formOpened === false) && ($this->formEnabled === true)) {
349 // Throw an exception
350 throw new FormClosedException (array($this, "submit"), self::EXCEPTION_CLOSED_FORM);
353 // Generate the content
354 $inputContent = sprintf("<input type=\"submit\" class=\"submit_button\" id=\"%s_submit\" name=\"%s_button\" value=\"%s\" />",
355 $this->getFormName(),
356 $this->getFormName(),
361 $this->addContentToPreviousGroup($inputContent);
365 * Add a form group or close an already opened and open a new one
367 * @param $groupId Name of the group or last opened if empty
368 * @param $groupText Text including HTML to show above this group
370 * @throws FormClosedException If no form has been opened before
371 * @throws EmptyVariableException If $groupId is not set
373 public function addFormGroup ($groupId = "", $groupText = "") {
375 if (($this->formOpened === false) && ($this->formEnabled === true)) {
376 // Throw exception here
377 throw new FormClosedException(array($this, $groupId), self::EXCEPTION_CLOSED_FORM);
380 // At least the group name should be set
381 if ((empty($groupId)) && ($this->ifGroupOpenedPreviously() === false)) {
382 // Throw exception here
383 throw new EmptyVariableException(array($this, 'groupId'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
384 } elseif (empty($groupId)) {
385 // Close the last opened
386 $groupId = $this->getPreviousGroupId();
389 // Same group to open?
390 if (($this->ifGroupOpenedPreviously() === false) && ($groupId === $this->getPreviousGroupId())) {
391 // Abort here silently
395 // Initialize content with closing div by default
396 $content = " </div>\n</div><!-- Group - CLOSE //-->";
398 // Is this group opened?
399 if ($this->ifGroupOpenedPreviously() === false) {
400 // Begin the div/span blocks
401 $content = sprintf("<!-- Group %s - OPEN //-->
402 <div class=\"group_box\" id=\"%s_group_box\">
403 <span class=\"group_text\" id=\"%s_group_text\">
406 <div class=\"group_field\" id=\"%s_group_field\">",
415 $this->openGroupByIdContent($groupId, $content, "div");
417 // Is a sub group opened?
418 if ($this->ifSubGroupOpenedPreviously()) {
420 $this->addFormSubGroup();
423 // Get previous group id
424 $prevGroupId = $this->getPreviousGroupId();
427 $this->closePreviousGroupByContent($content);
429 // All call it again if the group name is not empty
430 if ((!empty($groupId)) && ($groupId != $prevGroupId)) {
431 //* DEBUG: */ echo $groupId."/".$prevGroupId."<br />\n";
432 $this->addFormGroup($groupId, $groupText);
438 * Add a form sub group or close an already opened and open a new one or
439 * throws an exception if no group has been opened before or if the sub
440 * group name is empty.
442 * @param $subGroupId Name of the group or last opened if empty
443 * @param $subGroupText Text including HTML to show above this group
445 * @throws FormFormClosedException If no group has been opened before
446 * @throws EmptyVariableException If $subGroupId is not set
448 public function addFormSubGroup ($subGroupId = "", $subGroupText = "") {
449 // Is a group opened?
450 if ($this->ifGroupOpenedPreviously() === false) {
451 // Throw exception here
452 throw new FormFormClosedException(array($this, $subGroupId), self::EXCEPTION_UNEXPECTED_CLOSED_GROUP);
455 // At least the sub group name should be set
456 if ((empty($subGroupId)) && ($this->ifSubGroupOpenedPreviously() === false)) {
457 // Throw exception here
458 throw new EmptyVariableException(array($this, 'subGroupId'), self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
459 } elseif (empty($subGroupId)) {
460 // Close the last opened
461 $subGroupId = $this->getPreviousSubGroupId();
464 // Same sub group to open?
465 if (($this->ifSubGroupOpenedPreviously() === false) && ($subGroupId == $this->getPreviousSubGroupId())) {
466 // Abort here silently
470 // Initialize content with closing div by default
471 $content = " </div>\n</div><!-- Sub group- CLOSE //-->";
473 // Is this group opened?
474 if ($this->ifSubGroupOpenedPreviously() === false) {
475 // Begin the span block
476 $content = sprintf("<!-- Sub group %s - OPEN //-->
477 <div class=\"subgroup_box\" id=\"%s_subgroup_box\">
478 <span class=\"subgroup_text\" id=\"%s_subgroup_text\">
481 <div class=\"subgroup_field\" id=\"%s_subgroup_field\">",
489 // Switch the state and remeber the name
490 $this->openSubGroupByIdContent($subGroupId, $content, "div");
492 // Get previous sub group id
493 $prevSubGroupId = $this->getPreviousSubGroupId();
496 $this->closePreviousSubGroupByContent($content);
498 // All call it again if sub group name is not empty
499 if ((!empty($subGroupId)) && ($subGroupId != $prevSubGroupId)) {
500 $this->addFormSubGroup($subGroupId, $subGroupText);
506 * Add text surrounded by a span block when there is a group opened before
507 * or else by a div block.
509 * @param $fieldName Field name
510 * @param $fieldText Text for the field
512 * @throws FormClosedException If the form is not yet opened
514 public function addFieldText ($fieldName, $fieldText) {
515 // Is the form opened?
516 if (($this->formOpened === false) && ($this->formEnabled === true)) {
517 // Throw an exception
518 throw new FormClosedException (array($this, $fieldName), self::EXCEPTION_CLOSED_FORM);
521 // Set the block type
523 if ($this->ifGroupOpenedPreviously()) $block = "span";
525 // Generate the content
526 $inputContent = sprintf(" <%s id=\"%s_text\">
536 $this->addContentToPreviousGroup($inputContent);
540 * Add text (notes) surrounded by a div block. Still opened groups or sub
541 * groups will be automatically closed.
543 * @param $noteId Id for this note
544 * @param $formNotes The form notes we shell addd
546 * @throws FormClosedException If the form is not yet opened
548 public function addFormNote ($noteId, $formNotes) {
549 // Is the form opened?
550 if (($this->formOpened === false) && ($this->formEnabled === true)) {
551 // Throw an exception
552 throw new FormClosedException (array($this, "form_notes"), self::EXCEPTION_CLOSED_FORM);
555 // Generate the content
556 $inputContent = sprintf(" <div id=\"form_note_%s\">
564 $this->addContentToPreviousGroup($inputContent);
568 * Adds a selection box as a sub group to the form. Do not box this into
569 * another sub group. Sub-sub groups are not (yet) supported.
571 * @param $selectId Id of the selection box
572 * @param $firstEntry Content to be added as first non-selectable entry
574 * @throws FormClosedException If the form is not yet opened
576 public function addInputSelectField ($selectId, $firstEntry) {
577 // Is the form group opened?
578 if (($this->formOpened === false) && ($this->formEnabled === true)) {
579 // Throw an exception
580 throw new FormClosedException (array($this, "form_notes"), self::EXCEPTION_CLOSED_FORM);
583 // Shall we close or open the sub group?
584 if (($this->ifSubGroupOpenedPreviously() === false) && ($this->getPreviousSubGroupId() !== $selectId)) {
585 // Initialize first entry (which might be non-selectable if content is provided
586 if (!empty($firstEntry)) {
587 // Add selection around it
588 $firstEntry = sprintf("<option value=\"invalid\" disabled=\"disabled\">%s</option>\n",
593 // Construct the opening select tag
594 $content = sprintf("<select class=\"select_box\" id=\"%s_%s\" name=\"%s\">\n%s",
595 $this->getFormName(),
601 // Open the sub group
602 $this->openSubGroupByIdContent($selectId, $content, "select");
603 } elseif ($this->getPreviousSubGroupId() != $selectId) {
604 // Something went wrong!
605 $this->debugInstance(__METHOD__."(): Previous sub group id {$this->getPreviousSubGroupId()} does not match current id {$selectId}.");
607 // Close the sub group
608 $this->closePreviousSubGroupByContent("</select>");
613 * Adds a non-selectable sub option to a previously added selection box.
614 * This method does *not* validate if there is already a sub option added
615 * with the same name. We need to finish this here!
617 * @param $subName Name of the sub action
618 * @param $subValue Value of the sub action
620 * @throws HelperNoPreviousOpenedSubGroupException If no previously opened sub group was found
621 * @todo Add checking if sub option is already added
623 public function addSelectSubOption ($subName, $subValue) {
624 // Is there a sub group (shall be a selection box!)
625 if ($this->ifSubGroupOpenedPreviously() === false) {
626 // Then throw an exception here
627 throw new HelperNoPreviousOpenedSubGroupException(array($this, $content), self::EXCEPTION_NO_PREVIOUS_SUB_GROUP_OPENED);
630 // Render the content
631 $content = sprintf("<option value=\"invalid\" class=\"suboption suboption_%s\" disabled=\"disabled\">%s</option>\n",
636 // Add the content to the previously opened sub group
637 $this->addContentToPreviousGroup($content);
641 * Adds a selectable option to a previously added selection box. This method
642 * does *not* validate if there is already a sub option added with the same
643 * name. We need to finish this here!
645 * @param $optionName Name of the sub action
646 * @param $optionValue Value of the sub action
648 * @throws HelperNoPreviousOpenedSubGroupException If no previously opened sub group was found
649 * @todo Add checking if sub option is already added
651 public function addSelectOption ($optionName, $optionValue) {
652 // Is there a sub group (shall be a selection box!)
653 if ($this->ifSubGroupOpenedPreviously() === false) {
654 // Then throw an exception here
655 throw new HelperNoPreviousOpenedSubGroupException(array($this, $content), self::EXCEPTION_NO_PREVIOUS_SUB_GROUP_OPENED);
658 // Render the content
659 $content = sprintf("<option value=\"%s\" class=\"option option_%s\">%s</option>\n",
665 // Add the content to the previously opened sub group
666 $this->addContentToPreviousGroup($content);
670 * Adds a pre-configured CAPTCHA
674 public function addCaptcha () {
675 // Get last executed pre filter
676 $extraInstance = Registry::getRegistry()->getInstance('extra');
678 // Get a configured instance
679 $captchaInstance = ObjectFactory::createObjectByConfiguredName($this->getFormName().'_captcha', array($this, $extraInstance));
681 // Initiate the CAPTCHA
682 $captchaInstance->initiateCaptcha();
684 // Render the CAPTCHA code
685 $captchaInstance->renderCode();
687 // Get the content and add it to the helper
688 $this->addContentToPreviousGroup($captchaInstance->renderContent());
692 * Enables/disables the form tag usage
694 * @param $formEnabled Wether form is enabled or disabled
697 public final function enableForm ($formEnabled = true) {
698 $this->formEnabled = (bool) $formEnabled;
702 * Setter for form name
704 * @param $formName Name of this form
707 public final function setFormName ($formName) {
708 $this->formName = (string) $formName;
712 * Getter for form name
714 * @return $formName Name of this form
716 public final function getFormName () {
717 return $this->formName;
721 * Checks wether the registration requires a valid email address
723 * @return $required Wether the email address is required
725 public function ifRegisterRequiresEmailVerification () {
726 $required = ($this->getConfigInstance()->readConfig('register_requires_email') === "Y");
731 * Checks wether profile data shall be asked
733 * @return $required Wether profile data shall be asked
735 public function ifRegisterIncludesProfile () {
736 $required = ($this->getConfigInstance()->readConfig('register_includes_profile') === "Y");
741 * Checks wether this form is secured by a CAPTCHA
743 * @return $isSecured Wether this form is secured by a CAPTCHA
745 public function ifFormSecuredWithCaptcha () {
746 $isSecured = ($this->getConfigInstance()->readConfig($this->getFormName().'_captcha_secured') === "Y");
751 * Flushs the content out (not yet secured against open forms, etc.!) or
752 * close the form automatically
755 * @throws FormOpenedException If the form is still open
757 public function flushContent () {
758 // Is the form still open?
759 if (($this->formOpened === true) && ($this->formEnabled === true)) {
760 // Close the form automatically
762 } elseif ($this->formEnabled === false) {
763 if ($this->ifSubGroupOpenedPreviously()) {
765 $this->addFormSubGroup();
766 } elseif ($this->ifGroupOpenedPreviously()) {
768 $this->addFormGroup();
772 // Send content to template engine
773 //* DEBUG: */ echo __METHOD__.": form=".$this->getFormName().", size=".strlen($this->renderContent())."<br />\n";
774 $this->getTemplateInstance()->assignVariable($this->getFormName(), $this->renderContent());