Disappearing Button

A light-weight hands-on-coding kinda post this one, and that too not in a mainstream language, Grails. The use case is a familiar one on social networking sites like facebook or linkedin.

Let's say you have pending friendship/connection requests. Adjacent to each username you will have a button ("Accept"). Once you click the button and the server has done its job, you will see text in place of the button saying something like "Mr. X is now a connection". I call this pattern as the disappearing button pattern.

The key to implement it is an ajax call by the button pressed, the return updating the div element in which the button is placed and replacing the button with a text.

In grails, the mechanism is as follows:
view
render template1

template 1
div1
    remoteSubmit
    update div1
/div1

controller
render template2

template 2
Connection Accepted

Here is the actual code, and it’s quite easy to follow the flow.
view.gsp
<g:form>
<g:submitToRemote value="Check Pending Connnections"
url="[controller: 'profile', action: 'pending_connections']"
update="pending_connections_list" />
</g:form>
<div id="pending_connections_list">
</div>
view raw tt1.gsp hosted with ❤ by GitHub
ProfileController
def pending_connections = {
def user = session.user.attach()
render (template: 'pending-connections',
model: [pending_connections : user.connections_requested_by])
}
view raw tt4.groovy hosted with ❤ by GitHub
_pending_connections.gsp
<b>Pending Connections List</b>
<table>
<g:each var="user" in="${pending_connections}">
<g:form>
<tr>
<td>${user}</td>
<td><div id="accept_connection-${user}">
<g:submitToRemote value="Accept Connection"
url="[controller: 'profile', action: 'accept_connection']"
update="accept_connection-${user}" />
</div></td>
</tr>
</g:form>
</g:each>
</table>
view raw tt2.gsp hosted with ❤ by GitHub
ProfileController.groovy
def accept_connection = {
def user1 = session.user.attach()
user1.connections_requested_by.remove(params.profile_username)
user1.connections.add(profile_username)
user1.save()
User user2 = User.findByUsername(params.profile_username)
user2.connections.requested_to.remove(user1.username)
user2.save()
render (template: 'accept-connection')
}
view raw tt3.groovy hosted with ❤ by GitHub
_accept-connection.gsp
Connection Accepted

Comments

Popular posts from this blog

Mentoring Trainees In Java

27th

Fetching Blogger Posts With Python