Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play-java 2.5.9 form.errorsAsJson() always returns english error messages

I'm new to play framework, I'm using play java 2.5.9 I'm trying to get form errors and render it using ajax (that's why I'm using form.errorsAsJson()) , errors should be displayed in Arabic language

I've tried and put error messages in my conf/messages.ar like this:

#bean validation messages
validation.required=لابد من إدخال قيمة في هذا الحقل
error.required=لابد من إدخال قيمة في هذا الحقل

I've also tried and put the following in conf/ValidationMessages_ar.properties :

error.required=\u0627\u0644\u062D\u0642\u0644 \u0645\u0637\u0644\u0648\u0628 validation.required=\u0644\u0627\u0628\u062F \u0645\u0646 \u0625\u062F\u062E\u0627\u0644 \u0642\u064A\u0645\u0629 \u0641\u064A \u0647\u0630\u0627 \u0627\u0644\u062D\u0642\u0644 neither of the two messages is renderd but I always get:

This field is required

my action code is as follows:

@Transactional
public Result addUOMType(){
    ObjectNode result = Json.newObject();
    Form<UnitOfMeasureType> uomTypeForm = formFactory.form(UnitOfMeasureType.class);
    try{
        uomTypeForm = uomTypeForm.bindFromRequest();
        System.out.println(Http.Context.current()  != null ? Http.Context.current().lang() : "");
        if(uomTypeForm.hasErrors()){
            result.put("status", "error");
            result.put("errors", uomTypeForm.errorsAsJson());
            return ok(result);
        }
        UnitOfMeasureType uomType = uomTypeForm.get();
        uomType.save();
        result.put("status", "success");
        result.put("message", Messages.get("response.success"));
    }catch (Exception exp){
        result.put("status", "error");
        result.put("errors", Json.toJson(exp.getMessage()));
    }

    return ok(result);
}

the System.out.println prints: Lang(ar)

like image 559
Hassaan Hassaan Avatar asked Mar 22 '26 00:03

Hassaan Hassaan


1 Answers

Form.errorsAsJson has an overloaded version taking Lang parameter:

public com.fasterxml.jackson.databind.JsonNode errorsAsJson(Lang lang)
// Returns the form errors serialized as Json using the given Lang.

So you can do:

result.put("errors", uomTypeForm.errorsAsJson(lang()));

and it will return properly localized messages, as long as you define them in conf/messages.ar. I've just tried this in my project and it worked fine.

Method lang() is defined in play.mvc.Controller.

like image 189
Paweł Bartkiewicz Avatar answered Mar 24 '26 14:03

Paweł Bartkiewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!