1
我創建了一個ZF2項目具有以下依存關係:Zend框架2原則2 - 多形式相同查看
"php": ">=5.3.3",
"zendframework/zendframework": "2.*",
"zendframework/zend-developer-tools": "dev-master",
"doctrine/doctrine-orm-module": "dev-master",
"bjyoungblood/bjy-profiler": "dev-master"
我創建了一個用戶實體和RegisterUser形式。在我的索引行動我的用戶實體綁定到我的登記表格,並把它傳遞給我的看法 - 就像這樣:
public function indexAction() {
$entityManager = $this->getServiceLocator()->get ('Doctrine\ORM\EntityManager');
$form = new RegisterUserForm ($this->serviceLocator);
$user = new User();
$form->bind ($user);
if ($this->getRequest()->isPost()) {
$form->setData ($this->getRequest()->getPost());
if ($form->isValid()) {
$entityManager->persist($user);
$entityManager->flush();
}
}
return new ViewModel(array('form' => $form));
}
現在我想以另一種形式(登錄)添加到了同樣的觀點。我在確定最佳方式時遇到了一些麻煩。將多個表單綁定到相同的用戶實體會感到危險,我不確定如何處理不同操作中的帖子。
下面來看看我的表格:
class RegisterUserForm extends Form
{
public function __construct(ServiceManager $serviceManager)
{
parent::__construct('register-user-form');
$entityManager = $serviceManager->get('Doctrine\ORM\EntityManager');
$this->setHydrator(new DoctrineHydrator ($entityManager, 'Application\Entity\User'));
$userPostFieldset = new UserPostFieldset($serviceManager);
$userPostFieldset->setUseAsBaseFieldset(true);
$this->add($userPostFieldset);
}
}
和相應的字段集:
class UserPostFieldset extends Fieldset implements InputFilterProviderInterface {
public function __construct(ServiceManager $serviceManager) {
parent::__construct ('user');
$entityManager = $serviceManager->get ('Doctrine\ORM\EntityManager');
$this->setHydrator (new DoctrineHydrator ($entityManager, 'Application\Entity\User'))->setObject (new User());
$this->add (array (
'type' => 'Zend\Form\Element\Text',
'name' => 'firstName',
'options' => array (
'label' => 'First Name'
)
));
$this->add (array (
'type' => 'Zend\Form\Element\Email',
'name' => 'email',
'options' => array (
'label' => 'Email Address'
)
));
$this->add (array (
'type' => 'Zend\Form\Element\Email',
'name' => 'emailCheck',
'options' => array (
'label' => 'Re-Enter Email Address'
)
));
$this->add (array (
'name' => 'submit',
'attributes' => array (
'type' => 'submit',
'value' => 'Submit'
)
));
}
public function getInputFilterSpecification() {
return array (
'email' => array (
'required' => true,
'filters' => array (
array (
'name' => 'StripTags'
),
array (
'name' => 'StringTrim'
)
),
'validators' => array (
array (
'name' => 'Identical',
'options' => array (
'token' => 'emailCheck',
'message' => 'Emails do not match'
)
)
)
)
);
}
}
任何有識之士將不勝感激。
問題:
1 - 什麼是添加多個窗體具有相同實體處理視圖中的最佳做法?
2 - 如何拆分我的索引動作,以便將多個表單傳遞給我的視圖,然後將這些帖子映射到不同的動作以執行驗證檢查?
感謝, d
嗨,山姆,我很驚訝這是你!我在你的博客上閱讀過很多文章。請耐心等待..我是zf2的新手。我在哪裏定義'my-login-form'和'my-register-form'動作?$ sl是serviceLocator?你的解決方案看起來不錯,乾淨。我最終爲用戶,登錄表單和註冊表單創建了變量,所以我如果驗證失敗,我會創建一個ViewModel並使用setTemplate('application/index/index.phtml');重新使用索引視圖。 。想法?謝謝你對zf2的巨大貢獻:) – 2013-04-10 18:21:11
編輯使其更加清晰。配置適用於你的模塊'getServiceConfig()'工廠 – Sam 2013-04-10 18:26:48
我將在清理完後立即編輯,看看工廠。 – 2013-04-10 18:34:03