Zend1表单上传文档文件

时间:2013-12-13 08:05:16

标签: forms zend-framework document

我有一个“addForm”和一个“editForm”。在addForm中添加文档文件后,它将保存在我的数据库中。如果我想编辑此表单,我必须再次上传此文档。旧文档将被删除。我想创建一个函数来检查文档是否已经上传,所以每次我想编辑项目时都不需要上传它。我只是不知道从哪里开始。一点帮助都会很棒。

我的添加/编辑形式:

    $pdf = new Zend_Form_Element_File('document');
    $pdf->setLabel('Nieuwe PDF')
            ->addValidator('extension', true, array('docx',  
                              'docx','pdf','txt'))
            ->addValidator('Count', false, 1)
            ->addValidator('Size', false, 10240000)
            ->setDestination( PUBLIC_PATH . '/../data/invoicespdf/')
            ->setRequired(false);

1 个答案:

答案 0 :(得分:0)

尝试在控制器中使用它...修改它以满足您的需求:

if ($request->isPost()) {
                if ($form->isValid($request->getPost())) {
                    if ('administrator' == $user->role) {
                        $oldFileName = $form->getElement('oldfilename')->getValue(); //the hidden field
                        $data = $form->getValues();
                        $model->populate($data);
                    if (file_exists('uploads/cv/' . $oldFileName)) {
                            $form->getElement('cv')->setIgnore(true); //this is my Form File Element - the file exists, I don't need to store the filename
                        } else { // if you want you can unlink $oldFileName
                            $upload = new Zend_File_Transfer_Adapter_Http();
                            $info = $upload->getFileInfo('cv');
                            $upload->setDestination("uploads/cv/");
                            if (file_exists('uploads/cv/' . $info['cv']['name'])) {
                                $newFileName = time() . rand(0, 100000) . "-" . $info['cv']['name']; // I need to avoid overwriting file
                            } else {
                                $newFileName = $info['cv']['name'];
                                $upload->addFilter('Rename', $newFileName);
                            }
                            try {
                                $upload->receive();
                            } catch (Zend_File_Transfer_Exception $e) {
                                $e->getMessage();
                            }
                        }
                        $model->save();
                        return $this->_helper->redirector('list');
                    } else {
                        //some error message
                        $this->_helper->redirector('list');
                    }
                } else { //form not valid
                    $this->view->form = $form;
                }
            } else {
                $model->find($id);
                $data = array();
                $data = $model->toArray();
                $data['oldfilename'] = $model->get_cv(); //the filename stored in db
                $form->getElement('cv')->setRequired(false);
                $form->populate($data);
                $this->view->form = $form;
            }