如何从具有多对一关系的学说模型中填充Zend表单?

时间:2012-01-02 19:08:05

标签: forms zend-framework doctrine-orm populate

我有一个名为Lead的实体设置,其中包含汽车品牌,型号等,此Lead通过多对一关系映射到客户实体,该实体具有forname,surname等。 即客户可能有很多线索

我创建了一个toArray函数,它从Lead中获取数据,

public function toArray()
{
    $record_data = get_object_vars($this);
    $formatted_record_data = array();
    foreach($record_data as $name=>$value){
        if (is_object($value)){
            if (get_class($value) == 'DateTime') {
                $value = $this->datetimeToString($value);
            } else {
                $value = $value->toArray();
            }
        }
            $formatted_record_data[$this->from_camel_case($name)] = $value;
    }
    return $formatted_record_data;
}

然后使用:

填充Zend表单
$record = $this->_em->getRepository($this->_entity)->find($this->_primaryId);
$form->setDefaults($record->toArray());

这适用于已填充的Lead实体的字段,但它不会填充基于客户端的字段,例如的forName。

修改

我已通过以下方法解决了我的问题:

1)将以下方法添加到我的更新操作中。

$this->_record = $this->_em->getRepository($this->_entity)->find($this->_primaryId);
$this->_form->setRecord($this->_record);
$this->view->form = $this->_form;

2)将以下方法添加到我的表单模型

public function setRecord($record)
{
    $data = array('registration' => $record->registration,
                'make' => $record->make,
                'model' => $record->model,
                'pav' => $record->pav,
                'salvage_value' => $record->salvageValue,
                'forname' => $record->client->forname,
                'surname' => $record->client->surname,
                'vehicle_address1' => $record->vehicleAddress1,
                'vehicle_address2' => $record->vehicleAddress2,
                'vehicle_address3' => $record->vehicleAddress3,
                'vehicle_address4' => $record->vehicleAddress4,
                'vehicle_address5' => $record->vehicleAddress5,
                'vehicle_postcode' => $record->vehiclePostcode,
                'category' => $record->category,  
                'colour' => $record->colour
    );
    $this->setDefaults($data);
}

这样我可以手动获取相关数据,在这种情况下:

'forname' => $record->client->forname,
'surname' => $record->client->surname,

并使用以下内容将它们添加到表单中

$this->setDefaults($data);

1 个答案:

答案 0 :(得分:0)

尝试:

$leads = $record->toArray();
$client_info = array('name' => 'test', 'surname' => 'test 2'); // or if from db use what you did for the leads.

$defaults = array_merge($leads, $client_info);

$form->setDefaults($defaults);