Package play.data

Class Form<T>

  • Direct Known Subclasses:
    DynamicForm

    public class Form<T>
    extends Object
    Helper to manage HTML form description, submission and validation.
    • Field Detail

      • logger

        protected final org.slf4j.Logger logger
    • Constructor Detail

      • Form

        public Form​(Class<T> clazz,
                    MessagesApi messagesApi,
                    Formatters formatters,
                    javax.validation.ValidatorFactory validatorFactory,
                    com.typesafe.config.Config config)
        Creates a new Form. Consider using a FormFactory rather than this constructor.
        Parameters:
        clazz - wrapped class
        messagesApi - messagesApi component.
        formatters - formatters component.
        validatorFactory - validatorFactory component.
        config - config component.
      • Form

        public Form​(String rootName,
                    Class<T> clazz,
                    MessagesApi messagesApi,
                    Formatters formatters,
                    javax.validation.ValidatorFactory validatorFactory,
                    com.typesafe.config.Config config)
      • Form

        public Form​(String rootName,
                    Class<T> clazz,
                    Class<?> group,
                    MessagesApi messagesApi,
                    Formatters formatters,
                    javax.validation.ValidatorFactory validatorFactory,
                    com.typesafe.config.Config config)
      • Form

        public Form​(String rootName,
                    Class<T> clazz,
                    Class<?>[] groups,
                    MessagesApi messagesApi,
                    Formatters formatters,
                    javax.validation.ValidatorFactory validatorFactory,
                    com.typesafe.config.Config config)
      • Form

        public Form​(String rootName,
                    Class<T> clazz,
                    Map<String,​String> data,
                    List<ValidationError> errors,
                    Optional<T> value,
                    Class<?>[] groups,
                    MessagesApi messagesApi,
                    Formatters formatters,
                    javax.validation.ValidatorFactory validatorFactory,
                    com.typesafe.config.Config config)
        Creates a new Form. Consider using a FormFactory rather than this constructor.
        Parameters:
        rootName - the root name.
        clazz - wrapped class
        data - the current form data (used to display the form)
        errors - the collection of errors associated with this form
        value - optional concrete value of type T if the form submission was successful
        groups - the array of classes with the groups.
        messagesApi - needed to look up various messages
        formatters - used for parsing and printing form fields
        validatorFactory - the validatorFactory component.
        config - the config component.
      • Form

        public Form​(String rootName,
                    Class<T> clazz,
                    Map<String,​String> data,
                    Map<String,​Http.MultipartFormData.FilePart<?>> files,
                    List<ValidationError> errors,
                    Optional<T> value,
                    Class<?>[] groups,
                    MessagesApi messagesApi,
                    Formatters formatters,
                    javax.validation.ValidatorFactory validatorFactory,
                    com.typesafe.config.Config config)
        Creates a new Form. Consider using a FormFactory rather than this constructor.
        Parameters:
        rootName - the root name.
        clazz - wrapped class
        data - the current form data (used to display the form)
        files - the current form file data
        errors - the collection of errors associated with this form
        value - optional concrete value of type T if the form submission was successful
        groups - the array of classes with the groups.
        messagesApi - needed to look up various messages
        formatters - used for parsing and printing form fields
        validatorFactory - the validatorFactory component.
        config - the config component.
      • Form

        public Form​(String rootName,
                    Class<T> clazz,
                    Map<String,​String> data,
                    List<ValidationError> errors,
                    Optional<T> value,
                    Class<?>[] groups,
                    MessagesApi messagesApi,
                    Formatters formatters,
                    javax.validation.ValidatorFactory validatorFactory,
                    com.typesafe.config.Config config,
                    Lang lang)
        Creates a new Form. Consider using a FormFactory rather than this constructor.
        Parameters:
        rootName - the root name.
        clazz - wrapped class
        data - the current form data (used to display the form)
        errors - the collection of errors associated with this form
        value - optional concrete value of type T if the form submission was successful
        groups - the array of classes with the groups.
        messagesApi - needed to look up various messages
        formatters - used for parsing and printing form fields
        validatorFactory - the validatorFactory component.
        config - the config component.
        lang - used for formatting when retrieving a field (via field(String) or apply(String)) and for translations in errorsAsJson()
      • Form

        public Form​(String rootName,
                    Class<T> clazz,
                    Map<String,​String> data,
                    Map<String,​Http.MultipartFormData.FilePart<?>> files,
                    List<ValidationError> errors,
                    Optional<T> value,
                    Class<?>[] groups,
                    MessagesApi messagesApi,
                    Formatters formatters,
                    javax.validation.ValidatorFactory validatorFactory,
                    com.typesafe.config.Config config,
                    Lang lang)
        Creates a new Form. Consider using a FormFactory rather than this constructor.
        Parameters:
        rootName - the root name.
        clazz - wrapped class
        data - the current form data (used to display the form)
        files - the current form file data
        errors - the collection of errors associated with this form
        value - optional concrete value of type T if the form submission was successful
        groups - the array of classes with the groups.
        messagesApi - needed to look up various messages
        formatters - used for parsing and printing form fields
        validatorFactory - the validatorFactory component.
        config - the config component.
        lang - used for formatting when retrieving a field (via field(String) or apply(String)) and for translations in errorsAsJson()
      • Form

        public Form​(String rootName,
                    Class<T> clazz,
                    Map<String,​String> data,
                    List<ValidationError> errors,
                    Optional<T> value,
                    Class<?>[] groups,
                    MessagesApi messagesApi,
                    Formatters formatters,
                    javax.validation.ValidatorFactory validatorFactory,
                    com.typesafe.config.Config config,
                    Lang lang,
                    boolean directFieldAccess)
        Creates a new Form. Consider using a FormFactory rather than this constructor.
        Parameters:
        rootName - the root name.
        clazz - wrapped class
        data - the current form data (used to display the form)
        errors - the collection of errors associated with this form
        value - optional concrete value of type T if the form submission was successful
        groups - the array of classes with the groups.
        messagesApi - needed to look up various messages
        formatters - used for parsing and printing form fields
        validatorFactory - the validatorFactory component.
        config - the config component.
        lang - used for formatting when retrieving a field (via field(String) or apply(String)) and for translations in errorsAsJson()
        directFieldAccess - access fields of form directly during binding instead of using getters
      • Form

        public Form​(String rootName,
                    Class<T> clazz,
                    Map<String,​String> data,
                    Map<String,​Http.MultipartFormData.FilePart<?>> files,
                    List<ValidationError> errors,
                    Optional<T> value,
                    Class<?>[] groups,
                    MessagesApi messagesApi,
                    Formatters formatters,
                    javax.validation.ValidatorFactory validatorFactory,
                    com.typesafe.config.Config config,
                    Lang lang,
                    boolean directFieldAccess)
        Creates a new Form. Consider using a FormFactory rather than this constructor.
        Parameters:
        rootName - the root name.
        clazz - wrapped class
        data - the current form data (used to display the form)
        files - the current form file data
        errors - the collection of errors associated with this form
        value - optional concrete value of type T if the form submission was successful
        groups - the array of classes with the groups.
        messagesApi - needed to look up various messages
        formatters - used for parsing and printing form fields
        validatorFactory - the validatorFactory component.
        config - the config component.
        lang - used for formatting when retrieving a field (via field(String) or apply(String)) and for translations in errorsAsJson()
        directFieldAccess - access fields of form directly during binding instead of using getters
    • Method Detail

      • getBackedType

        public Class<T> getBackedType()
      • blankInstance

        protected T blankInstance()
      • maxJsonChars

        protected long maxJsonChars()
        The default maximum number of chars to support when binding a form from JSON.
      • maxJsonDepth

        protected int maxJsonDepth()
        The default maximum depth of JSON objects and arrays when binding a form from JSON.
      • bindFromRequest

        public Form<T> bindFromRequest​(Http.Request request,
                                       String... allowedFields)
        Binds request data to this form - that is, handles form submission.
        Parameters:
        request - the request to bind data from.
        allowedFields - the fields that should be bound to the form, all fields if not specified.
        Returns:
        a copy of this form filled with the new data
      • bindFromRequestData

        public Form<T> bindFromRequestData​(Lang lang,
                                           TypedMap attrs,
                                           Map<String,​String[]> requestData,
                                           String... allowedFields)
        Binds request data to this form - that is, handles form submission.
        Parameters:
        lang - used for validators and formatters during binding and is part of Constraints.ValidationPayload. Later also used for formatting when retrieving a field (via field(String) or apply(String)) and for translations in errorsAsJson(). For these methods the lang can be change via withLang(Lang).
        attrs - will be passed to validators via Constraints.ValidationPayload
        requestData - the map of data to bind from
        allowedFields - the fields that should be bound to the form, all fields if not specified.
        Returns:
        a copy of this form filled with the new data
      • bind

        public Form<T> bind​(Lang lang,
                            TypedMap attrs,
                            com.fasterxml.jackson.databind.JsonNode data,
                            long maxChars,
                            String... allowedFields)
        Binds Json data to this form - that is, handles form submission.
        Parameters:
        lang - used for validators and formatters during binding and is part of Constraints.ValidationPayload. Later also used for formatting when retrieving a field (via field(String) or apply(String)) and for translations in errorsAsJson(). For these methods the lang can be change via withLang(Lang).
        attrs - will be passed to validators via Constraints.ValidationPayload
        data - data to submit
        maxChars - the maximum number of chars allowed to be used in the intermediate map representation of the JSON. `parse.DefaultMaxTextLength` is recommended to passed for this parameter.
        allowedFields - the fields that should be bound to the form, all fields if not specified.
        Returns:
        a copy of this form filled with the new data
      • bind

        public Form<T> bind​(Lang lang,
                            TypedMap attrs,
                            com.fasterxml.jackson.databind.JsonNode data,
                            long maxChars,
                            int maxDepth,
                            String... allowedFields)
        Binds Json data to this form - that is, handles form submission.
        Parameters:
        lang - used for validators and formatters during binding and is part of Constraints.ValidationPayload. Later also used for formatting when retrieving a field (via field(String) or apply(String)) and for translations in errorsAsJson(). For these methods the lang can be change via withLang(Lang).
        attrs - will be passed to validators via Constraints.ValidationPayload
        data - data to submit
        maxChars - the maximum number of chars allowed to be used in the intermediate map representation of the JSON. `parse.DefaultMaxTextLength` is recommended to passed for this parameter.
        maxDepth - the maximum depth allowed for JSON objects and arrays.
        allowedFields - the fields that should be bound to the form, all fields if not specified.
        Returns:
        a copy of this form filled with the new data
      • getArgumentsForConstraint

        protected Object[] getArgumentsForConstraint​(String objectName,
                                                     String field,
                                                     javax.validation.ConstraintViolation<Object> violation)
      • getMessageForConstraintViolation

        protected String getMessageForConstraintViolation​(javax.validation.ConstraintViolation<Object> violation)
        When dealing with @ValidateWith or @ValidatePayloadWith annotations, and message parameter is not used in the annotation, extract the message from validator's getErrorMessageKey() method
        Parameters:
        violation - the constraint violation.
        Returns:
        the message associated with the constraint violation.
      • rawData

        public Map<String,​String> rawData()
        Returns:
        the actual form data as unmodifiable map. Does not contain file data, use files() to access files.
      • value

        public Optional<T> value()
        Returns:
        the actual form value - even when the form contains validation errors.
      • fill

        public Form<T> fill​(T value)
        Populates this form with an existing value, used for edit forms.
        Parameters:
        value - existing value of type T used to fill this form
        Returns:
        a copy of this form filled with the new data
      • hasErrors

        public boolean hasErrors()
        Returns:
        true if there are any errors related to this form.
      • hasGlobalErrors

        public boolean hasGlobalErrors()
        Returns:
        true if there any global errors related to this form.
      • globalErrors

        public List<ValidationError> globalErrors()
        Retrieve all global errors - errors without a key.
        Returns:
        All global errors.
      • globalError

        public Optional<ValidationError> globalError()
        Retrieves the first global error (an error without any key), if it exists.
        Returns:
        An error.
      • errors

        public List<ValidationError> errors()
        Returns all errors.
        Returns:
        All errors associated with this form.
      • errors

        public List<ValidationError> errors​(String key)
        Parameters:
        key - the field name associated with the error.
        Returns:
        All errors for this key.
      • error

        public Optional<ValidationError> error​(String key)
        Parameters:
        key - the field name associated with the error.
        Returns:
        an error by key
      • errorsAsJson

        public com.fasterxml.jackson.databind.JsonNode errorsAsJson()
        Returns:
        the form errors serialized as Json.
      • errorsAsJson

        public com.fasterxml.jackson.databind.JsonNode errorsAsJson​(Lang lang)
        Returns the form errors serialized as Json using the given Lang.
        Parameters:
        lang - the language to use.
        Returns:
        the JSON node containing the errors.
      • get

        public T get()
        Gets the concrete value only if the submission was a success. If the form is invalid because of validation errors this method will throw an exception. If you want to retrieve the value even when the form is invalid use value() instead.
        Returns:
        the concrete value.
        Throws:
        IllegalStateException - if there are errors binding the form, including the errors as JSON in the message
      • get

        public T get​(Lang lang)
        Gets the concrete value only if the submission was a success. If the form is invalid because of validation errors this method will throw an exception. If you want to retrieve the value even when the form is invalid use value() instead.
        Parameters:
        lang - if an IllegalStateException gets thrown it's used to translate the form errors within that exception
        Returns:
        the concrete value.
        Throws:
        IllegalStateException - if there are errors binding the form, including the errors as JSON in the message
      • withError

        public Form<T> withError​(ValidationError error)
        Parameters:
        error - the ValidationError to add to the returned form.
        Returns:
        a copy of this form with the given error added.
      • withError

        public Form<T> withError​(String key,
                                 String error,
                                 List<Object> args)
        Parameters:
        key - the error key
        error - the error message
        args - the error arguments
        Returns:
        a copy of this form with the given error added.
      • withError

        public Form<T> withError​(String key,
                                 String error)
        Parameters:
        key - the error key
        error - the error message
        Returns:
        a copy of this form with the given error added.
      • withGlobalError

        public Form<T> withGlobalError​(String error,
                                       List<Object> args)
        Parameters:
        error - the global error message
        args - the global error arguments
        Returns:
        a copy of this form with the given global error added.
      • withGlobalError

        public Form<T> withGlobalError​(String error)
        Parameters:
        error - the global error message
        Returns:
        a copy of this form with the given global error added.
      • discardingErrors

        public Form<T> discardingErrors()
        Returns:
        a copy of this form but with the errors discarded.
      • apply

        public Form.Field apply​(String key)
        Retrieves a field.
        Parameters:
        key - field name
        Returns:
        the field (even if the field does not exist you get a field)
      • apply

        public Form.Field apply​(String key,
                                Lang lang)
        Retrieves a field.
        Parameters:
        key - field name
        lang - the language to use for the formatter
        Returns:
        the field (even if the field does not exist you get a field)
      • field

        public Form.Field field​(String key)
        Retrieves a field.
        Parameters:
        key - field name
        Returns:
        the field (even if the field does not exist you get a field)
      • field

        public Form.Field field​(String key,
                                Lang lang)
        Retrieves a field.
        Parameters:
        key - field name
        lang - used for formatting
        Returns:
        the field (even if the field does not exist you get a field)
      • withDirectFieldAccess

        public Form<T> withDirectFieldAccess​(boolean directFieldAccess)
        Sets if during binding fields of the form should be accessed directly or via getters.
        Parameters:
        directFieldAccess - true enables direct field access during form binding, false disables it and uses getters instead. If null falls back to config default.