Pergunta

I have a select field to choose the department. I want to implement a view that displays the list of employees working in that department. I want to display both the select field and list of employees in the same page(view). How is it possible to send the selected field parameter to the same controller and update the list of employees object and display the list in the same page.

Foi útil?

Solução

There are three main parts to a partial page update. I will give you a general overview of how each part is composed with some examples. This should get you started on the right path. I'm having to make lots of assumptions since your question is light on details. However you should be able to take this information and write your won implementation.

Part 1 (Making the request)

This involves monitoring the select list for a change and sending the value of the selected option to the controller. JQuery is well suited for this. I am going to pretend that the select list has an id of "departmentId" and we want to put the contents of the employee list into an element with the id of "displayList".

<script type='text/javascript'>
<!--
  (function() {
    $("#departmentId").on("change", function() {
      $.get("${g.createLink(controller: 'employeee', action: 'listForDepartment')}/"+$(this).val(), function(data) {
        $("#displayList").html(data);
      });
    });
  })();
// -->
</script>

Part 2 (Fulfilling the request)

The second part is our controller code for getting the list of employees. This is just an example of what it might look like. Notice that we are going to render a template instead of a view. This is very important because we don't want Grails (Sitemesh) to apply any layout to the results.

class EmployeeController {
  ...
  def listByDepartment() {
    def model = [:]
    model['department'] = Department.get(params.id)
    model['employees'] = Employee.findAllByDepartment(model['department'])
    render template: 'employeeListForDepartment', model: model
  }
  ...
}

Part 3 (Displaying the results in a template)

Finally, our template grails-app/views/employee/_employeeListForDepartment.gsp is going to display our employees for the department. Since we used the employee controller the template is inside the employee views and all templates begin with an underscore.

<h1>Employees for ${department.name}</h1>
<ul>
<g:each in="${employees}" var="employee">
  <li>${employee.name}</li>
</g:each>
</ul>

Of course, the details of your implementation my be very different but the overall concept should be the same. This just touches on the main part of this and leaves a lot of details out, such as spinners, canceling requests, and such.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top