按照教程,我能够很好地创建文件上传,并且根据 zend 教程,editAction 与 Add 操作几乎相同。
如果我不在 editAction 中添加文件上传代码,它工作正常,但添加文件上传后,exchangearray() 中显示错误
不能在第 20 行的 \module\report\src\report\Model\CompanyReport.php 中使用类型为 \Model\CompanyReport 的对象作为数组
这是模型文件
public function exchangeArray($data)
{
<-this is line number 20->$this->id = (isset($data['id'])) ? $data['id'] : null;
$this->title = (isset($data['title'])) ? $data['title'] : null;
$this->company = (isset($data['company'])) ? $data['company'] : null;
$this->sector = (isset($data['sector'])) ? $data['sector'] : null;
$this->report_date = (isset($data['report_date'])) ? $data['report_date'] : null;
$this->report_file = (isset($data['report_file'])) ? $data['report_file'] : null;
}
下面是editAction代码
public function editAction(){
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('companyreport', array(
'action' => 'add'
));
}
// Get the Album with the specified id. An exception is thrown
// if it cannot be found, in which case go to the index page.
try {
$companyreport = $this->getCompanyReportTable()->getCompanyReport($id);
}
catch (\Exception $ex) {
return $this->redirect()->toRoute('companyreport', array(
'action' => 'index'
));
}
$form = new CompanyReportForm();
$form->bind($companyreport);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
if ($request->isPost()) {
$companyreport = new CompanyReport();
$form->setInputFilter($companyreport->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('report_file');
$data = array_merge_recursive(
$this->getRequest()->getPost()->toArray(),
$this->getRequest()->getFiles()->toArray()
);
$form->setData($data);
if ($form->isValid()) {
$size = new Size(array('min'=>500000)); //minimum bytes filesize
$adapter = new \Zend\File\Transfer\Adapter\Http();
//validator can be more than one...
$adapter->setValidators(array($size), $File['name']);
if (!$adapter->isValid()){
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$error[] = $row;
} //set formElementErrors
$form->setMessages(array('report_file'=>$error ));
} else {
$adapter->setDestination(dirname(__DIR__).'/company_reports');
if ($adapter->receive($File['name'])) {
$companyreport->exchangeArray($form->getData());
$this->getCompanyReportTable()->saveCompanyReport($companyreport);
// Redirect to list of albums
return $this->redirect()->toRoute('companyreport');
}
}
}
}
return array(
'id' => $id,
'form' => $form,
);
}
请建议使用 editAction 进行文件上传。