Magento:Adminhtml表单“图像”字段

时间:2010-01-29 21:02:14

标签: image forms magento field backend

我已使用以下代码在管理表单中设置了“Image”类型的输入字段:

<?php
// Tab Form
// File: app/code/local/MyCompany/Mymodule/Block/Adminhtml/Items/Edit/Tab/Form.php

class MyCompany_Mymodule_Block_Adminhtml_Items_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
  protected function _prepareForm()
  {
      $form = new Varien_Data_Form();
      $this->setForm($form);
      $fieldset = $form->addFieldset('mymodule_form',        array('legend'=>Mage::helper('mymodule')->__('Item information')));     

      $fieldset->addField('photo', 'image', array(
          'label'     => Mage::helper('mymodule')->__('Photo'),
          'required'  => false,
          'name'      => 'photo',
      ));     

      if ( Mage::getSingleton('adminhtml/session')->getMymoduleData() )
      {
          $form->setValues(Mage::getSingleton('adminhtml/session')->getMymoduleData());
          Mage::getSingleton('adminhtml/session')->setMymoduleData(null);
      } elseif ( Mage::registry('mymodule_data') ) {
          $form->setValues(Mage::registry('mymodule_data')->getData());
      }
      return parent::_prepareForm();
  }
}

然后,在控制器内部使用以下方法保存图像:

public function saveAction() 
{
 if($data = $this->getRequest()->getPost()) {              
     $model = Mage::getModel('mymodule/speakers');        
     $model->setData($data)->setId($this->getRequest()->getParam('id'));

     $model->setKeynote($this->getRequest()->getParam('keynote'));

     // Save photo
     if(isset($_FILES['photo']['name']) && $_FILES['photo']['name'] != '') {
         try {    
             $uploader = new Varien_File_Uploader('photo');

             $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
             $uploader->setAllowRenameFiles(false);
             $uploader->setFilesDispersion(false);

             // Set media as the upload dir
             $media_path  = Mage::getBaseDir('media') . DS;                

             // Upload the image
             $uploader->save($media_path, $_FILES['photo']['name']);

             $data['photo'] = $media_path . $_FILES['photo']['name'];

         } 
         catch (Exception $e) {
             print_r($e);
             die;
         }                            
     }
     else {       
         if(isset($data['photo']['delete']) && $data['photo']['delete'] == 1) {
             $data['photo'] = '';
         }
         else {
             unset($data['photo']);
         }
      }
     if(isset($data['photo'])) $model->setPhoto($data['photo']);    

     try {                
         $model->save();

         Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('mymodule')->__('Item was successfully saved'));
         Mage::getSingleton('adminhtml/session')->setFormData(false);

         if ($this->getRequest()->getParam('back')) {
             $this->_redirect('*/*/edit', array('id' => $model->getId()));
             return;
         }
         $this->_redirect('*/*/');
         return;
     } 
     catch (Exception $e) {
         Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
         Mage::getSingleton('adminhtml/session')->setFormData($data);
         $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
         return;
     }
 }

 Mage::getSingleton('adminhtml/session')->addError(Mage::helper('mymodule')->__('Unable to find item to save'));
 $this->_redirect('*/*/');
}

长话短说:当我在后端保存项目(使用保存或保存并继续编辑)时,可以节省一次。然后下次它给出下一个错误:

  

注意:数组转换为字符串   /home/wwwadmin/public_html/aaa.bbb.ccc/public/lib/Zend/Db/Statement/Pdo.php   在232行

接下来保存好了。下一个:错误。接下来好......你知道我的意思......

我正在查看一些代码以了解如何使用此输入类型。但还没有。在magento代码中都没有。这是我发现的唯一一件事:http://www.magentocommerce.com/wiki/how_to/how_to_create_pdf_upload_in_backend_for_own_module

有什么想法吗?

由于

2 个答案:

答案 0 :(得分:0)

此行运行时:

$model->setData($data)->setId($this->getRequest()->getParam('id'));<br/>
$model->_data['image'] will be set to   array('image'=>'[YOUR path]')<br/>

在使用setData()

进行所有操作后,您应该调用方法data['image'];

答案 1 :(得分:0)

在控制器中尝试使用以下代码进行保存操作

    if ($data = $this->getRequest()->getPost()) {
        $id = $this->getRequest()->getParam('id');
        $model = Mage::getModel('your_model')->load($id);

        if (isset($data['image']['delete'])) {
            Mage::helper('your_helper')->deleteImageFile($data['image']['value']);
        }
        $image = Mage::helper('your_helper')->uploadBannerImage();
        if ($image || (isset($data['image']['delete']) && $data['image']['delete'])) {
            $data['image'] = $image;
        } else {
            unset($data['image']);
        }            
        $model->setData($data)
                ->setId($id);
        try {
            $model->save();
            Mage::getSingleton('adminhtml/session')->addSuccess('Your request Save.');
            $this->_redirect('*/*/');
        } catch (Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            Mage::getSingleton('adminhtml/session')->setFormData($data);
            $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
            return;
        }
    } else {
        Mage::getSingleton('adminhtml/session')->addError(Mage::helper('your_helper')->__('Unable to find your request to save'));
        $this->_redirect('*/*/');
    }

在你的助手

    public function uploadBannerImage() {
    $path = Mage::getBaseDir('media') . DS . 'images';
    $image = "";
    if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') {
        try {
            /* Starting upload */
            $uploader = new Varien_File_Uploader('image');

            // Any extention would work
            $uploader->setAllowedExtensions(array(
                'jpg', 'jpeg', 'gif', 'png'
            ));
            $uploader->setAllowRenameFiles(true);

            $uploader->setFilesDispersion(true);

            $uploader->save($path, $uploader->getCorrectFileName($_FILES['image']['name']));
            $image = substr(strrchr($uploader->getUploadedFileName(), "/"), 1);
        } catch (Exception $e) {
            Mage::getSingleton('customer/session')->addError($e->getMessage());
        }
    }
    return $image;
}

    public function deleteImageFile($image) {
    if (!$image) {
        return;
    }
    try {
        $img_path = Mage::getBaseDir('media') . "/" . $image;
        if (!file_exists($img_path)) {
            return;
        }
        unlink($img_path);
    } catch (Exception $exc) {
        echo $exc->getTraceAsString();
    }
}