4th part in Confluence plugin development series..
Today I describe how to make Ajax requests to XWork actions inside a
Confluence plugin. A good example is server-side form validation. User fills a form, clicks
Submit
, then we validate the form in background and if there are no errors we allow submitting the form, otherwise show field errors.
Suppose we have a simple user info form with input fields like name, department, email etc:
<form id="saveform" action="doUpdate.action" method="post">
#tag( TextField "name='user.name'" "size='50'" )
#tag( Select "name='user.department'"
"list=departmentsDao.all"
"listKey=name" "listValue=name"
"emptyOption='true'" )
#tag( TextField "name='user.email'" "size='50'" )
...
#tag( Submit "id=userformsubmit"
"name='save'" "value='dot.button.save'" )
#tag( Submit "name='cancel'" "value='dot.button.cancel'" )
</form>
One way to make form validation is to write it in javascript, but what if you already have it implemented in action? Write everything again? Maybe it's better to use existing server side code so you can switch on/off Ajax at any time and you'll not have the same logic implemented twice.
Here are the required steps:
- edit atlassian-plugin.xml and create a package for you application with validation enabled, declare an action
doUpdate
for submitting a form and editValidate
for Ajax validation <package name="userinfo" extends="default"
namespace="/dot/users">
<default-interceptor-ref name="validatingStack"/>
...
<action name="doUpdate"
class="dot.userinfo.users.action.EditUserInfo"
method="save">
<external-ref name="dotUsersDao">
usersDao</external-ref>
<external-ref name="dotDepartmentsDao">
departmentsDao</external-ref>
<external-ref name="dotCitiesDao">
citiesDao</external-ref>
<result name="input" type="velocity">
/templates/dot/userinfo/users/edituser.vm</result>
<result name="success" type="redirect">
/dot/users/usercard.action?id=${user.id}</result>
<result name="cancel" type="redirect">
/dot/users/observe.action</result>
</action>
...
<action name="editValidate"
class="dot.userinfo.users.action.EditUserInfo">
<result name="input" type="json" />
<result name="success" type="json" />
</action>
...
</package>
I turn on validatingStack
for the whole package so I could use WebWork validation everywhere I need it. Don't forget to turn off validation for actions where you don't need it, use defaultStack
for that<interceptor-ref name="defaultStack"/>
Action editValidate
will be called in Ajax from javascript. In my experience, both input
and success
return types are required. input
is returned in case of any field errors, success
when everything is ok. Actually there is no need to return success
to javascript, but instead I could save the form and redirect to another form. I'll try this in next post.
- create EditUserInfo action and implement JSONAction interface
public class EditUserInfo
extends ConfluenceActionSupport
implements JSONAction {
...
public String getJSONString() {
try {
if (hasFieldErrors()) {
StringBuffer sb = new StringBuffer();
sb.append("[");
Map fieldErrors = getFieldErrors();
for (Object field : fieldErrors.keySet()) {
List<Object> msg =
(List<Object>) fieldErrors.get(field);
if (field != null && msg != null
&& msg.get(0) != null) {
sb.append("{field:'"+field+"',
error:'"+msg.get(0)+"'},");
}
}
if (sb.length() > 1) {
sb.deleteCharAt(sb.length()-1);
}
sb.append("]");
return sb.toString();
}
} catch (Exception e) {
// handle exception
}
return "";
}
}
By the time getJSONString()
method is called validation was already done by WebWork so we can immediatelly process the errors. Here I generate a Javascript array of all field errors which I want to show next to input fieds.
- write
EditUserInfo-validation.xml
file in the same package as java class. My validation file looks something like this <!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="user.name">
<field-validator type="requiredstring">
<message key="dot.field.error.required" />
</field-validator>
</field>
<field name="user.department">
<field-validator type="requiredstring">
<message key="dot.field.error.required" />
</field-validator>
</field>
<field name="user.email">
<field-validator type="requiredstring">
<message key="dot.field.error.required" />
</field-validator>
<field-validator type="email">
<message key="dot.field.error.email" />
</field-validator>
</field>
</validators>
Main stuff is done, last thing we need is to call validation from Javascript and show error messages.
- attach
click
event to submit button $("#userformsubmit").click(function(e) {
try {
var form = $("#saveform");
validateForm(form);
} catch (e) { alert(e); }
return false; // always!
});
- my
validateForm
looks like this function validateForm(form) {
$.ajax({url: "editValidate.action",
data: form.serialize(),
success: function(data) { try {
var fields = $("#saveform span.fielderror");
// delete old errors,
// error spans are found by class name
fields.html("");
// set received errors, iterate through span IDs
data = eval(data);
if (data && data.length > 0) {
for (i in data) {
var id = data[i].field.replace(/\./, "\\.")+
"-error";
var fe = $("#"+id);
if (fe) { fe.html(data[i].error); }
}
return false;
}
$("#saveform").submit();
return true;
} catch (e) { alert(e); } }
});
return false;
}
here for every input control I have span with id ending with '-error'
and class 'fielderror'
. I still haven't tried to write macros so I implemented a separate file fielderror.vm
<span id="$!webwork.htmlEncode($f)-error"
class="fielderror">
#set( $err = $fieldErrors.get($f) )
#if( $err.size() > 0 )
$err.get(0)
#end
</span>
which I include in main page next to input fields. Example for user name field:#set( $f = "user.name" )
#parse( "/templates/dot/userinfo/fielderror.vm" )
not so nice solution but I can live with that for now.
Next week I'll try to optimize the code. In current implementation I believe validation is called twice: 1st time in ajax, and 2nd time when form is submitted (this we can escape), for field errors I need macro..