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

问题描述 投票:0回答:1

我有一个名为 Lead 的实体设置,其中包含汽车品牌、型号等,并且该 Lead 通过多对一关系映射到客户实体,该客户实体具有姓名等。 即一个客户可能有很多潜在客户

我创建了一个 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());

这对于填充的潜在客户实体的字段效果很好,但它不会填充基于客户的字段,例如名字.

编辑

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

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);
php forms zend-framework doctrine-orm populate
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.