我正在努力将我的 zend_form 刷新为2个实体。我总共有3个实体。用户,地址和国家/地区。国家不是很有趣,因为它有标准值,只有ID进入地址。我的添加动作很好(只有当我保持我的地址/国家为空时,它会在数据库中放入一条新记录,所以我要解决这个问题)。但是我的编辑只刷新了我最新的绑定。我的编辑动作:
/**
* Edit action for single user
*
* @return route zfcadmin/user/add
* @return route zfcadmin/user
* @return array(id, form, flashMessages)
*/
public function editAction()
{
$id = (int)$this->getEvent()->getRouteMatch()->getParam('id');
if (!$id) {
return $this->redirect()->toRoute('zfcadmin/user/', array('action' => 'add'));
}
//Get user with the id (given in URL), and pick his address(es)
$user = $this->getEntityManager()->find('User\Entity\User', $id);
$addresses = $user->addresses;
$form = new UserForm();
//Set country values out of the entity
$form = $this->fillCountrySelectbox($form);
$form->bind($user);
//Get addresses from the user, and bind it to the $form
foreach($addresses as $address) {
//If user has address, bind the addresses
if(isset($address)) {
$form->bind($address);
}
}
$form->get('save_goback')->setAttribute('value', 'Save');
$form->get('save')->setAttribute('value', 'Save & Stay');
$request = $this->getRequest();
if ($request->isPost()) {
//Set the inputfilter on the input values
$inputFilter = new InputFilter();
//Set filters from different entities
$inputFilter = $user->setFilters($inputFilter);
$inputFilter = $address->setFilters($inputFilter);
//Set the inputFilter on the form
$form->setInputFilter($inputFilter);
$form->setData($request->getPost());
if ($form->isValid()) {
$form->bindValues();
//set complete country object in address entity.
$country = $this->getEntityManager()->find('User\Entity\Country', $form->get('country')->getValue());
$address->__set('country', $country);
//Set country Null when no country was selected, otherwise it conflict with country entity (because no '' is set)
if($address->country == '') {
$address->country = NULL;
}
//Set modifier (current user)
$address->__set('last_modifier_id', $this->zfcUserAuthentication()->getIdentity()->getId());
$this->flashMessenger()->addMessage('User saved');
$this->getEntityManager()->flush();
if ($this->getRequest()->getPost('save_goback')) {
return $this->redirect()->toRoute('zfcadmin/user');
}
}
}
return array(
'id' => $id,
'form' => $form,
'flashMessages' => $this->flashMessenger()->getMessages()
);
}
当我没有绑定地址时,它将刷新到用户实体,当我绑定地址时,它只刷新地址,因此我对用户的编辑将不起作用。如何编辑我的表单,保存用户和地址?