We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 2935
    • 15 Posts
    I am fairly new at PHP and I am trying to do a registration/document request form with eForm where the user can click checkboxes from a list of documents, fill out the form and submit it. Submitting the form sends of a report to the admin and auto-sends an email with generated links to the requested documents. The list of documents(checkboxes and labels) is generated with a PHP function called by the eFormOnBeforeFormParse and the links in the email are generated by another function called by the eFormOnBeforeMailSent events. I am also allowing for checkboxes to be set automatically by a query string value (links from a library page).

    Everything is working fine except if the user misses a field and the form gets posted back with the validation message the state of the dynamically created checkboxes is lost. I thought of trying to grab the values from the $fields array to set these states again and I am having no luck. How does one go about doing this? Can I do this with a list of checkboxes that isn’t validated by eForm?

    Here is the snippet call:
    [[ComposeDocLinks]]
    [[RegDocsMenu]]
    [!eForm? &formid=`RegistrationForm` &from=`[+email+]` &fromname=`[+first_name+] [+last_name+]` &sendAsHTML=`1` &to=`[email protected]` &tpl=`RegistrationForm` &report=`RegistrationFormReport` &subject=`FMI Website Registration` &allowhtml=`1` &automessage=`RegistrationFormAutoreply` &autosender=`[email protected]` &autoSenderName=`The Fraud Management Institute` &eFormOnBeforeFormParse=`regDocsMenu` &eFormOnBeforeMailSent=`composeLinks` &debug=`1` &noemail=`1` &thankyou=`RegistrationFormReport` !]
    


    Here is the php function that generates the checkbox list. Right now I am grabbing values from a text file. This will be from MODx or a database later:
    <?php
    function regDocsMenu(&$fields, &$templates)
    {
     	#
    	global $modx; // Access to DocumentParser
    	$doc_list_id = 68;
    	$evt =& $modx->event; // The Snippet call event (not eFormOnBeforeFormParse event)
    	#
    
    	#
    	// Replicate $isPostBack variable
    	#
    	$validFormId = ($evt->params['formid'] == $_POST['formid']);
    	#
    	$isPostBack = ($validFormId && count($_POST) > 0); // (bool)true if the form is being updated
    		if (!$isPostBack) {
    			//set up some array variable 
    			$lines = array();
    			$doclist = array();
    			//check the URL for any query string vars for requested docs
    			if (isset($_GET['docid'])) {
    				$requested = $_GET['docid'];
    			} else {
    				$requested = 0;
    			}
    			//get the PDF document list from MODx text document
    			$doc = $modx->getDocument($doc_list_id, '*', 1); // Search published first.
    			if (empty($doc)) {
    				$doc = $modx->getDocument($doc_list_id, '*', 0); // Un-published next
    			}
    			//separate the lines of documents
    			$lines = explode("\n", $doc['content']);
    			unset($lines[0]);
    			//loop through and grab file name and title
    			foreach ($lines as $line) {
    				if (!empty($line) || $line != "") {
    					$pos = strrpos($line, "]")+1;
    					$tempstr = substr($line, $pos);
    					$tempArr = explode("|", $tempstr);
    					array_push($doclist, $tempArr);
    				}
    			}
    			//start the list of boxes
    			$output = "<ul>";
    			
    			$i = 1;
    			//add each document title and filename as label checkboxes
    				foreach ($doclist as $item) {
    					$output .= "\t<li><label for=\"".str_replace("&", "", str_replace(" ", "_", $item[0]))."\" ><input type=\"checkbox\" id=\"".str_replace("&", "", str_replace(" ", "_", $item[0]))."\" name=\"requested_documents[]\" value=\"".$item[1]."\"";
    					//check to see if it is a selected document
    					if ($requested == $i) {
    						$output .= " checked=\"checked\"";
    					}
    					$output .= " />".$item[0]."</label></li>\n";
    					$i++;
    				}
    			$output .= "</ul>";
    		} else {
    			
    			//if not a postback 
    			
    			//set up some array variable 
    						
    			$lines = array();
    			$doclist = array();
    			//get the PDF document list from MODx text document
    			$doc = $modx->getDocument($doc_list_id, '*', 1); // Search published first.
    			if (empty($doc)) {
    				$doc = $modx->getDocument($doc_list_id, '*', 0); // Un-published next
    			}
    			//separate the lines of documents
    			$lines = explode("\n", $doc['content']);
    			unset($lines[0]);
    			//loop through and grab file name and title
    			foreach ($lines as $line) {
    				if (!empty($line) || $line != "") {
    					$pos = strrpos($line, "]")+1;
    					$tempstr = substr($line, $pos);
    					$tempArr = explode("|", $tempstr);
    					array_push($doclist, $tempArr);
    				}
    			}
    			
    			//start the list of boxes			
    			$output = "<ul>";
    			$i = 1;
    			//add each document title and filename as label checkboxes
    				foreach ($doclist as $item) {
    					$output .= "\t<li><label for=\"".str_replace("&", "", str_replace(" ", "_", $item[0]))."\" ><input type=\"checkbox\" id=\"".str_replace("&", "", str_replace(" ", "_", $item[0]))."\" name=\"requested_documents[]\" value=\"".$item[1]."\"";
    					
    					//***** need to do something here to check what was posted ***
    					
    					
    					$output .= " />".$item[0]."</label></li>\n";
    					$i++;
    				}
    			$output .= "</ul>";
    			
    				### trying to output fields data on postback so I can see values
    				$fieldsdata = "";
    				foreach($fields as $fld => $value){
    				      if(!empty($value) && field_is_not_required($fld)){
    				         $fieldsdata .="<p>{$fld}: {$value}</p>";   
    				      }
    				   }
    
    			$fields['thefields'] = $fieldsdata;
    		}
    		
    	$fields['docsdropdown'] = $output;
    	return true;
    }
    ?>
    


    The form code:
    	<script type="text/javascript" charset="utf-8">
    			var alerted = false;
    		function enableOtherBox(ckbox,elem) {
    			if (ckbox.checked == true) {
    				document.forms['RegistrationForm'].elements[elem].disabled = false;
    			} else {
    				document.forms['RegistrationForm'].elements[elem].disabled = true;
    			}
    		}
    	
    	</script>	
    [+validationmessage+]
    	<form method="post" action="[~[*id*]~]" id="RegistrationForm" name="RegistrationForm" >
    	<input name="formid" type="hidden" value="RegistrationForm" />
    	<fieldset id="doclist">
    		Please send me a copy of these documents:<br />
    		[+docsdropdown+]
    	</fieldset>
    <fieldset>	<label for="first_name">First Name</label>
    	<input name="first_name" id="first_name" class="text" type="text" eform="First Name::1:" />
    	<br />
    	<label for="last_name">Last Name</label>
    	<input name="last_name" id="last_name" class="text" type="text" eform="Last Name::1:" />
    	<br />
    	<label for="company_name">Company Name</label>
    	<input type="text" name="company_name" id="company_name" eform="Company Name::1:" />
    	<br />
    	<label for="title">Title</label>
    	<input type="text" name="title" id="title" eform="Title::1:" />
    </fieldset>
    <fieldset>Company Address:<br />
    	<label for="company_address1">Address 1</label>
    	<input type="text" name="company_address1" id="company_address1" eform="Address::1:" />
    	<br />
    		<label for="company_address2">Address 2</label>
    		<input type="text" name="company_address2" id="company_address2"  />
    		<br />
    			<label for="company_city">City</label>
    			<input type="text" name="company_city" id="company_city" eform="City::1:" />
    			<br />
    			<label for="company_state">State</label>
    				<select id="company_state" name="company_state" eform="State::1:">
    				<option value="">-- Select One --</option>
    
    				<optgroup label="U.S. States">
    				<option value="AK">Alaska</option>
    				<option value="AL">Alabama</option>
    				<option value="AR">Arkansas</option>
    				<option value="AZ">Arizona</option>
    				<option value="CA">California</option>
    				<option value="CO">Colorado</option>
    				<option value="CT">Connecticut</option>
    				<option value="DC">District of Columbia</option>
    				<option value="DE">Delaware</option>
    				<option value="FL">Florida</option>
    				<option value="GA">Georgia</option>
    				<option value="HI">Hawaii</option>
    				<option value="IA">Iowa</option>
    				<option value="ID">Idaho</option>
    				<option value="IL">Illinois</option>
    				<option value="IN">Indiana</option>
    				<option value="KS">Kansas</option>
    				<option value="KY">Kentucky</option>
    				<option value="LA">Louisiana</option>
    				<option value="MA">Massachusetts</option>
    				<option value="MD">Maryland</option>
    				<option value="ME">Maine</option>
    				<option value="MI">Michigan</option>
    				<option value="MN">Minnesota</option>
    				<option value="MO">Missouri</option>
    				<option value="MS">Mississippi</option>
    				<option value="MT">Montana</option>
    				<option value="NC">North Carolina</option>
    				<option value="ND">North Dakota</option>
    				<option value="NE">Nebraska</option>
    				<option value="NH">New Hampshire</option>
    				<option value="NJ">New Jersey</option>
    				<option value="NM">New Mexico</option>
    				<option value="NV">Nevada</option>
    				<option value="NY">New York</option>
    				<option value="OH">Ohio</option>
    				<option value="OK">Oklahoma</option>
    				<option value="OR">Oregon</option>
    				<option value="PA">Pennsylvania</option>
    				<option value="PR">Puerto Rico</option>
    				<option value="RI">Rhode Island</option>
    
    				<option value="SC">South Carolina</option>
    				<option value="SD">South Dakota</option>
    				<option value="TN">Tennessee</option>
    				<option value="TX">Texas</option>
    				<option value="UT">Utah</option>
    				<option value="VA">Virginia</option>
    				<option value="VT">Vermont</option>
    				<option value="WA">Washington</option>
    				<option value="WI">Wisconsin</option>
    				<option value="WV">West Virginia</option>
    				<option value="WY">Wyoming</option>
    				</optgroup>
    				<optgroup label="Canadian Provinces">
    				<option value="AB">Alberta</option>
    				<option value="BC">British Columbia</option>
    				<option value="MB">Manitoba</option>
    				<option value="NB">New Brunswick</option>
    				<option value="NF">Newfoundland</option>
    				<option value="NT">Northwest Territories</option>
    				<option value="NS">Nova Scotia</option>
    				<option value="NU">Nunavut</option>
    				<option value="ON">Ontario</option>
    				<option value="PE">Prince Edward Island</option>
    				<option value="QC">Quebec</option>
    				<option value="SK">Saskatchewan</option>
    				<option value="YT">Yukon Territory</option>
    				</optgroup>
    				</select>
    		
    			<br />
    			<label for="company_zip">Zip</label>
    			<input type="text" name="company_zip" id="company_zip" eform="Zip::1:" />
    			<br />
    			<label for="company_country">Country</label>
    			<input type="text" name="company_country" id="company_country" />
    </fieldset>
    <fieldset>	<label for="phone">Phone</label>
    	<input type="text" name="phone" id="phone" eform="Phone Number::1:" />
    	<br />
    	<label for="email">E-mail address</label>
    	<input type="text" name="email" id="email" eform="Email Address:email:1" /></fieldset>
    
    	<div class="checkbox_list clearfix">
    		Industry:<br />
    		   <label><input type="radio" name="industry" value="Banking" eform="Your industry::1"/>Banking</label>
    		   <label><input type="radio" name="industry" value="Online Retailing" />Online Retailing</label>
    		   <label><input type="radio" name="industry" value="Fraud Management Consultant" />Fraud Management Consultant</label>
    		   <label><input type="radio" name="industry" value="Fraud Management Software" />Fraud Management Platform / Software / Data Provider</label>
    		   <label class="lblother"><input type="radio" name="industry" value="Industry-Other:" class="inpother"  onchange="enableOtherBox(this,'industry_other_name')" />Other</label><input type="text" name="industry_other_name" disabled="disabled" class="fldother" />
    	</div>
    	<div class="checkbox_list clearfix">
    		Fraud Role (check all that apply):<br />
    		   <label><input type="checkbox" name="fraud_role[]" value="Management" eform="Your fraud role::1" />Management</label>
    		   <label><input type="checkbox" name="fraud_role[]" value="Analyst" />Analyst</label>
    		   <label><input type="checkbox" name="fraud_role[]" value="Investigator" />Investigator</label>
    		   <label><input type="checkbox" name="fraud_role[]" value="Consultant" />Consultant</label>
    		   <label class="lblother"><input type="checkbox" name="fraud_role[]" value="Fraud Role-Other:" class="inpother" onchange="enableOtherBox(this,'role_other_name')" />Other</label><input type="text" name="role_other_name" id="role_other_name" disabled="disabled" class="fldother" />
    	</div>
    	
    		<div class="checkbox_list clearfix">
    			Fraud Responsibilities (check all that apply):<br />
    			   <label><input type="checkbox" name="fraud_responsibility[]" value="New Account Fraud" eform="Your fraud responsibilities::1" />Management</label>
    			   <label><input type="checkbox" name="fraud_responsibility[]" value="Account Takeover Fraud" />Analyst</label>
    			   <label><input type="checkbox" name="fraud_responsibility[]" value="ID Theft / Address Fraud" />Investigator</label>
    			   <label><input type="checkbox" name="fraud_responsibility[]" value="Internal Fraud" />Consultant</label>
    			   <label class="lblother"><input type="checkbox" name="fraud_responsibility[]" value="Responsibility-Other:" class="inpother" onchange="enableOtherBox(this,'resp_other_name')" />Other </label><input type="text" name="resp_other_name" id="resp_other_name" disabled="disabled" class="fldother" />
    		</div>
    		<br />
    	<p><input type="submit" name="Register" id="Register" class="button" value="Submit" /></p>
    </form>
    [+thefields+]
    



    Any help would be appreciated. I have had great luck with eForm up until now. It has had everything I need. Now I just need to figure out what to tell it do.

    Thanks
    Brian
      • 30223
      • 1,010 Posts
      Change this line:
      //<?php
      $fields['docsdropdown'] = $output;
      


      to:
      //<?php
      $templates['tpl'] = strr_replace( '[+docsdropdown+]', $output, $templates['tpl']);
      


      and validation shoudl magically start to work properly smiley
        • 2935
        • 15 Posts
        Thanks TobyL for your help.
        Hmmm? Changed that line, but it still doesn’t hold the checkbox states and I am now getting a validation error "requested_documents » Incorrect value". I also got this when I was trying to use a select box.

        Debug message:
        formid’ passed using rule: #VALUE RegistrationForm, (input=RegistrationForm)
        ’Selected docuements’ Failed using rule: #LIST JECM_The_Fraud_Management_Lifecycle.pdf ,ChipCardFraud_WP_FINAL.pdf ,InternetRetailer.CVN.pdf ,StoredValueCardsCCF.pdf ,WCCF_Using_the_FML_1of2.pdf ,WCCF_Using_the_FML_2of2.pdf ,FMLFinalWCCF_10-08F.pdf ,CCM0404_Securityrg.pdf, (input=InternetRetailer.CVN.pdf)
          • 2935
          • 15 Posts
          Ahhhhaaaaaahhhh! Whitespace was breaking the validation. I am parsing the list from a text file (will do this better later) there was a line break character after the value. My guess is that this was probably not looking like the right value to the eForm class so therefore it was breaking the validation AND the not keeping the checkbox states.

          Thanks TobyL for being so active on this forum and supporting your code.
            • 30223
            • 1,010 Posts
            Glad you worked it out and thanks,... no trouble at all smiley
              • 2935
              • 15 Posts
              Well fixed one thing but broke another. Yes I am still at it. Now the form above is not recognizing the conditional logic that presets checkboxes from the query string. I am stumped. Can anybody see a problem with my logic? It appears that eForm is un-checking the boxes when it parses the form.

              <?php
              function regDocsMenu(&$fields, &$templates)
              {
              	global $modx; // Access to DocumentParser
              		//set up some array variable 
              			$lines = array();
              			$doclist = array();
              			//check the URL for any query string vars for requested docs
              			if (isset($_GET['docid'])) {
              				$requested = $_GET['docid'];
              			} else {
              				$requested = 0;
              			}
              			//get the PDF document list from MODx text document
                                      $dittoOutput = $modx->runSnippet(
              				"Ditto",
              				array(
              					"parents" => "49",
              					"tpl" => "dittoDocListing",
              					"showInMenuOnly" => "0",
              					"display" => "all",
              					"depth" => "3",
              					"hideFolders" => "1",
              					"showPublishedOnly" => "1",
              					"hidePrivate" => "1"
              				)
              			);
              			//separate the lines of documents
              					$lines = explode("|~", $dittoOutput);
              					//loop through and grab file name and title
              					foreach ($lines as $line) {
              						if (!empty($line) || $line != "") {
              							$tempArr = explode("||", $line);
              							array_push($doclist, $tempArr);
              						}
              					}
              					echo $requested.",<br />";
              					
              					//start the list of boxes
              					$output = "<ul>";
              					//add each document title and filename as label checkboxes
              						foreach ($doclist as $item) {
              							$output .= "\t<li><label for=\"document".$item[0]."\"><input type=\"checkbox\" id=\"document".$item[0]."\" name=\"requested_documents[]\" value=\"".trim($item[2])."\"";
              
              							### This conditional statement is getting ignored
              							//check to see if it is a selected document
              							if( $item[0] == $requested ) {
              								$output .= " checked=\"checked\"";
              							}
              							
              							$output .= "/>".$item[0]."-".$item[1]."</label></li>\n";
              						}
              					$output .= "</ul>";
              	## This allows setting some checkboxes onload. But doesn't hold the states
              	//$fields['docsmenu'] = $output;
              	
              	## This doesn't allow checkboxes set onload, but does hold checkbox states
              	$templates['tpl'] = str_replace( '[+docsmenu+]', $output, $templates['tpl']);
              	return true;
              }
              ?>
              
                • 5340
                • 1,624 Posts
                id the html generated correctly?

                Try to put a space before checked
                $output .= "[space]checked=\"checked\"";
                  • 2935
                  • 15 Posts
                  Yes, I have checked the HTML for correctness. It was fine and the checked="checked" was not generated. I also put an echo statement in there to try and debug the problem. Nothing was outputed. I also tried casting the variables to integers, as in:
                  if( ((int) $item[0]) == ((int) $requested ) ) {
                  $output .= " checked=\"checked\"";
                  }
                  I also tried "===" just in case.

                  Yes, the space should be there. I took it out earlier in my effort to try and find ANY issue.
                    • 5340
                    • 1,624 Posts
                    try this

                    if( $item[0] == $requested ) {
                    $output .= " checked=\"checked\"";
                    $output .= ’ item="’.$item[0].’"’;
                    $output .= ’ requested="’.$requested.’"’;
                    }

                    what’s the the output? Might help in seeing the values of the variables in the IF statement
                      • 5340
                      • 1,624 Posts
                      Ignore the one above
                      It only shows you if the IF statement is entered and those values should be equal

                      Put this after the FOR statement

                      $output .= ’<div>’.$item[0].’<div>’;
                      $output .=’<div>’.$requested.’<div>’;

                      What are those values?