We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 30223
    • 1,010 Posts
    This example is in reply to a question in this topic. and I’ve kept the solution rather simple. There’s not a lot of error checking for instance. I’m not trying to solve the problem but rather to give anyone wanting to dynamically build a select field using TV’s with eForm something to start from.

    The goal:
    Creating a form where visitors can select a meeting from a list of dates.
    Meeting dates can be entered by the site admin or editor.

    The solution:
    1. Create a TV and name it tv_dates. Set the input type to textarea (mini) and set the description to "Add one date per line". Leave the rest of the fields blank and assign the TV to the same template the page your form is using.


    2. Create the form and report template.
    form template: (named sampleForm here)
    [+validationmessage+]
    <form action="[~[*id*]~]" id="test1" method="post">
    <p><label for="fld_name">Name</label><br />
    <input type="text" id="fld_name" name="name" eform=":text:1:Please fill in your full name" /></p>
    <p><label for="fld_options">TV Options</label><br />
    <select id="fld_options" name="tv_options" eForm="::1:You need to select something:">
    [+display_tv_options+]
    </select></p>
    <p><input type="submit" value="send" /></p>
    </form>
    

    Note the [+display_tv_options+] place holder. This will be replaced with the values from the TV.

    The report: (named sampleReport here)
    <p>Here's the results of your form:</P
    
    <p>Name: [+name+]</p>
    <p>Your options:[+tv_options+]</p>
    



    3 Create a snippet with the function we are going to use in the eFormOnBeforeFormParse event. (I’ve named the snippet getTvDates)

    <?php
    if( !function_exists('eformGetTvDates') ) {
    	function eformGetTvDates(&$fields,&$templates){
    		global $modx;
    		$rawvalue = $modx->getTemplateVarOutput('tv_dates');
    		if(!$rawvalue['tv_dates']){ //no data, don't display a form at all
    			$templates['tpl']="<p>There are no meetings scheduled</p>";
    		}
    		$dates = explode("\n",$rawvalue['tv_dates']);
    
    		foreach( $dates as $dateString ){
    			$dateString = trim($dateString);
    			if($dateString) $options .= "<option value=\"$dateString\">$dateString</option>\n";
    		}
    		$templates['tpl']=str_replace('[+display_tv_options+]',$options,$templates['tpl']);
    		return true;
    	}
    }
    
    return '';
    ?>
    



    4. Create the form page and add both snippets.

    [[getTvDates]]
    [!eForm? &formid=`sampleForm` &tpl=`sampleForm` &report=`sampleReport` &noemail=`1` &eFormOnBeforeFormParse=`eformGetTvDates`!]
    



    5.
    Add some values in the TV. As I said before there’s not much error checking so potentially you could fill in anything, date or not.
    21 February 2008
    12 April 2008
    1 January 2009
    



    The function in 3. will get the template variable output if there is one and split each value on a line ending. Empty lines will be discarded. Each value is added as an option field and the result is used to fill in the [+display_tv_options+] placeholder in the form template. If no TV values are found (and thus no meeting dates) the form template is replaced completely with a simple message.

    This is pretty limited example and you should not just copy and paste it for a live site. Think about what you require and adapt this to your needs!
    • Would it not be better to have the <select>...</select> tags in the snippet? If there are no meetings, your <p>message</p> will still be enclosed in the <select> tags in your template.
        Studying MODX in the desert - http://sottwell.com
        Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
        Join the Slack Community - http://modx.org
        • 30223
        • 1,010 Posts
        The whole template is replaced in this case so there is no form at all if no TV is set but just a message.

        You are right of course in scenarios where there would be a form either way. I just choose to not display a form at all as in this case that wouldn’t make much sense anyway.
          • 5529
          • 70 Posts
          Okay, this was very, very helpful! Thank you for documenting this as I think there are many people who use tv’s for form values (and everything else in MODx since it is one of the central features of the CMS).

          A couple notes. First, in the foreach part of the function you set $datestring and then right below call $dateString (that one took me quite a while to find because i was getting an empty select list which wasn’t supposed to happen under any circumstances). Secondly, if you don’t trim whitespace from $datestring it will throw a validation error. So $datestring = trim($datestring) right above the line that creates the options means the difference between the form submitting and the eForm marking the select list as invalid.

          Otherwise, I couldn’t have done this without you. I now have a form that grabs SESSION variables created by WebloginPE like fullname and email, puts it in eForm in text inputs that I hide using CSS (not hidden inputs) and creates a dynamic list of meeting dates to select and then emails the admin the results. Awesome! Thanks!
            • 30223
            • 1,010 Posts
            A couple notes. First, in the foreach part of the function you set $datestring and then right below call $dateString (that one took me quite a while to find because i was getting an empty select list which wasn't supposed to happen under any circumstances). Secondly, if you don't trim whitespace from $datestring it will throw a validation error.  So $datestring = trim($datestring) right above the line that creates the options means the difference between the form submitting and the eForm marking the select list as invalid. 


            Corrections made in original post smiley
              • 7231
              • 4,205 Posts
              This is a great example. I was able to do exactly what I wanted, with a little effort to understand the bit about the template replacement but once I understood it it was like "wow, that is a great idea". Thanks for posting this.
                [font=Verdana]Shane Sponagle | [wiki] Snippet Call Anatomy | MODx Developer Blog | [nettuts] Working With a Content Management Framework: MODx

                Something is happening here, but you don&#39;t know what it is.
                Do you, Mr. Jones? - [bob dylan]
                • 21700
                • 42 Posts
                Hi all, I created something to use ScottyDelicious’ UserPlaceholders in an eForm template.

                And, if you wish, you could also hide certain fields for logged in users (e.g. all webusers must have an emailaddress, so why bother asking again?), by setting hide="true" on elements. The script will automatically throw in style="display: none;" so users simply won’t see the information. If a user isnt logged in, the placeholder will be removed from the form (except for logged in since and last login.)

                Requirements:
                Userplaceholders
                eForm
                this snippet.

                Call:
                userplaceholder
                this snippet
                eForm.

                <?php
                /***
                user info for eform by noes
                v1.0
                
                based on example by TobyL (see http://modxcms.com/forums/index.php/topic,22072.0.html)
                and on UserPlaceholders by Scotty Delicious
                
                this snippet basically allows you to populate eform fields with placeholders from UserPlaceholders by Scotty Delicious. Make sure to have UserPlaceholders installed already, and call it before the eform snippet.
                
                install: copy paste this code in a new snippet, name it eFormPopulate or whatever you like.
                
                usage: 
                1st: call userplaceholder snippet
                2nd: call this snippet
                3rd: call eform with &eFormOnBeforeFormParse=`eformpopulate` in snippetcall
                
                now you can use UserPlaceholders in your eForm forms!
                */
                
                if  (!function_exists('eformpopulate')){
                	function eformpopulate(&$fields,&$templates){
                		/*adjusting dateFormat will allow you to use your own date/time makeup. using php date function. defaults to whatever is set at UserPlaceholders snippet.*/
                		$dateFormat = isset($dateFormat) ? $dateFormat : '%A %B %d, %Y at %I:%M %p';
                
                		global $modx;
                		if(isset($_SESSION['webShortname'])){
                			$hide=true; //user is logged in, some fields can now be hidden. 
                		} else { 
                			$hide=false;
                		}
                
                		//hide all <tr hide="true"> using CSS display none if user is logged in.
                		if($hide==true){
                			$templates['tpl']=str_replace('hide="true"','style="display: none;"',$templates['tpl']);
                			$templates['tpl']=str_replace('hide="false"','',$templates['tpl']);
                		} else { //prevent ( X ) HTML errors, html property hide is nonexistent according to w3c stds 
                			$templates['tpl']=str_replace('hide="true"','',$templates['tpl']);
                			$templates['tpl']=str_replace('hide="false"','',$templates['tpl']);
                		}
                
                		$user_info_for_eform = $modx->getWebUserInfo($modx->getLoginUserID());
                		$templates['tpl']=str_replace('[+user.username+]',stripslashes($user_info_for_eform['username']),$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.fullname+]',stripslashes($user_info_for_eform['fullname']),$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.internalkey+]',$user_info_for_eform['internalKey'],$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.email+]',$user_info_for_eform['email'],$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.phone+]',$user_info_for_eform['phone'],$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.mobilephone+]',$user_info_for_eform['mobilephone'],$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.dob+]',strftime('%m-%d-%G',$user_info_for_eform['dob']),$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.gender.integer+]',$user_info_for_eform['gender'],$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.gender+]',stringForGenderInt($user_info_for_eform['gender']),$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.country.integer+]',$user_info_for_eform['country'],$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.country+]',stringForCountryInt($user_info_for_eform['country']),$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.state+]',$user_info_for_eform['state'],$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.zip+]',$user_info_for_eform['zip'],$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.fax+]',$user_info_for_eform['fax'],$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.photo+]',$user_info_for_eform['photo'],$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.comment+]',stripslashes($user_info_for_eform['comment']),$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.logincount+]',$user_info_for_eform['logincount'],$templates['tpl']);
                		
                		$templates['tpl']=str_replace('[+user.lastlogin+]',strftime($dateFormat, $user_info_for_eform['lastlogin']),$templates['tpl']);
                		$templates['tpl']=str_replace('[+user.thislogin+]',strftime($dateFormat, $user_info_for_eform['thislogin']),$templates['tpl']);
                
                		return true;
                	}
                }
                ?>


                Just use as stated in the example, but without TV. With the HTML pseudo element hide="true" or hide="false" you can select what elements to hide or show. The snippet hides using CSS (style="display: none;").

                Any comments are welcome!
                • How does this work if the email field is required, but the field is hidden?
                    Studying MODX in the desert - http://sottwell.com
                    Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
                    Join the Slack Community - http://modx.org
                    • 21700
                    • 42 Posts
                    It populates the field when you are logged in and keeps it hidden. If you aren’t logged in, it will show the field so you can enter it. When all webusers are required to enter an emailadres in the signup procedure, all webusers will have an emailaddress to populate the field with. I’ll edit the snippet to enable you to change the eform="" parameter as well, depending on logged in or not. If a user is logged in, no errorhandling is possible for hidden fields, but I can’t really figure out why it isn’t possible.

                    For all not-logged in users, all fields will be visible, so everyone can enter one. On the site I’m working on, once you are logged in, you get to see your details in a pane on the right. This contains two links, one to update profile and on to change the password. I believe this is sufficient to check your details.
                      • 16501
                      • 28 Posts
                      huh

                      Hi Sorry if this is a stupid question, but when trying to implement this example I get the following error after submitting the form...

                      Fatal error: Call to undefined function eformGetTvDates() ...


                      Where have I gone wrong?