DJ180
DJ180

Reputation: 19854

Spring MVC: Bind from form:option to enum

I am looking to bind from my select box in my form to a particular enum.

Consider this enum:

public enum OperatorDTO {
LESS_THAN ("<"),
GREATER_THAN (">"),
EQUALS ("="),
NOT_EQUALS("!=");

private String operator;

public String getOperator() {
    return operator;
}

private OperatorDTO(String operator)
{
    this.operator = operator;
}

and this snippet from my form:

<form:select path="rules[${counter.index}].operator">
    <form:options itemLabel="operator" itemValue="operator" />
</form:select>

The page renders fine and displays the various ">", "<" symbols in the drop-down box

However, when I submit my form I get errors when it attempts to bind the values back to the enums e.g. "No enum const class com.fmrco.insight.adminconsole.dto.enums.OperatorDTO.<"

Is there an easy way to perform this binding?

Thanks

Upvotes: 1

Views: 5085

Answers (2)

Rustam
Rustam

Reputation: 241

Form tags snippet is correct and enum is correct also. What is missing here is converter which Spring will use to convert String from form:options element to OperatorDTO enum.

1) Add two more methods to OperatorDTO enum

    // Enum level method to get enum instance by operator field.
    public static OperatorDTO getByOperator( final String p_operator ) {
        for ( OperatorDTO operatorDTO : OperatorDTO.values() ) {
            if ( operatorDTO.isOperatorEqual( p_operator ) ) {
                return operatorDTO;
            }
        }
        return null;
    }
    // Instance level method to compare operator field.
    public boolean isOperatorEqual( final String p_operator ) {
        return getOperator().equals( p_operator ) ? true : false;
    }

2) Create custom converter such this

import org.springframework.core.convert.converter.Converter;

public class OperatorDTOConverter implements Converter<String, OperatorDTO> {
    public OperatorDTO convert( String source ) {
        return OperatorDTO.getByOperator( source.trim() );
    }
}

3) Registeg converter in app configuration (java config in this case)

@Configuration
@EnableWebMvc
@ComponentScan( basePackages = { "your.base.package"} )
public class AppWebConfig extends WebMvcConfigurerAdapter {
@Override
    public void addFormatters( FormatterRegistry registry ) {
        registry.addConverter( String.class, OperatorDTO.class, new OperatorDTOConverter() );
    }

    ...
}

Upvotes: 1

axtavt
axtavt

Reputation: 242686

Try to omit itemValue="operator".

Item value should be the name of enum constant, and as far as I remember it's a default behavior.

Upvotes: 6

Related Questions