Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento Module Upload Image in Admin

Tags:

magento

I'm developing a module with both a frontend and a backend. Until now everything has been ok, but now I want to upload images in the backend. I don't know how to start, and everything I've tried has just given me a headache.

Thanks

like image 355
Castro Roy Avatar asked Sep 02 '10 20:09

Castro Roy


2 Answers

After a few days of research, here is an easy to use example of how you can upload files in magento How to create an image or video uploader for the Magento Admin Panel

Bassically, we need to add the 'enctype' => 'multipart/form-data' to our form

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

Add a field of type file to our fieldset

$fieldset->addField('fileinputname', 'file', array(
    'label'     => 'File label',
    'required'  => false,
    'name'      => 'fileinputname',
));

And save it in our controller

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'));

    $uploader->setAllowRenameFiles(false);

    $path = Mage::getBaseDir('media') . DS ;

    $uploader->save($path, $_FILES['fileinputname']['name']);

    $data['fileinputname'] = $_FILES['fileinputname']['name'];
  }catch(Exception $e) {

  }
}
like image 135
Castro Roy Avatar answered Oct 14 '22 22:10

Castro Roy


This needs to go into your module's etc/system.xml file:

<?xml version="1.0"?>
<config>
    <sections>
        <imagesection> <!-- Make up a section key (configuration sidebar) -->
            <!-- ... -->
            <groups>
                <imagegroup> <!-- Make up a group key (the part you can expand/collapse) -->
                    <!-- ... -->
                    <fields>
                        <imagefield> <!-- Make up a field key -->
                            <label>Field Name</label>
                            <frontend_type>image</frontend_type>
                            <backend_model>adminhtml/system_config_backend_image</backend_model>
                            <upload_dir config="system/filesystem/media" scope_info="1">uploaddir</upload_dir> <!-- would upload into media/uploaddir -->
                            <base_url type="media" scope_info="1">uploaddir</base_url> <!-- same as previous line -->
                            <sort_order>10</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </imagefield>
like image 43
mattalxndr Avatar answered Oct 14 '22 21:10

mattalxndr