title: Spring MVC 3. How to modify the form after binding but before validation
body: <p>I am developing an application using Spring MVC 3 annotated style controllers. In some ocassions I need to add/modify some field values depending on session variables or some other condition. To complicate things, the field may have a fixed value if some condition is matched, and read user input if not. The question is: There is a way to modify the form after binding but before validation using spring mvc 3? It was quite simple with SimpleFormController (onBind method), but I can't find a way in spring mvc 3.</p>
  
  <p>An example:</p>
  
  <p>a) I initialize the binder for my form. Add a validator, set the list of allowed fields, and add a list of generic property editors</p>
  
  <pre><code>@InitBinder(value = COMMAND_NAME)
  @Override
  public void initBinder(final WebDataBinder binder, final HttpServletRequest httpServletRequest) {
      binder.setValidator(reenvioAsientoValidator);
      binder.setAllowedFields(ReenvioAsientoForm.getListaCamposPermitidos());
      .... Add some custom property editors for booleans, integers ....
  }
  </code></pre>
  
  <p>b) Create model object</p>
  
  <pre><code>@ModelAttribute(value = COMMAND_NAME)
  public ReenvioAsientoForm rellenaModelo(final HttpServletRequest httpServletRequest) {
  
      final ReenvioAsientoForm form = new ReenvioAsientoForm();       
      ... Add some field values, which cannot be modified by user ...
      return form;
  }
  </code></pre>
  
  <p>c) Binding happens: And it can modify any field that is in the allowedFields list. Even those I setted in phase b)</p>
  
  <p>d) <strong>THIS IS WHAT I CAN'T DO</strong>. I need to set/modify some fields of the form. Can't be done in the create model phase, because those fields are in the allowedFields list (Depending on different conditions, they can be readonly or accept user input)</p>
  
  <p>e) Validation happens</p>
  
  <p>f) Controller POST method is invoked </p>
  
  <pre><code>@RequestMapping(value = URI_REENVIO_ASIENTO, method = RequestMethod.POST)
  public ModelAndView submit(@Valid @ModelAttribute(COMMAND_NAME) final ReenvioAsientoForm form, final BindingResult result, HttpServletRequest request) {
      .....
  }
  </code></pre>
  
  <p>Somethings I've tried:</p>
  
  <ol>
  <li>Modify inside validator, before validation: That is a possible solution, but I find it nasty, because I am using the validator for something it is not intended. Plus it only works if the form is validated.</li>
  <li>Using a CustomPropertyEditor. This way I can check the condition and set the value during binding. The problem is that the binder is fired only if a the property is present in the request. If there were someway to fire it always, it would be a nice solution</li>
  </ol>