ZF2 Doctrine 2 ObjectSelect具有不同的on字段

时间:2014-04-23 14:09:55

标签: doctrine-orm zend-framework2

填充我的表单我使用fieldset方法。对于一个给定的表单字段,我将使用select,选项直接来自这样的实体:

$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' => '*'
                ),
            )
    );

这非常有效。唯一不足的是,我必须在田野城市上区别对待。我怎么解决这个问题? 关心安德烈

1 个答案:

答案 0 :(得分:3)

我解决这个问题的方法是在存储库中创建一个函数来返回不同的实体,然后在表单元素中指定该函数名称。

所以在你的情况下,例如:

在您的存储库中:

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'
                )
            )
        )
);