如何在 Grails 中进行正确的数据绑定

How to do proper data binding in Grails

我正在尝试通过将实体添加到数据库来执行标准流程。流程应如下所示:

  1. 用户打开 link 示例。co/connection/putForm
  2. 编辑所有字段
  3. 提交 (POST) 到 示例。co/connection/put
  4. 如果没有错误,那么他将被重定向到 ../conncetion/index 否则他应该会看到之前的表格,所有字段都已填写(第 2 步)和错误消息

现在我的代码如下所示:

def putForm() {
    [
            providers: Provider.findAll(),
            cities   : City.findAll()
    ]
}

@Transactional
def put() {
    // not important part of parsing fields from params
    def provider = Provider.get(params.provider)
    def startTime = parseStartTime(params)
    def path = parsePath(params)
    def departurePlace = params.departurePlace

    def connection = new Connection(provider: provider, startTime: startTime, departurePlace: departurePlace, path: path)
    if (connection.save()) {
        redirect controller: 'connection', action: 'index', params: [addedConnection: connection.id] // this part is OK
    } else {
        render view: 'putForm', params: params, model: [connection: connection] // this sucks... look below
    }
}

问题是我需要渲染视图 putForm 但是从 link .../connection/put .这会导致问题,即在渲染之后所有文本字段都是空的(上面的第 4 步)。还有我丑link.

Grails 有针对这种常见情况的模式吗?

PS我不能使用脚手架。

你离得不远..试试这个:

def putForm() {
    [
            providers: Provider.findAll(),
            cities   : City.findAll(),
connection: new Connection()  // everything defaulted to empty or whatever you want the default to be
    ]
}

@Transactional
def put( Connection connection ) {
    // NOTE: by putting the connection as the parameter to this action,
    // all params.X that match a property X in the connection will auto-
    // populate, even the Provider, assuming the value of params.provider.id
    // is the id of a provider or blank (in which case 
    // connection.provider will be null.

    // Skip this now
    //def provider = Provider.get(params.provider)
    //def startTime = parseStartTime(params)
    //def path = parsePath(params)
    //def departurePlace = params.departurePlace
    //def connection = new Connection(provider: provider, 
    // startTime: startTime, departurePlace: departurePlace, path: path)

    if (connection.save()) {
        redirect controller: 'connection', action: 'index', 
           params: [addedConnection: connection.id] // this part is OK
    } else {
        render view: 'putForm', model: [
            providers: Provider.findAll(),
            cities   : City.findAll(),
            connection: connection] 
    }
}

您现在需要做的是确保您的 putForm.gsp 确实使用了您发送下来的值。您应该输入以下内容:

<g:input name="path" type="text" 
         value="${fieldValue( bean:connection, field:'path' )}" />

<g:select name="provider.id" from="${providers}"   // note the .id in places here
          value="${connection.provider?.id ?: ''}"
          noSelection="['':'None']"/>

请注意,每次呈现页面时,这些将填充连接中发送的任何内容。因此,第一次它将只有默认值,如果由于错误而必须重新呈现,它将具有验证失败的连接值。

希望对您有所帮助。