![](/img/trans.png)
[英]Getting data from a database in a datetimelocal form element on Zend framework2
[英]how to set value from database in Zend Framework 2 in add form element
我是zenframework 2的新手。我已經正確設置了zendframework 2,doctrine和zfcUser.All,它們都可以正常工作。
我現在的問題是,如果成員已經登錄,如何預先填寫表格。
這是我擴展zfcUser以獲得登錄成員的ID的位置:
public function setid( $id)
{
$this->id = $id;
}
public function getId()
{
if (!$this->id) {
$this->setid($this->zfcUserAuthentication()->getAuthService()->getIdentity()->getId());
}
return $this->id;
}
我知道要使用該ID從數據庫中獲取值,然后使用這些值填充表單。
這是我的表格:
public function aboutYouAction()
{
$id = $this->getId() ;
$form = new CreateAboutYouForm($this->getEntityManager());
$aboutYou = new AboutYou();
$form->setInputFilter($aboutYou->getInputFilter());
$form->bind($aboutYou);
if ($this->request->isPost())
{
$form->setData($this->request->getPost());
if ($form->isValid())
{
$post = $this->request->getPost();
$this->getEntityManager()->persist($aboutYou);
$this->getEntityManager()->flush();
return $this->redirect()->toRoute('worker', array('action' => 'aboutYou'));
}
}
$messages='';
// return array('form' => $form);
return new ViewModel(array('form' => $form, 'messages' => $messages));
}
要在表單上設置值,您需要做的就是$form->bind($aboutYou)
bind()
方法旨在獲取傳遞的實體實例並將其映射到form元素。 該過程稱為形式水合 。
根據附加到表單或字段集的AboutYou
(使用學說,通常是DoctrineModule\\Stdlib\\Hydrator\\DoctrineObject
),這應該能夠評估AboutYou
字段,包括任何實體引用/關聯,並設置相應的表單元素值。 我假設這些字段之一是user
。
在您的特定情況下,您似乎正在綁定一個新實體(因此將不設置任何屬性,例如您的用戶)
$aboutYou = new AboutYou(); // Brand new entity
$form->bind($aboutYou); // Binding to the form without any data
這意味着表單正在嘗試設置元素的值,但是提供的AboutYou
類沒有要設置的數據(因為它是新數據,並且未通過學說加載)和/或AboutYou
類的屬性未正確映射表單的元素。
如果希望綁定用戶,則需要獲取填充的實例。 這可以使用原則( $objectManager->find('AboutYou', $aboutYouId)
)完成,或者如果您需要設置當前登錄用戶,請從控制器ZfcUser\\Controller\\Plugin\\ZfcUserAuthentication
調用控制器插件ZfcUser\\Controller\\Plugin\\ZfcUserAuthentication
。否則 。
您的工作流程應與此類似( 僅用於說明目的 )
// Controller
public function aboutYouAction()
{
// Get the id via posted/query/route params
$aboutYouId = $this->params('id', false);
// get the object manager
$objectManager = $this->getServiceLocator()->get('ObjectManager');
// Fetch the populated instance
$aboutYou = $objectManager->find('AboutYou', $aboutYouId);
// here the about you entity should be populated with a user object
// so that if you were to call $aboutYou->getUser() it would return an user object
// Get the form from the service manager (rather than creating it in the controller)
// meaning you should create a factory service for this
$form = $this->getServiceLocator()->get('MyForm');
// Bind the populated object to the form
$form->bind($aboutYou);
//... rest of the action such as handle edits etc
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.