Command Object representando hasMany
07/08/2014 12:19
class Tarifa {
static hasMany = [valores: Valores]
List valores
String nome
}
class Valores {
static belongsTo = [tarifa: Tarifa]
BigDecimal valor
}
class GrupoCommand {
Long id //usado na edição
String nome
List<Valores> valores = [].withLazyDefault { new Valores(valor: 0) } //Crio um valor default para cada campo.
//Constraints
Tarifa criarTarifa() {
def tarifa = Tarifa.get(id) ?: new Tarifa()
tarifa.nome = nome
valores.each { valor -> tarifa.addTo(valor) }
return tarifa
}
}
<g:each in="${0..29}" var="cont" status="i">
<input type="text" id="valor_${cont}" name="valores[${cont}].valor" value="${formatNumber(number: instance.valores[cont].valor, format: "#,##0.00#, locale: 'fr_FR')}" />
</g:each>
def salvarTarifa = {GrupoCommand cmd ->
if(cmd.validate()) {
def tarifa = cmd.criarTarifa()
tarifa.save()
flash.message = message(code: 'xpto')
redirect ...
return
}
render template: 'template', model: [instance: cmd] //renderiza as mensagens de erro.
}
static hasMany = [valores: Valores]
List valores
<g:each in="${0..29}" var="cont" status="i">
<g:hiddenField name="valores[${cont}].id" value="instance.valores[cont].id" />
<input type="text" id="valor_${cont}" name="valores[${cont}].valor" value="${formatNumber(number: instance.valores[cont].valor, format: "#,##0.00#, locale: 'fr_FR')}" />
</g:each>
def salvarGrupoTarifa = { GrupoTarifaCommand cmd ->
flash.message = ""
if(cmd.validate()) {
def grupoTarifa = cmd.createGrupoTarifa();
grupoTarifa.save()
flash.message_list = message(code: 'tabelas.generico.salvo');
def estabelecimento = Estabelecimento.get(authenticateService.userDomain().estabelecimentoId)
render template: 'lista_grupo_tarifa', model: [lista: GrupoTarifa.findAllByEstabelecimentoAndStatusNotEqual(estabelecimento, "I")]
return
}
response.status = 500
render template: 'form_grupo_tarifa', model: [grupoTarifaInstance: cmd]
return
}
Para se registrar, clique aqui.