问题
I have a have a form that I have added an extra sfWidgetFormTextarea widget onto in the form class.
I want to save the form by updating database for the fields that correpsond to the form, but then get the value for the sfWidgetFormTextarea and insert that into another table as a new row saving both the textarea value and the id number created for the saved data in the other table.
It sounds confusing so maybe if I put it in context it'll be less so. My form is getting the details of a patient's blood test. The user can also add any comments if they want about the test. One blood test record can have multiple comments. For this reason I want to save the comment in another table with the id of the test so all comments for one test can be retrieved.
I have realised that this extra sfWidgetFormTextarea is going to break the save function because it'll go to save it and there wont be a field in the table called comment so it wont know where to save this textarea value to. Should I somehow remove the comment value from $request and insert it into the comment table? I'd also need to know the id thought of the tets it relates to though, which isn't cone until the save function.
Please help, my head hurts!!
回答1:
You can save the form manually, please check the code snippet below
$this->form->bind($request->getParameter('formname'));
if ($this->form->isValid()) {
$arrValues = $this->form->getValues();
//get dataobject base on criteria...
$objTable1 = Table1Peer::getByField($arrValues['my_field']);
if(is_object($objTable1)){
$objTable1->setField($arrValues['my_field']);
//update
if($objTable1->save()){
$objTable2 = new Table2();
$objTable2->setPostId($objTable1->getId());
$objTable2->setComment($arrValues['my_comment']);
if($objTable2->save()){
$this->redirect('@action_name');
$this->getUser()->setFlash('success', 'comment saved');
}else{
$this->getUser()->setFlash('error', 'failed to save form, contact admin');
}
}else{
$this->getUser()->setFlash('error', 'failed to save form, contact admin');
}
}
I hope this helps, let me know if you come alright...
来源:https://stackoverflow.com/questions/5961527/how-to-update-2-tables-from-one-form-in-symfony