ZF2 Doctrine 2 ObjectSelect,具有不同的字段 [英] ZF2 Doctrine 2 ObjectSelect with distinct on field
本文介绍了ZF2 Doctrine 2 ObjectSelect,具有不同的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
填写我的表单我使用字段集方法。对于一个给定的表单字段,我将使用select,并且选项直接来自一个实体,如下所示:
to populate my form I use the fieldset approach. For one given form field I will use a select and the options are coming directly from an entity like this:
$this->add(
array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'city',
'options' => array(
'label' => 'City: ',
'object_manager' => $this->_om,
'target_class' => 'Hotbed\Entity\AllAdresses',
'property' => 'city',
'is_method' => true,
'find_method' => array(
'name' => 'findBy',
'params' => array(
'criteria' => array('postal_code' => $postalCode),
'orderBy' => array('city' => 'ASC'),
),
),
),
'attributes' => array(
'class' => 'form-control input-large',
'required' => '*'
),
)
);
这个效果很好。唯一不方便的是,我必须在现场城市做一个明确的事情。如何解决这个问题?
请问Andrea
This works pretty well. The only inconvient is that I have to put a distinct on the field city. How can I solve this problem? Regards Andrea
推荐答案
我解决的方法是在存储库中创建一个函数来返回不同的实体,然后在您的表单元素中指定该函数名。
The way I got around this was to create a function in the repository to return the distinct entities, and then specify that function name in your form element.
所以在你的情况下,例如:
So in your case, for example:
在您的存储库中:
public function findDistinctCitiesByPostalCode($postalCode) {
$dql = "SELECT DISTINCT a.city "
. "FROM Hotbed\Entity\AllAdresses a "
. "WHERE a.postalCode :postalCode";
$qry = $this->getEntityManager()->createQuery($dql);
$qry->setParameter('postalCode', $postalCode);
$results = $qry->getArrayResult();
// $results will be an array in the format
// array(array('city' => 'city_1'), array('city' => 'city_1'),....)
// so you'll need to loop through and create an array of entities
foreach ($results as $row) {
$addresses[] = new Hotbed\Entity\AllAdresses(array('city' => $row['city']);
}
return $addresses;
}
然后以您的形式:
$this->add(
array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'city',
'options' => array(
'label' => 'City: ',
'object_manager' => $this->_om,
'target_class' => 'Hotbed\Entity\AllAdresses',
'property' => 'city',
'is_method' => true,
'find_method' => array(
'name' => 'findDistinctCitiesByPostalCode'
)
)
)
);
这篇关于ZF2 Doctrine 2 ObjectSelect,具有不同的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文