grailsmany-to-manyparameter-passinggrails-2.4

Grails - How to send one ID from view to controller (many-to-many relationship)


I am trying to send an ID of an iterated item but I think the whole list is being sent. How can I send just one ID? I have STUDENT and COURSE domain class.

Domain Model

class Student {
    String fullName
    String toString() {
        "$fullName"
    }

    static belongsTo = [school: School]
    static hasMany = [courses:Course, studentCourses:StudentCourse]
}

class Course {
    String course
    String toString() {
        "$course"
    }

    static hasMany = [studentCourses:StudentCourse]
    static belongsTo = Student

}

class StudentCourse {
    Student student
    Course course

    //Some methods...
}

And this is my edit view.

<g:if test="${studentInstance.studentCourses?.course}">
        <g:each class="courseList" in="${studentInstance.studentCourses?.course}" var="courses">
            <li class="courseList">
                <span class="courseList" aria-labelledby="courses-label">${courses.id} ${courses}
                <g:actionSubmitImage class="deleteIcon" action="deleteCourse" value="delete"
                 src="${resource(dir: 'images', file: 'delete.png')}" height="17"
                 onclick="return confirm('${message(code: 'default.button.delete.confirm.message', default: 'Are you sure?')}');"
                 params="${courses.id}"/></span>
            </li>
        </g:each>
    </g:if>

I'd like to be able to delete one course from the list when user clicks delete.png image. But when I println params.course the parameter is being sent as a whole list, not as an individual item of the list even though it is within g:each tag. How can I just send one corresponding item to the controller?

My edit page has a list of courses.

Course 23  English (delete icon here)
       42  Science (delete icon here)
       67  Math (delete icon here)

In my println params.course this is what I see.

[ English, Science, Math ]

How can I just have [English] when user clicks the delete button next to English line?

Thank you in advance.


Solution

  • As far as I have understand your problem, The problem should be in your taglib

    I am giving you the example of similar code and this is working.

    <g:each in="${student?.studentCourses?.course}" var="course">
    <div>
        <span>${course.id} ${course.course}</span>
        <g:link controller="login" action="delete" params="[courseId:course.id]">
            Delete
        </g:link>
    </div>
    

    In this block of code, by clicking delete link with params having params="${[id:course.id]}, it will redirect to delete action inside login controller. Print params in delete action and you will get output as params: [courseId:2, action:delete, format:null, controller:login] Here you can see your params.courseId is only a Long value not a list.

    Hope it will help you understand your problem.