【发布时间】:2013-06-11 20:28:18
【问题描述】:
使用 zf2 和 Doctrine,我正在为我的 Salesman 类生成一个表单。 Salesman 有一个对 Store 的 ManyToOne 引用(即,一个商店可以有 1 个或多个销售员)
由于我使用了@Annotation\Type("DoctrineORMModule\Form\Element\EntitySelect"),所以我在表单中显示了一个下拉列表,这正是我想要的。 p>
我想要实现的是基于商店的名称属性对商店进行排序在@ManyToOne 关联的框架中
这是我拥有的 HTML(生成)代码:
<select>
<option value="1" selected="selected">Store A</option>
<option value="2">Store C</option> <- not ordered! probably because using row id for sorting.
<option value="3">Store B</option>
<select>
这就是我想要的:
<select>
<option value="1" selected="selected">Store A</option>
<option value="3">Store B</option>
<option value="2">Store C</option> <- good, now my store are alphabetically ordered :-)
<select>
@Annotation\Type("DoctrineORMModule\Form\Element\EntitySelect") 接受 @ORM\OrderBy({"name" = "ASC"}) 可选注释但这仅适用于 @OneToMany 或 @ManyToMany :-(
问题:
如何通过我的 @ManyToOne 关联在我的 EntitySelect 中实现排序?
PHP源码摘录:
<?php
namespace Customer\Entity;
use Doctrine\ORM\Mapping as ORM;
use Zend\Form\Annotation;
/**
* @ORM\Entity
*/
class Salesman extends AbstractEntity
{
...
/**
* @ORM\ManyToOne(targetEntity="Customer\Entity\Store", fetch="EAGER")
* @Annotation\Attributes({"readonly":"false"})
* @Annotation\Type("DoctrineORMModule\Form\Element\EntitySelect")
* @Annotation\Options({"label":"Store:", "target_class":"Customer\Entity\Store"})
*/
protected $store;
...
}
<?php
namespace Customer\Entity;
use Doctrine\ORM\Mapping as ORM;
use Zend\Form\Annotation;
/**
* @ORM\Entity
*/
class Store extends AbstractEntity
{
...
/**
* @ORM\Column(type="string", length=100)
* @Annotation\Options({"label":"Name: "})
*/
protected $name;
/**
* @ORM\OneToMany(targetEntity="Customer\Entity\Salesman", mappedBy="store", cascade={"all"}, orphanRemoval=true)
* @Annotation\Attributes({"type":"hidden"})
* @Annotation\Required(false)
* @Annotation\Type("Zend\Form\Element\Collection")
* @Annotation\Options({
* "label" : "Salesmen",
* "target_element" : {
* "composedObject" : "Customer\Entity\Salesman"
* }
* })
*/
protected $salesmen;
...
}
关于视图(.phtml),没什么特别要说的:只是基本形式。
...
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formCollection($form);
echo $this->form()->closeTag();
...
感谢您的帮助。
【问题讨论】:
-
谢谢山姆。好吧...我使用 $builder = new AnnotationBuilder(); 创建表单$this->form = $builder->createForm('Customer\Entity\Salesman');所以我会尝试在表单中找出生成的“DoctrineModule\Form\Element\ObjectSelect”并以编程方式对其进行更改。但这似乎不是“最干净”的继续方式(使用基于注释的表单创建方法时)
-
我自己不使用注释,所以无法解决这个事实,但目前这是唯一的方法。如果我没记错的话,我们在 ZF2 中没有
@Inject。 -
感谢您的评论:所以我调试并找到了 EntitySelect 元素并且可以更改选项以使其正常工作!感谢您的提示(我在回答中感谢您)
标签: php doctrine zend-framework2