Announcement Announcement Module
Collapse
No announcement yet.
Dynamic population of form fields upon combo selection SPRING MVC Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Dynamic population of form fields upon combo selection SPRING MVC

    have a Drop down list and a Listbox. What I want to do is to populate data to the listBox when an option is selected from the Drop Down list.

    Could you tell me how can I achieve this in a simple manner?

    The problems that I had

    Couldn't save nested objects in a spring:form
    Couldn't update the listbox items when dropdown onchange event fired
    Hard to know where to store a static array in an HTML web page
    Had to redirect to the server and there I had lots of problems it so tires me when I have to do round trip for a small thing
    Your helps will be much appreciated Cheers

  • #2
    Use ajax

    This is quite simple. Use the Ajax lib of your choice. Try jQuery if you don't have one already.

    Comment


    • #3
      Using jQuery it would be very simple. For example if your dropdown list id is 'products' then you can write a jQuery as:

      Code:
      $(document).ready(function() {
       	$('#products').click(function() {
                     //make a call to service which returns the list.
      	});
      });
      For an example on how to integrate Spring + JSON + jQuery you can find many examples here is one...
      http://springdiaries.blogspot.com/20...ng-mvc-3x.html

      Comment


      • #4
        Thank you guys, never tried JQuery before so I didn't know I could do populating with JQuery.
        I will check it out.


        Cheers!!!

        Comment


        • #5
          Actually, here is an article that offers a fully working Maven project.
          It uses jQuery and Spring MVC 3 to populate two selects: states and cities.
          The states is populated at load time and the cities is populated when you select a state.
          It has unit and integration tests via jetty and Selenium 2.

          Comment


          • #6
            The example in the website is pretty new, uses spring mvc 3. It is hard to find examples like this one. Thanks for sharing the website, it will be very useful for me.

            Cheers...

            Comment


            • #7
              Hi,

              Json works fine here, and I can fetch data no problem.
              Altering dropdown lists (selects or options in selects) does not, I dont seem to be able to update the results.

              Im using spring MVC with Roo generated code and I just added some javascript to handle changing the contents of the dropdown list.

              Any ideas ?

              Regards,
              Emil

              Comment


              • #8
                Is there any reason that the aforementioned article and complete example doesn't work for you?

                Comment


                • #9
                  Well it uses different tags than what I have in spring MVC.

                  Ive tried at least 5 different jquery and dojo/dijit examples and most of them end with

                  $('#usStates').html(html);
                  or
                  setting innerHTML of the destination object, but when I try that it simply doesnt work, no error I just dont get the results.

                  I tried modifying the options list of the current select item and that didnt work.

                  Do you know an example of this that works with Roo generated controllers ? that is Spring MVC ? if so please send me a link

                  Regards,
                  Emil

                  p.s. I will try futher to integrate this example into my Spring MVC code/controllers and see if I can get it to work

                  Comment


                  • #10
                    Originally posted by emil2010 View Post
                    Well it uses different tags than what I have in spring MVC.
                    So you're not using HTML tags nor Spring MVC's core and form tags? That's what the example uses along with jQuery. And it's all explained in the article.

                    We're not mind readers so if you want further help you need to post your broken code.

                    Comment


                    • #11
                      Sorry about the mindreading

                      Here is my javascript code


                      Code:
                      			dojo.addOnLoad(
                      				function(){
                      				dojo.require("dijit.form.Select");
                      					var id = 3;
                      					var node = dijit.byId('_projectType_id');
                      					var dNode = dojo.byId('_years_id');
                      					dojo.connect(node, 'onChange', function(){
                      						dojo.xhrGet({ url: '../../TDF/projectdurations/lookup/' + id,
                      						handleAs: "json",
                      						preventCache: true,
                      						load: function(data) {
                      							var html = '<option value="">State</option>';
                      							var len = data.length;
                      							for ( var i = 0; i < len; i++) {
                      								html += '<option value="' + data[i].name + '">'
                      									+ data[i].description + '</option>';
                      							}
                      							html += '</option>';
                                              //now that we have our options, give them to our select
                      						dojo.byId('mydiv').html(html);
                      							},
                      							error: function(error) {
                      							dNode.innerHTML = "AJAX error: " + error;
                      							}
                      						});
                                  }
                              );
                      					});

                      To explain, I have two dropdown lists generated by Roo or to explain in code :
                      Code:
                              <field:select field="projectType" id="c_is_rannis_sjodir_tdf_domain_TypeAndDuration_projectType" itemValue="id" items="${projecttypes}" path="/projecttypes" z="aX32lFhmcIYB81RjsH/7HBr1DLs="/>
                      
                              <field:select field="years" id="c_is_rannis_sjodir_tdf_domain_TypeAndDuration_years" itemValue="id" items="${projectdurations}" path="/projectdurations" required="true" z="0LwlWg69oxlubxwcXvA8qsHbeBU="/>
                      Basicly how this works is, you select a project type and some projects have 1 some have 2 and some have 3 years to select from, so when you select a project type that has one year only as the duration, the duration dropdownlist should only have that one item, not one year , two years three years.

                      The project Type select gives 6 types of projects to select from
                      Project duration (or years) basicly gives one year, two years three years.

                      I have created a function in a controller which returns a json response (this works I tested it by just callin the function and it returns a json response). I basicly just pass the id of projecttype to this function and it returns the correct number of year objects as json.

                      Code:
                      	@RequestMapping(value = "/lookup/{numberofyears}", method = RequestMethod.GET)
                          public @ResponseBody List<ProjectDuration> findProjectDurations(@PathVariable("numberofyears") String years, HttpServletResponse response, HttpSession p_session) {
                      		try
                      		{
                      			List<ProjectDuration> tf = ProjectDuration.findProjectDurationsNumberLessAndEquals(years).getResultList();
                      			
                      	        return tf;
                      		}
                      		catch(Exception ex)
                      		{
                      			
                      		}
                      		return (List<ProjectDuration>) null;
                          }
                      So basicly, I tried every variation of the
                      dojo.byId('mydiv').html(html); I can think of, like making an empty div to receive the new html etc.

                      Help would be greatly appreciated.

                      Regards,
                      Emil

                      Comment

                      Working...
                      X