How To? Create file/image/video upload in Backend for own module

Last modified by xebay on Fri, June 25, 2010 09:35
Source|Old Revisions  

First lets suppose you created a custom module with the module creator.

Then in /app/code/local/Company/ModName/Block/Adminhtml/ModName/Edit/Form.php

Add ‘enctype’ ⇒ ‘multipart/form-data’ That should help to get something in $_FILES

You should have something looking like this:

  1. $form = new Varien_Data_Form(array(
  2.          'id' => 'edit_form',
  3.         'action' => $this->getUrl('*/*/save', array('id' =>    $this->getRequest()->getParam('id'))),
  4.         'method' => 'post',
  5.         'enctype' => 'multipart/form-data'
  6.    )
  7.  );

Then in /app/code/local/Company/ModName/Block/Adminhtml/ModName/Edit/Tab/Form.php

in _prepareForm Add your upload field (you can add a field of type file (any file) image (image with a “preview” and a checkbox to delete) or imagefile for vidéos !

  1. $fieldset->addField('fileinputname', 'file', array(
  2.           'label'     => Mage::helper('pictos')->__('File label'),
  3.           'required'  => false,
  4.           'name'      => 'fileinputname',
  5. ));

Then in /app/code/local/Company/ModName/controllers/Adminhtml/ModuleNameController.php again after if ($data = $this→getRequest()→getPost()) { in saveAction()

  1.  
  2. if(isset($_FILES['fileinputname']['name']) and (file_exists($_FILES['fileinputname']['tmp_name']))) {
  3.   try {
  4.     $uploader = new Varien_File_Uploader('fileinputname');
  5.     $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); // or pdf or anything
  6.  
  7.  
  8.     $uploader->setAllowRenameFiles(false);
  9.  
  10.     // setAllowRenameFiles(true) -> move your file in a folder the magento way
  11.     // setAllowRenameFiles(true) -> move your file directly in the $path folder
  12.     $uploader->setFilesDispersion(false);
  13.    
  14.     $path = Mage::getBaseDir('media') . DS ;
  15.                
  16.     $uploader->save($path, $_FILES['fileinputname']['name']);
  17.  
  18.     $data['fileinputname'] = $_FILES['fileinputname']['name'];
  19.   }catch(Exception $e) {
  20.  
  21.   }
  22. }

if you are using an image field type, (image is set in addField), then you should add the following code after the if in the controller code. It will now handle a “delete” checkbox linked to the upload field.

  1. else {       
  2.  
  3.     if(isset($data['fileinputname']['delete']) && $data['fileinputname']['delete'] == 1)
  4.         $data['image_main'] = '';
  5.     else
  6.         unset($data['fileinputname']);
  7. }

That’s it you’re done.




 

Magento 2 GitHub Repository

Magento Job Board - Some sort of tag line goes here

Latest Posts| View all Jobs