【发布时间】:2013-01-03 16:00:26
【问题描述】:
正如here 所提到的,我正在构建一个自定义水合策略来处理表单中选择框中的相关对象。
我的表单如下所示:
$builder = new AnnotationBuilder($entityManager);
$form = $builder->createForm(new MyEntity());
$form->add(new MyFieldSet());
$hydrator = new ClassMethodsHydrator();
$hydrator->addStrategy('my_attribute', new MyHydrationStrategy());
$form->setHydrator($hydrator);
$form->get('my_attribute')->setValueOptions(
$entityManager->getRepository('SecEntity\Entity\SecEntity')->fetchAllAsArray()
);
当我通过 addAction 添加新的 MyEntity 时,一切正常。
我写了fetchAllAsArray() 来填充我的选择框。它位于我的 SecEntityRepository 中:
public function fetchAllAsArray() {
$objects = $this->createQueryBuilder('s')
->add('select', 's.id, s.name')
->add('orderBy', 's.name ASC')
->getQuery()
->getResult();
$list = array();
foreach($objects as $obj) {
$list[$obj['id']] = $obj['name'];
}
return $list;
}
但在编辑情况下,extract() 函数不起作用。我现在还没有看到hydrate() 的内容,所以我暂时将其排除在外。
我的补水策略如下所示:
class MyHydrationStrategy extends DefaultStrategy
{
public function extract($value) {
print_r($value);
$result = array();
foreach ($value as $instance) {
print_r($instance);
$result[] = $instance->getId();
}
return $result;
}
public function hydrate($value) {
...
}
问题如下:
致命错误:在非对象上调用成员函数 getId()
print_r($value) 返回大量以
DoctrineORMModule\Proxy__CG__\SecEntity\Entity\SecEntity 对象
接下来是关于 BasicEntityPersister 的一些内容,而混乱中的某处是我引用的实体。
print_r($instance) 不打印任何内容。它只是空的。因此我猜错误消息是合法的......但为什么我不能遍历这些对象?
有什么想法吗?
编辑:
关于@Sam:
我在实体中的属性:
/**
* @ORM\ManyToOne(targetEntity="Path/To/Entity", inversedBy="whatever")
* @ORM\JoinColumn(name="attribute_id", referencedColumnName="id")
* @Form\Attributes({"type":"hidden"})
*
*/
protected $attribute;
我的新选择框:
$form->add(array(
'name' => 'attribute',
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'attributes' => array(
'required' => true
),
'options' => array(
'label' => 'MyLabel',
'object_manager' => $entityManager,
'target_class' => 'Path/To/Entity',
'property' => 'name'
)
));
我最后的希望是我在控制器中做错了什么。我的选择框既没有被预选,也没有保存值...
...
$obj= $this->getEntityManager()->find('Path/To/Entity', $id);
$builder = new \MyEnity\MyFormBuilder();
$form = $builder->newForm($this->getEntityManager());
$form->setBindOnValidate(false);
$form->bind($obj);
$form->setData($obj->getArrayCopy());
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$form->bindValues();
$this->getEntityManager()->flush();
return $this->redirect()->toRoute('entity');
}
}
【问题讨论】:
-
问题:为什么不使用 Doctrine Form Elements?
-
好一个 :) 我不知道他们的存在我不得不承认......你知道他们的好教程吗?如果他们工作,这是我会说这个问题的合法答案;)
标签: php doctrine-orm zend-form zend-framework2 foreign-key-relationship