zend框架表单上传编辑问题

时间:2011-05-12 12:20:39

标签: php zend-framework forms upload populate

我正在使用zend表格上传图片。

我的问题是当表单中的信息编辑时,表单中包含所有信息,但file_path为空,因此当您单击提交发生的更新时,将file_path设置为null。

我只想在加载时查看可编辑项目的路径,因此当您单击提交时,旧路径将在那里。

public function EditaddAction() {

    $session = new Zend_Session_Namespace('user');
    $userid = $session->id;
    // in case the request was an edit request
    $id = (int) $this->_request->getParam('id');
    //The incoming request
    $request = $this->getRequest();
    //initialize form
    $form = new Admin_Form_Banner();
    //uploaded file settings
    $file = $form->file_path;
    $file->setDestination(ZendX_Image::getFullUploadPath() . '/files/get/original/');
    //instance of db
    $db = Zend_Db_Table::getDefaultAdapter();

    if ($this->getRequest()->isPost()) {
        if ($form->isValid($request->getPost())) {

            $dbFilePath = "/files/get/original/" . $file->getFileName(null, false);


            //code to get the duration of the video
            $sourceVideo = PUBLIC_PATH . $form->getValue('file_path');
            ob_start();
            passthru("ffmpeg -i \"" . $sourceVideo . "\" 2>&1");
            $duration = ob_get_contents();
            ob_end_clean();
            preg_match('/Duration: (.*?),/', $duration, $matches);
            $duration = $matches[1];
            $duration_array = preg_split('[:]', $duration);
            $duration = $duration_array[0] * 3600 + $duration_array[1] * 60 + $duration_array[2];

            die($time);
            end of code to get the duration of the video
            if (isset($id) && $id != "" && $file->receive()) {
                try {
                    $db->update('banner', array('banner_title' => $form->getValue('banner_title'),
                        'banner_type' => $form->getValue('banner_type'),
                        'banner_position' => $form->getValue('banner_position'),
                        'banner_link' => $form->getValue('banner_link'),
                        'link_open' => $form->getValue('link_open'),
                        'file_path' => $dbFilePath,
                        'is_active' => $form->getValue('is_active')
                            ), array('id =?' => $id));
                    $this->flash('Banner Updated', 'admin/banner');
                } catch (Exception $e) {
                    $this->flash($e->getMessage(), 'admin/banner');
                }
            } else {
                try {

                    $db->insert('banner', array('banner_title' => $form->getValue('banner_title'),
                        'banner_type' => $form->getValue('banner_type'),
                        'banner_position' => $form->getValue('banner_position'),
                        'banner_link' => $form->getValue('banner_link'),
                        'link_open' => $form->getValue('link_open'),
                        'file_path' => $dbFilePath,
                        'is_active' => $form->getValue('is_active'),
                        'created_by' => $userid,
                        'date_ceated' => date('Y/m/d H:i:s'),
                        'is_deleted' => 0,
                    ));
                    $this->flash('Banner Added', 'admin/banner');
                } catch (Exception $e) {
                    $this->flash($e->getMessage(), 'admin/banner');
                }
            }
        }
    }

    if (isset($id) && $id != "") {
        $checkvalues = $db->fetchCol($db->select()->from(array('banner'),array('file_path')));
        $values = $db->fetchRow("SELECT * FROM banner WHERE id = ?", $id);
        $values['file_path'] = $checkvalues;
        $form->populate($values);
    }

    $this->view->form = $form;

3 个答案:

答案 0 :(得分:1)

当你说路径是指http客户端中的路径? 您无权访问。

如果您的问题与上传后文件的路径有关,则可以执行以下操作:

1)元素必须是Zend_Form_Element_File。

2)在控制器中:

$form->file_path->receive(); //this will return true if the file was successfully received and false if not
$file_path_on_server = $form->file_path->getFileName(); // there you get the file name

该文件将保留其原始名称。

答案 1 :(得分:1)

我遇到了同样的问题。 我通过在表单中​​使用隐藏字段来解决它,我在其中存储文件名并在修改操作中使用它

some action code
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;
            }

当然,为了更好的编程,有很多事情可以修复......

答案 2 :(得分:0)

    public function addAction()
    {

        // Criação do Objeto Formulário
        $form = new Application_Form_Banner();
        $banners = new Application_Model_Banners();
        // Há dados para Tratamento?
        if ($this->getRequest()->isPost()) {

            // Pegamos os Dados como Foram Enviados
            $data = $this->getRequest()->getPost();
            $path = APPLICATION_PATH . '/../public/banners/';
            if (!is_dir($path)) {
                mkdir($path, 0777, true);
            }
            if ($form->isValid($data)) {

                try {
                    // Dados Filtrados pelo Formulário
                    $banners->getAdapter()->beginTransaction();
                    //gambi para renomear arquivos
                    $upload = new Zend_File_Transfer_Adapter_Http();
//                $upload->addValidator('Size', false, array('min' => 100,
//                    'max' => 1150000,
//                    'bytestring' => true));
                    $upload->addValidator('ImageSize', false, array(
                        'minwidth' => 10, 'minheight' => 10,
                        'maxwidth' => 5500, 'maxheight' => 5500));
                    $filename = $upload->getFilename();
                    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
                    $filename = basename($filename);
                    $newfilename = mt_rand() . '.' . $ext;
                    $upload->addFilter(new Zend_Filter_File_Rename(array('target' => $path . $newfilename, 'overwrite' => false)));
                    if (!$upload->isValid()) {
                        $this->_flashMessenger->addMessage(array('error' => 'O tamanho arquivo é muito grande.'));
                    }
                    if ($upload->receive()) {

                        //Para funcionar esse metodo $form->getValues(); precisa ficar abaixo do método $upload->receive()
                        $data = $form->getValues();
                        $data['banner_imagem'] = $newfilename;
                        // Qualquer Manipulação de Dados
                        $banners->insert($data);
                        $banners->getAdapter()->commit();
                        $form->reset(); //limpa os campos do form.
                        $this->_flashMessenger->addMessage(array('success' => 'Dados salvos com sucesso!'));
                    }
                } catch (Exception $e) {
                    $this->_flashMessenger->addMessage(array('error' => $e->getMessage()));
                } catch (Zend_File_Transfer_Exception $e) {
                    $this->_flashMessenger->addMessage(array('error' => $e->getMessage()));
                } catch (Zend_Db_Table_Exception $e) {
                    $banners->getAdapter()->rollBack();
                    $this->_flashMessenger->addMessage(array('error' => $e->getMessage()));
                }
            } else {
                $form->populate($data);
            }
        }
        // Envio para a Camada de Visualização
        $this->view->form = $form;
    }

    public function editAction()
    {
        // Criação do Objeto Formulário
        $form = new Application_Form_Banner();
        $banners = new Application_Model_Banners();
        $form->getElement('banner_imagem')->setRequired(false);
        $form->getElement('banner_imagem')->setIgnore(true);

        $id = $this->_request->getParam('id');
        $data = $banners->find($id)->current()->toArray();
        $path = APPLICATION_PATH . '/../public/banners/';
        $banner_imagemdb = $data['banner_imagem'];
//        Zend_Debug::dump( $form->getValues());
        // Há dados para Tratamento?
        if ($this->getRequest()->isPost()) {

            // Pegamos os Dados como Foram Enviados
            $data = $this->getRequest()->getPost();

//            $data = $form->getValues();
//            Zend_Debug::dump($this->getRequest()->getPost());
//            print($form->getValue('banner_imagem'));
//            $banner_imagem = $form->getValue('banner_imagem');


            if (!is_dir($path)) {
                mkdir($path, 0777, true);
            }
            if ($form->isValid($data)) {
//                Zend_Debug::dump($this->getRequest()->getPost());
                try {

                    // Dados Filtrados pelo Formulário
                    $banners->getAdapter()->beginTransaction();
//                    Zend_Debug::dump($banner_imagem);
                    if ($form->banner_imagem->isUploaded()) {
                        //gambi para renomear arquivos
                        $upload = new Zend_File_Transfer_Adapter_Http();
                        $upload->addValidator('Size', false, array('min' => 100,
                            'max' => 11150000,
                            'bytestring' => true));
                        $upload->addValidator('ImageSize', false, array(
                            'minwidth' => 10, 'minheight' => 10,
                            'maxwidth' => 5500, 'maxheight' => 5500));
                        $filename = $upload->getFilename();
                        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
                        $filename = basename($filename);
                        $newfilename = mt_rand() . '.' . $ext;
                        $upload->addFilter(new Zend_Filter_File_Rename(array('target' => $path . $newfilename, 'overwrite' => false)));
                        if (!$upload->isValid()) {
                            $this->_flashMessenger->addMessage(array('error' => 'O tamanho arquivo é muito grande.'));
                        }
                        if ($upload->receive()) {
                            //apaga imagem antiga            
                            @unlink($path . $banner_imagemdb);

                            //Para funcionar esse metodo $form->getValues(); precisa ficar abaixo do método $upload->receive()
                            $data = $form->getValues();
                            $data['banner_imagem'] = $newfilename;
                            // Qualquer Manipulação de Dados
                            $where = $banners->getAdapter()->quoteInto("banner_id = ?", $id);
                            $banners->update($data, $where);
                            $banners->getAdapter()->commit();
                            $form->reset(); //limpa os campos do form.
                            $this->_flashMessenger->addMessage(array('success' => 'Dados salvos com sucesso!'));
                        }
                    } else {
                        $form->getElement('banner_imagem')->setRequired(false);
                        $form->getElement('banner_imagem')->setIgnore(true);
                        //Para funcionar esse metodo $form->getValues(); precisa ficar abaixo do método $upload->receive()
                        $data = $form->getValues();
                        $data['banner_imagem'] = $banner_imagemdb;
                        // Qualquer Manipulação de Dados
                        $where = $banners->getAdapter()->quoteInto("banner_id = ?", $id);
                        $banners->update($data, $where);
                        $banners->getAdapter()->commit();
                        $form->reset(); //limpa os campos do form.
                        $this->_flashMessenger->addMessage(array('success' => 'Dados salvos com sucesso!'));
                    }
                } catch (Exception $e) {
                    $this->_flashMessenger->addMessage(array('error' => $e->getMessage()));
                } catch (Zend_File_Transfer_Exception $e) {
                    $this->_flashMessenger->addMessage(array('error' => $e->getMessage()));
                } catch (Zend_Db_Table_Exception $e) {
                    $banners->getAdapter()->rollBack();
                    $this->_flashMessenger->addMessage(array('error' => $e->getMessage()));
                }
            }
        }

//        Zend_Debug::dump($data);
        $form->populate($data);
        $imagePreview = $form->createElement('image', 'image_preview');
// element options
        $imagePreview->setLabel('Preview Image: ');
        $imagePreview->setAttrib('style', 'width:200px;height:auto;');
// add the element to the form
        $imagePreview->setOrder(4);
        $imagePreview->setImage('/public/banners/' . $data['banner_imagem']);

        $form->addElement($imagePreview);


        // Envio para a Camada de Visualização
        $this->view->form = $form;
    }

    assim da certo