PLEASE NOTE: These forums are no longer utilized and are provided as an archive for informational purposes only. All support issues will be handled via email using our support ticket system. For more detailed information on this change, please see this blog post.

automatically populate a dropdown with post titles?

  1. How to automatically populate a dropdown with post titles form a certain category?

    I would like to achieve the following: a HR Manager posts a new vacant job in a certain category (let's say cat ID 16). For the applications we use a form that needs to be up to date and I don't want the HR Manager to touch the forms section in the website. So the drop down listing the open positions needs to be populated automatically.

    Could someone give me a quick example on how to go about?

    Posted 9 years ago on Friday January 8, 2010 | Permalink
  2. Jan Egbert
    Member

    I would be interested in this as well. I'm building a simple webshop in which every post is a product. The form to order the product has hidden fields prepopulated with the product title (post title) and price (custom field).

    I'd like to enable people to add one or two extra products to the form. A dropdown or multiple choice field with post titles would be a great solution.

    Posted 9 years ago on Friday January 8, 2010 | Permalink
  3. We will post a code snippet here soon. Need to put one together. But this is possible, it will require using a hook to dynamically populate the contents of the drop down.

    Posted 9 years ago on Friday January 8, 2010 | Permalink
  4. HI Carl, great! now I know it can be done I'd love to see a code snippet. Any clue on when you could put something together?

    Posted 9 years ago on Monday January 11, 2010 | Permalink
  5. So here is how this will have to be done. It's a little bit of a work around.

    What you will have to do is add a TEXT FIELD to your form and name it what you want the post title drop down to be. What we need to do is use PHP code to change the display of a TEXT FIELD into a drop down. So instead of adding a drop down to your form, add a text field. The information will be stored in this text field.

    Here is the code snippet that will transform this text field into a drop down that consists of post titles for a given category id...

    Note, you will need to change the FORM ID, the CATEGORY, and the FIELD ID in this code snippet.

    //Adds a filter to form id 14. Replace 14 with your actual form id
    add_filter("gform_pre_render_14", populate_dropdown);
    function populate_dropdown($form){
    
        //Reading posts for "Business" category;
        $posts = get_posts("category=Business");
    
        //Creating drop down item array.
        $items = array();
    
        //Adding initial blank value.
        $items[] = array("text" => "", "value" => "");
    
        //Adding post titles to the items array
        foreach($posts as $post)
            $items[] = array("value" => $post->post_title, "text" => $post->post_title);
    
        //Adding items to field id 8. Replace 8 with your actual field id. You can get the field id by looking at the input name in the markup.
        foreach($form["fields"] as &$field)
            if($field["id"] == 8){
                $field["type"] = "select";
                $field["choices"] = $items;
            }
    
        return $form;
    }

    The form id you need to change is the 14 in this piece of the code snippet above:

    add_filter("gform_pre_render_14", populate_dropdown);

    The category you need to change is the name in this piece of the code snippet above:

    $posts = get_posts("category=Business");

    The field id you need to change is the id in this piece of the code snippet above:

    if($field["id"] == 8){

    You can get the field id by viewing source on the form front end, finding the field we are targeting and getting the id.

    Posted 9 years ago on Tuesday January 12, 2010 | Permalink
  6. Cool, this works.. Thanks Carl!

    Posted 9 years ago on Tuesday January 12, 2010 | Permalink
  7. One more question, when I look at the result the first select item is empty, would it be possible to add a default value? or possibly to add a select item like "other.."

    Posted 9 years ago on Tuesday January 12, 2010 | Permalink
  8. I will have to check, see if there is anything we can do to the code snippet to alter it so that you can set a default value. I'll get back with you.

    Posted 9 years ago on Tuesday January 12, 2010 | Permalink
  9. Hi Carl, any news on this one?

    Posted 9 years ago on Friday January 15, 2010 | Permalink
  10. Try the following.

    //Adds a filter to form id 18. Replace 14 with your actual form id
    add_filter("gform_pre_render_18", populate_dropdown);
    function populate_dropdown($form){
    
        //Reading posts for "Business" category;
        $posts = get_posts("category=Business");
    
        //Creating drop down item array.
        $items = array();
    
        //Adding initial blank value.
        //$items[] = array("text" => "", "value" => "");
    
        //Adding post titles to the items array
        foreach($posts as $post){
            $is_selected = $post->post_title == "testing" ? true : false;
            $items[] = array("value" => $post->post_title, "text" => $post->post_title, "isSelected"=> $is_selected);
        }
    
        //Adding other... item
        $items[] = array("text" => "Other...", "value" => "other");
    
        //Adding items to field id 8. Replace 8 with your actual field id. You can get the field id by looking at the input name in the markup.
        foreach($form["fields"] as &$field)
            if($field["id"] == 7){
                $field["type"] = "select";
                $field["choices"] = $items;
            }
    
        return $form;
    }

    You will need to replace "testing" on line 17 with the post title you would like selected by default.
    Also, I have removed the first empty item. You can add it again by un-commenting line 13 (i.e. removing the //)

    Posted 9 years ago on Friday January 15, 2010 | Permalink
  11. Hello,

    Can I ask, is it possible to use this code with custom fields? Say, I wanted to populate it with the UK counties that I have listed in my custom field called 'county' ?

    Thanks!
    Steph

    Posted 9 years ago on Saturday January 16, 2010 | Permalink
  12. This code could be used to populate a variety of fields. But to accomplish what you want it may require tweaking the code some. This is certainly more advanced usage of the hooks that are available so PHP knowledge is pretty important.

    Posted 9 years ago on Sunday January 17, 2010 | Permalink
  13. Cool! works like a charm
    thanks guys

    Posted 9 years ago on Monday January 18, 2010 | Permalink
  14. fuhrmara
    Member

    I used the code from the example.
    But it seems that the "isSelected" Setting isn't used from gravityForms.

    Posted 9 years ago on Sunday January 24, 2010 | Permalink
  15. Responded to your other post fuhrmara. What you are trying to do is different from what the subject of this post was.

    Posted 9 years ago on Monday January 25, 2010 | Permalink
  16. Jan Egbert
    Member

    Thanks for this great code snippet. It got me thinking about adding a dropdown with get_the_terms(). Here is how I edited Alex's code in order to get a dropdown of shoesizes (custom taxonomy) for the current post id (I embed the same order form in every product post, but shoesizes vary):

    //Adds a filter to form id 7. Replace 7 with your actual form id
    add_filter( 'gform_pre_render_7', 'populate_dropdown' );
    function populate_dropdown($form){
    
        //Reading terms for current post;
        global $post;
        $terms = get_the_terms($post->ID, 'size');
    
        //Creating drop down item array.
        $items = array();
    
        //Adding initial blank value.
        $items[] = array("text" => "", "value" => "");
    
        //Adding term names to the items array
        foreach($terms as $term){
            $is_selected = $term->name == "testing" ? true : false;
            $items[] = array("value" => $term->name, "text" => $term->name, "isSelected"=> $is_selected);
        }
    
        //Adding items to field id 1. Replace 1 with your actual field id. You can get the field id by looking at the input name in the markup.
        foreach($form["fields"] as &$field)
            if($field["id"] == 1){
                $field["type"] = "select";
                $field["choices"] = $items;
            }
    
        return $form;
    }

    Replace size in get_the_terms($post->ID, 'size'); with whatever taxonomy you want your dropdown to be pre-populated.

    Posted 9 years ago on Thursday February 4, 2010 | Permalink
  17. Good stuff Jan! If you have any interest in writing up a tutorial on this, we'd be glad to either post it here or link to it on your site.

    Posted 9 years ago on Thursday February 4, 2010 | Permalink
  18. Jan Egbert
    Member

    I'd be honored to write a tutorial about this. It might be interesting to cover the whole proces of building a simple WordPress shoe store using Gravity Forms, custom post types and custom taxonomies.

    Posted 9 years ago on Thursday February 4, 2010 | Permalink
  19. I modified Jan's code a bit so that the dropdown will be populated with all the terms associated with a defined taxonomy rather than the current post.

    //Adds a filter to form id 1. Replace 1 with your actual form id
    add_filter( 'gform_pre_render_1', 'populate_dropdown' );
    function populate_dropdown($form){
    
        //Grab all Terms Associated with a Specific Taxonomy;
        global $post;
        $terms = get_terms('YOUR_TAXONOMY_SLUG', 'hide_empty=0&orderby=none');
    
        //Creating drop down item array.
        $items = array();
    
        //Adding initial blank value.
        $items[] = array("text" => "", "value" => "");
    
        //Adding term names to the items array
        foreach($terms as $term){
            $is_selected = $term->name == "testing" ? true : false;
            $items[] = array("value" => $term->name, "text" => $term->name, "isSelected"=> $is_selected);
        }
    
        //Adding items to field id 1. Replace 1 with your actual field id. You can get the field id by looking at the input name in the markup.
        foreach($form["fields"] as &$field)
            if($field["id"] == 5){
                $field["type"] = "select";
                $field["choices"] = $items;
            }
    
        return $form;
    }
    Posted 9 years ago on Wednesday June 16, 2010 | Permalink
  20. I'm quite new to Gravity Forms so I have a very basic question...where do I put the above code snippet(s)? This post contains exactly what I am trying to do, myself.

    I don't see any area in Gravity Forms to create a 'text field' in the admin panel. I see Single Line Text and Paragraph text, but there's no clear area to paste this code.

    I've looked everywhere and found no documentation on how to use the more advanced functions of GF, such as dynamic field population and the above desired effect. Thanks in advance, guys!

    Posted 9 years ago on Monday July 5, 2010 | Permalink
  21. Well, nevermind. Sometimes I think just finally getting fed up enough to post the question makes the universe answer me somehow. I added the above to functions.php and viola...very nice indeed. I can see how useful this is now. Thanks for the above code guys, fantastic work.

    Edit -

    Although, while I am here...does anybody know how to modify the above code to query a list of posts in a custom post type that I created in Wordpress 3 called "workshops"?

    Posted 9 years ago on Monday July 5, 2010 | Permalink
  22. @Illuminated, place the code snippet in your functions.php and adjust the form ID, the 'text field' is the paragraph text in the GF backend

    Posted 9 years ago on Monday July 5, 2010 | Permalink
  23. Yup, I got that and I actually figured out how to pull from 'workshops' post type.

    Now my only other question is how to I get it to pull from meta data in my custom fields?

    I know I need to change this section:

    //Adding post titles to the items array
        foreach($posts as $post)
            $items[] = array("value" => $post->post_title, "text" => $post->post_title);

    I tried this but it didn't work:

    foreach($posts as $post)
            $items[] = array("value" => $post->get_post_meta($post->ID, 'Dates'), "text" => $post->$post->get_post_meta($post->ID, 'Dates'));

    Any ideas? I'm still very much a PHP newbie, but learning fast! :)

    Posted 9 years ago on Monday July 5, 2010 | Permalink
  24. Also tried this, no luck...

    //Adds a filter to form id 14. Replace 14 with your actual form id
    add_filter("gform_pre_render_1", populate_dropdown);
    function populate_dropdown($form){
    
        //Reading posts for "Business" category;
    	global $post;
            $posts = get_posts("post_type=calendar&showposts=99&orderby=title&order=ASC");
    	$date = get_post_meta($post->ID, 'Dates', false);
    
        //Creating drop down item array.
        $items = array();
    
        //Adding post titles to the items array
        foreach($posts as $post)
            $items[] = array("value" => $post->date, "text" => $post->date);
    
        //Adding items to field id 8. Replace 8 with your actual field id. You can get the field id by looking at the input name in the markup.
        foreach($form["fields"] as &$field)
            if($field["id"] == 27){
                $field["type"] = "checkbox";
                $field["choices"] = $items;
            }
    
        return $form;
    }

    And when I think about it, I'm also looking to have it return two fields: the post title and the custom field of 'date'. Hopefully someone here has done something like this! :)

    Posted 9 years ago on Monday July 5, 2010 | Permalink
  25. This code works fine for select fields (drop downs). But, it does not work for multiple choice or radio button fields.

    foreach($form["fields"] as &$field)
            if($field["id"] == 7){
                $field["type"] = "select";
                $field["choices"] = $items;
            }

    I can set it to a radio type:

    $field["type"] = "radio";

    But, the values for the various options are always set to the "text" value.

    Full example:

    $gender_values = array();
    $gender_values[] = array("text" => "Not Specified", "value" => "N", "isSelected" => true);
    $gender_values[] = array("text" => "Male", "value" => "M");
    $gender_values[] = array("text" => "Female", "value" => "F");
    
        foreach($form["fields"] as &$field) {
    
        if($field["id"] == 16){
                $field["type"] = "radio";
                $field["choices"] = $gender_values;
            }
    
        }

    It changed the field to a multiple choice/radio type. And the text for each option is correct. But the values are not.

    <ul class='gfield_radio' id='input_17_16'>
    <li class='gchoice_16_0'>
    <input name='input_16' type='radio' value='Not Specified' checked='checked' id='choice_16_0' tabindex='19' />
    <label for='choice_16_0'>
    Not Specified
    </label>
    </li>
    <li class='gchoice_16_1'>
    <input name='input_16' type='radio' value='Male' id='choice_16_1' tabindex='20' />
    <label for='choice_16_1'>
    Male
    </label>
    </li>
    <li class='gchoice_16_2'>
    <input name='input_16' type='radio' value='Female' id='choice_16_2' tabindex='21' />
    <label for='choice_16_2'>
    Female
    </label>
    </li>
    </ul>

    I am probably missing something obvious. Any ideas?

    I appreciate the help.

    Posted 9 years ago on Thursday July 8, 2010 | Permalink
  26. any ideas on this? Thanks.

    Posted 9 years ago on Tuesday July 13, 2010 | Permalink
  27. I'm looking for a variation on this, but seem to have a hard time with the code for functions.php. We use Gravity Forms for news submission ('Tip the Editor'), but some people keep sending in stuff we've already written about. Is there a way to display the latest X news items in Gravity Forms? I've tried the new HTML block with some PHP test code, but unfortunately the html block doesn't take PHP.
    The examples here are all for dropdowns and I just need an unordered list of e.g. 15 latest posts:
    get_posts('numberposts=15')
    Any help would be greatly appreciated.

    I actually would love to have a PHP block as extra to the HTM block. Then I could show our latest X custom news tweets as well.

    Posted 9 years ago on Sunday July 25, 2010 | Permalink
  28. Hi Jean Paul,

    You can update the contents of any Gravity Form field using the gform_pre_render filter. Here is some code that accomplishes what you are after (http://pastie.org/1059179) and here is a sample of what it will generally look like once implemented (http://grab.by/5zNw)

    Quick Breakdown:

    add_filter('gform_pre_render_7', 'customize_html_blocks');

    Here is where we assign the customize_html_blocks function to be run by the gform_pre_render filter. The number at the end is the ID of the form I used to test this code. You should change this to the form id you wish to implement this code for.

    $posts = get_posts('numberposts=5');
        foreach($posts as $post) {
            $content .= '<li><a href="' . get_permalink($post->ID) . '" target="_blank">' . $post->post_title . '</a></li>';
        }
    $content = '<h3>Latest News</h3><ul>' . $content . '</ul>';

    Next we get the posts we want to display and then loop through each returned post getting the post title and any other information we want to display about the post. You'll notice that I also wrapped my post title with a link to the post and a list item so everything will look nice and orderly when we display this on the front-end. The last line gives the whole section a title (Latest News) and wraps all of our post title list items in an unordered list.

    $form['fields']['0']['content'] = $content;
        return $form;

    This last bit updates the form object that is originally passed to this filter function with the content we just created. You'll need to figure out which field you're updating by viewing the source and looking at the field id. In my case it was "0". Then all there is left to do is return the updated form object. And done! :)

    Posted 9 years ago on Sunday July 25, 2010 | Permalink
  29. Wow, thank you so much. Not only for the code snippet, but for the excellent breakdown as well. This is a great help, so thank you for your time and effort.

    Posted 9 years ago on Sunday July 25, 2010 | Permalink
  30. My pleasure. Let me know if this works for you. :)

    Posted 9 years ago on Sunday July 25, 2010 | Permalink
  31. Actually it doesn't, but I'm probably overlooking something. As from previous posts in this discussion I understand I need to add a text field (Paragraph Text) (also tried with HTML block) and look up the field ID in the source code, which is 41:
    <li id='field_1_41' class='gfield' style='display:none;'><label class='gfield_label' for='input_1_41'>Untitled</label><div class='ginput_container'><textarea name='input_41' id='input_1_41' class='textarea medium' tabindex='4' rows='10' cols='50'></textarea></div></li>

    Does the Paragraph Text block need any additional settings, like a special label or a checkbox in Advanced?

    Current code in function.php is this:

    /*
    Gravity Forms - Custom Hooks
    */
    // Customize HTML Blocks
    add_filter('gform_pre_render_1', 'customize_html_blocks');
    function customize_html_blocks($form) {
    
        $posts = get_posts('numberposts=5');
        foreach($posts as $post) {
            $content .= '<li><a href="' . get_permalink($post->ID) . '" target="_blank">' . $post->post_title . '</a></li>';
        }
        $content = '<h3>Latest News</h3><ul>' . $content . '</ul>';
    
        $content = 'Test';
        $form['fields']['41']['content'] = $content;
        return $form;
    }

    I've setup an example page where this form (ID:1) is live. Please choose 'Nieuwstips' in the first dropdown to show the field where the post list should be.

    Thanks for you additional help!

    Posted 9 years ago on Sunday July 25, 2010 | Permalink
  32. Hey Jean, the example I provided assumes you are using an HTML block field. Sorry, I probably should have specified that. I think that'll do the trick for you. Let me know.

    Posted 9 years ago on Monday July 26, 2010 | Permalink
  33. OK. I originally had that and have once again added an HTML block (and removed the paragraph text). It's still not populating the block with the code in functions.php (it should output 'Test'), but the html block is just empty.
    <li id="field_1_42" class="gfield gfield_html gfield_html_formatted gfield_no_follows_desc" style="display: list-item; "></li>
    functions.php

    /*
    Gravity Forms - Custom Hooks
    */
    // Customize HTML Blocks
    add_filter('gform_pre_render_1', 'customize_html_blocks');
    function customize_html_blocks($form) {
    
        $posts = get_posts('numberposts=5');
        foreach($posts as $post) {
            $content .= '<li><a href="' . get_permalink($post->ID) . '" target="_blank">' . $post->post_title . '</a></li>';
        }
        $content = '<h3>Latest News</h3><ul>' . $content . '</ul>';
    
        $content = 'Test';
        $form['fields']['42']['content'] = $content;
        return $form;
    }

    Does the HTML block need any additional settings, like a special label or a checkbox in Advanced?

    Example page: http://www.ipadplanet.nl/gf-test/

    Again, thank you for your help and sorry for the trouble. Would really like to get this going and it's probably a small oversight.

    Posted 9 years ago on Monday July 26, 2010 | Permalink
  34. If you don't mind, could I get FTP access to this WP install? I would probably have better luck troubleshooting this if I can see the backend. You can email me at david@ounceoftalent.com.

    Posted 9 years ago on Monday July 26, 2010 | Permalink
  35. Sent :)

    Posted 9 years ago on Monday July 26, 2010 | Permalink
  36. Alright, fixed. Here is the update snippet: http://pastie.org/1060312

    The issue was a bad assumption on my part.

    $form['fields']['0']['content'] = $content;

    This line assumes that the index of the field in the form object is the same as the field id. This is not a good assumption to make; specifically in cases where forms have been updated several times. I've replaced that line with this:

    for($i = 0; $i < count($form['fields']); $i++) {
        	if($form['fields'][$i]['id'] == 42) {
        		$form['fields'][$i]['content'] = $content;
        	}
    }

    What we are doing instead is looping through each field in the form object and checking if the field id of that field is the field id we are looking for (in this case "42"). If so, THEN we replace the old content with our updated content.

    I've implemented this on your server. Let me know if you run into any issues. :)

    Posted 9 years ago on Monday July 26, 2010 | Permalink
  37. David, you're my hero! Your domain should be tonsoftalent.com instead of ounceoftalent.com :D Can't thank you enough for your time and help.

    Posted 9 years ago on Monday July 26, 2010 | Permalink
  38. mourgroup
    Member

    Hi!

    Is it possible to pre select a value in the dropdown based on what page the user comes from?

    Posted 8 years ago on Thursday November 11, 2010 | Permalink
  39. What you can do is configure your drop down to "Allow field to be populated dynamically" and give it a parameter name (i.e. my_field).
    You can then add "?my_field=dropdown_value" to the link that is targeting the page hosting your form.
    If changing the link is not an option, you will have to use a hook.

    Posted 8 years ago on Thursday November 11, 2010 | Permalink
  40. mourgroup
    Member

    Hi!

    I tried that but its not working when im using the code that Carl Hancock wrote on the top

    //Adds a filter to form id 14. Replace 14 with your actual form id
    add_filter("gform_pre_render_14", populate_dropdown);
    function populate_dropdown($form){
    
        //Reading posts for "Business" category;
        $posts = get_posts("category=Business");
    
        //Creating drop down item array.
        $items = array();
    
        //Adding initial blank value.
        $items[] = array("text" => "", "value" => "");
    
        //Adding post titles to the items array
        foreach($posts as $post)
            $items[] = array("value" => $post->post_title, "text" => $post->post_title);
    
        //Adding items to field id 8. Replace 8 with your actual field id. You can get the field id by looking at the input name in the markup.
        foreach($form["fields"] as &$field)
            if($field["id"] == 8){
                $field["type"] = "select";
                $field["choices"] = $items;
            }
    
        return $form;
    }
    Posted 8 years ago on Thursday November 11, 2010 | Permalink
  41. Can you send me a link to the page that has the link to the form?

    Posted 8 years ago on Thursday November 11, 2010 | Permalink
  42. Carramba
    Member

    is it possible to make two dynamically linked dropboxes?

    When I choose FORD, I see Explorer, Excursion in 2nd dropdown, OR
    when I choose Chevrolet, I see corresponding chevy models...

    Posted 8 years ago on Sunday December 12, 2010 | Permalink
  43. @Carramba This is only possible using conditional logic. Which means each variation would require you to add a drop down and manually add the values to the drop down and then use conditional logic to show/hide that drop down.

    Posted 8 years ago on Monday December 13, 2010 | Permalink

This topic has been resolved and has been closed to new replies.