/**
   * Persist a FormTempate.
   *
   * @param formTemplate - FormTemplate.
   * @param result - used for errorhandling.
   * @param status - used for session state handling.
   * @param model - ModelMap
   * @return navigate to Templatelist or back to TemplateEdit.
   */
  @Transactional
  @RequestMapping(method = RequestMethod.POST)
  public String addTemplate(
      @Valid @ModelAttribute("formTemplate") FormTemplate formTemplate,
      BindingResult result,
      SessionStatus status,
      ModelMap model) {
    if (result.hasErrors()) {
      return "TemplateEdit";
    }

    CustomCategory customCategory = formTemplate.getCustomCategory();
    if (customCategory != null) {
      for (Iterator<CustomSubCategory> it = customCategory.getCustomSubCategories().iterator();
          it.hasNext(); ) {
        CustomSubCategory subCategory = it.next();
        if (StringUtils.isBlank(subCategory.getName())) {
          it.remove();
        }
      }
    }

    formTemplate.setLastChanged(new Date());
    if (formTemplate.getId() == null) {
      formTemplateRepository.persist(formTemplate);
    } else {
      formTemplateRepository.merge(formTemplate);
    }

    status.setComplete();

    return "redirect:TemplateList";
  }
  /**
   * Redirect back to TemplateEdit to continue working with the formTemplate.
   *
   * @param formTemplate - the main backing bean.
   * @return - view for FormTemplate edit.
   */
  @RequestMapping(method = RequestMethod.POST, value = "/CustomCategoryUpdate")
  public String updateCustomCategory(@ModelAttribute("formTemplate") FormTemplate formTemplate) {
    for (Iterator<CustomSubCategory> it =
            formTemplate.getCustomCategory().getCustomSubCategories().iterator();
        it.hasNext(); ) {
      CustomSubCategory subCategory = it.next();
      if (StringUtils.isBlank(subCategory.getName())) {
        it.remove();
      }
    }

    return "redirect:TemplateEdit";
  }
  /**
   * Edit CustomCategory without persist. FormTemplate has to be handled to allow preserving data
   * not stored yet.
   *
   * @param formTemplate - main backing bean.
   * @return - view with edit form.
   */
  @RequestMapping(method = RequestMethod.GET, value = "/CustomCategoryEdit")
  public String editCustomCategory(@ModelAttribute("formTemplate") FormTemplate formTemplate) {

    List<CustomSubCategory> subCategories =
        formTemplate.getCustomCategory().getCustomSubCategories();
    int emptyCnt = 0;
    for (CustomSubCategory subCategory : subCategories) {
      if (StringUtils.isBlank(subCategory.getName())) emptyCnt++;
    }

    for (int i = emptyCnt; i < 3; i++) {
      CustomSubCategory customSubCategory = new CustomSubCategory();
      customSubCategory.setBackend(new Backend());

      subCategories.add(customSubCategory);
    }

    return "CustomCategoryEdit";
  }