作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我刚开始使用 Doctrine,并且正在重写一些代码以在某些形式中使用 Doctrine 实体。
我有一个实体业务,它与地址、员工、电子邮件等有一些 1:n 的关系。设置非常基本并且工作正常。
为了添加新业务,我为我的每个实体创建了一个 BusinessForm 和 Fieldsets。这里是表单的构造函数:
public function __construct($scenario='create', $entityManager = null) {
parent::__construct('business_form');
$this->scenario = $scenario;
$this->entityManager = $entityManager;
$this->setAttribute('method', 'post');
$businessFieldset = new BusinessFieldset($this->entityManager);
$businessFieldset->setUseAsBaseFieldset(true);
$this->add($businessFieldset);
$hydrator = new DoctrineHydrator($this->entityManager, new Business());
$this->setHydrator($hydrator);
$this->addElements();
$this->addInputFilter();
}
public function addAction(){
$form = new BusinessForm('create', $this->entityManager);
if ($this->getRequest()->isPost()) {
$data = $this->params()->fromPost();
$form->setData($data);
if($form->isValid()) {
// save Object
return $this->redirect()->toRoute('subcontractor', ['action'=>'index']);
}
}
return new ViewModel([
'form' => $form
]);
}
$form->getData()
从表单中获取数据.但我无法弄清楚如何使用表单的 Hydrator 从表单中获取填充的对象。当我使用
setObject(new Business())
在 Controller 启动时,
$form->isValid()
出现错误在跑 :
Zend\Hydrator\ArraySerializable::extract expects the provided object to implement getArrayCopy()
setObject()
而是使用
$form->bind(new Business())
验证后,我从
$form->getObject()
得到一个空对象.如果我得到数据并像这样使用表单的 Hydrator hydration 一个新对象:
$form->getHydrator()->hydrate($data['business], new Business())
我确实得到了我期待的填充对象。 (业务是基本字段集的名称)
$form->getObject()
获得最后一次通话的结果验证后?
$form->getData()
获得预期的业务对象
$this->add([
'name' => 'emails',
'type' => 'Zend\Form\Element\Collection',
'attributes' => [
'id' => 'business_emails',
],
'options' => [
'label' => 'Emails',
'count' => 1,
'should_create_template' => true,
'template_placeholder' => '__index__',
'allow_add' => true,
'target_element' => [
'type' => 'LwsSubcontractor\Form\EmailFieldset',
],
'target_class' => 'LwsSubcontractor\Entity\Email'
],
]);
public function __construct() {
parent::__construct('email');
$this->setObject(new Email());
$this->addElements();
}
protected function addElements() {
$this->add([
'name' => 'email',
'type' => 'Zend\Form\Element\Email',
'attributes' => [
'placeholder' => 'E-Mail (z.B. email@muster-email.de)',
'class' => 'form-control',
'required' => true,
'size' => 50,
],
'options' => [
'label' => 'Email',
],
]);
最佳答案
您必须将 Hydrator 添加到所有字段集中,我个人使用 DoctrineModule\Stdlib\Hydrator\DoctrineObject
对于 Doctrine 实体。
我也会考虑使用 init()
初始化表单和添加元素的方法,然后通过 FormElementManager 注册和检索表单和字段集,$serviceLocator->get('FormElementManager')->get(yourFieldsetorForm::class)
.然后可以将表单注入(inject)到您的 Controller 中。
我希望这有帮助。
关于doctrine - 如何从 Zend Forms 中正确地补充和提取 Doctrine Entity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45996348/
我是一名优秀的程序员,十分优秀!