Page tree
Skip to end of metadata
Go to start of metadata

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:

$form = new Varien_Data_Form(array(
         'id' => 'edit_form',
        'action' => $this->getUrl('*/*/save', array('id' =>    $this->getRequest()->getParam('id'))),
        'method' => 'post',
        'enctype' => 'multipart/form-data'
   )
 ); 

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 !

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

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

 


if(isset($_FILES['fileinputname']['name']) and (file_exists($_FILES['fileinputname']['tmp_name']))) {
  try {
    $uploader = new Varien_File_Uploader('fileinputname');
    $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); // or pdf or anything
 
 
    $uploader->setAllowRenameFiles(false);
 
    // setAllowRenameFiles(true) -> move your file in a folder the magento way
    // setAllowRenameFiles(true) -> move your file directly in the $path folder
    $uploader->setFilesDispersion(false);
   
    $path = Mage::getBaseDir('media') . DS ;
               
    $uploader->save($path, $_FILES['fileinputname']['name']);
 
    $data['fileinputname'] = $_FILES['fileinputname']['name'];
  }catch(Exception $e) {
 
  }
} 

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.

else {       
 
    if(isset($data['fileinputname']['delete']) && $data['fileinputname']['delete'] == 1)
        $data['image_main'] = '';
    else
        unset($data['fileinputname']);
} 

That's it! You're done!

  • No labels