0

How to create edit forms. For url edit?id=1121 I want to display pre-filled data

 EditForm(twf.Form):  
    class child(twf.TableLayout):  
       name= twf.TextField(name="name",value=DBSession.query(student.name).filter(student.id == <id passed in url>).distinct().all())


    @expose ('edit')  
   def edit(self, id)  

       return dict(page='edit', , form=EditForm(action='/save')  

Template:

    <div>${form.display()}</div>  
user2764578
  • 61
  • 3
  • 10

1 Answers1

1

There are a few ways to achieve this, but I'd say that the cleanest one is passing the values to the form from the controller action as showcased by http://turbogears.readthedocs.io/en/latest/turbogears/widgets_forms.html#displaying-forms

In the case of your specific example it should result in having a form that only declares the fields that need editing and a reference to the edited object id:

class EditForm(twf.Form):  
    class child(twf.TableLayout):  
       student_id = twf.HiddenField()
       name = twf.TextField(name="name")

Then within the controller you can fetch the edited object and provide the values to the form:

   @expose('edit')  
   def edit(self, id):
       edited_student = DBSession.query(student).filter(student.id==id).first()
       return dict(page='edit', 
                   form=EditForm(action='/save', 
                                 value=dict(student_id=id, 
                                            name=edited_student.name))

Keep in mind that this is just a proof of concept, I haven't tested the code and it lacks proper validation/error handling. But it should pretty much give the idea that you just pass the student name to the form through the value parameter when displaying it.

amol
  • 1,771
  • 1
  • 11
  • 15
  • That's works for TextField but for SingleSelectField I passed value like this which didn't worked.. form=EditForm(action='/save', value=dict(student_id=id, name=edited_student.name, subject={"options":['english',"maths"]) – user2764578 Jul 04 '18 at 21:13
  • I mean like this from db form=EditForm(action='/save', value=dict(student_id=id, name=edited_student.name, subject={"options":edited_student.subjects) – user2764578 Jul 04 '18 at 22:41
  • 1
    For singleselect your can still provide the "value" so the selected entry using the "value" parameter. For the options instead you need to specify them as a deferred parameter using `options=twf.Deferred(any_callable)` or you can just set them before displaying the form with `form.child.children.project.options = selectable_projects` See https://gist.github.com/amol-/db5922ba78551e739dc32b7365f0c991 for a working example. – amol Jul 05 '18 at 12:50