我正在努力将我的zend_form 刷新为 2 个实体。我总共有 3 个实体。用户、地址和国家。Country 并不有趣,因为它具有只有 ID 进入 Address 的标准值。我的添加操作效果很好(仅当我将地址/国家/地区保留为空时,它会在数据库中添加一条新记录,因此我必须解决此问题)。但是我的编辑只刷新了我最新的绑定。我的编辑动作:
/**
* 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()
);
}
当我不绑定地址时,它将刷新到用户实体,当我绑定地址时,它仅刷新到地址,因此我对用户的编辑将不起作用。如何通过保存用户和地址来编辑我的表单?