'This callback method is for handling form editing.  The value of response_redirect
should be an URL that is defined by the caller.  This allows for redirecting as desired
when the form changes have been saved.  For an example of how this works, see the
edit_template() method in the base controller.'

@web.expose
@web.require_admin
def edit_form_definition(self, trans, response_redirect=None, **kwd):

    params = util.Params(kwd)
    message = util.restore_text(params.get('message', ''))
    status = params.get('status', 'done')
    try:
        form_definition_current = trans.sa_session.query(trans.app.model.FormDefinitionCurrent).get(trans.security.decode_id(kwd['id']))
    except:
        return trans.response.send_redirect(web.url_for(controller='forms', action='browse_form_definitions', message='Invalid    form', status='error'))
    form_definition = form_definition_current.latest_form
    if params.get('refresh', False):
        current_form = self.get_current_form(trans, **kwd)
    else:
        current_form = self.get_saved_form(form_definition)
    if params.get('save_changes_button', False):
        (new_form_definition, message) = self.save_form_definition(trans, form_definition_current_id=form_definition.form_definition_current.id, **kwd)
        if (not new_form_definition):
            status = 'error'
        else:
            if response_redirect:
                return trans.response.send_redirect(response_redirect)
            form_definition = new_form_definition
            current_form = self.get_saved_form(form_definition)
            message = ("The    form    '%s'    has    been    updated    with    the    changes." % form_definition.name)
    elif params.get('add_layout_grid_button', False):
        current_form['layout'].append('')
    elif params.get('remove_layout_grid_button', False):
        index = (int(kwd['remove_layout_grid_button'].split('    ')[2]) - 1)
        del current_form['layout'][index]
    elif params.get('add_field_button', False):
        field_index = (len(current_form['fields']) + 1)
        self.empty_field['name'] = ('%i_field_name' % field_index)
        self.empty_field['label'] = ('Field    label    %i' % field_index)
        current_form['fields'].append(self.empty_field)
    elif params.get('remove_button', False):
        index = (int(kwd['remove_button'].split('    ')[2]) - 1)
        del current_form['fields'][index]
    elif ('Add' in kwd.values()):
        (current_form, status, message) = self.__add_select_field_option(trans=trans, current_form=current_form, **kwd)
    elif ('Remove' in kwd.values()):
        (current_form, status, message) = self.__remove_select_field_option(trans=trans, current_form=current_form, **kwd)
    return self.show_editable_form_definition(trans=trans, form_definition=form_definition, current_form=current_form, message=message, status=status, response_redirect=response_redirect, **kwd)
