Magento – Image uploader in extension not saving / uploading image

controllersimagemagento-1.8

I'm trying to add an image upload to an admin page of an extension following suit from Amasty's Improved Navigation (also the extension that I'm extending)…

After saving the page however, there is no image saved nor uploaded and I'm struggling to see where the problem lies.

My saveAction in the controller is the following:-

public function saveAction() 
{
    $id     = $this->getRequest()->getParam('id');
    $model  = Mage::getModel('amshopby/page');
    $data   = $this->getRequest()->getPost();
    if ($data) {
        $model->setData($data)->setId($id);
        
        try {
            $this->prepareForSave($model);
            
            $cond = array();
            for ($i=0; $i < $model->getNum(); ++$i){
                $cond[] = array(
                    'attribute_code' => $model->getData('attr_' . $i),
                    'attribute_value' => $model->getData('option_' . $i)
                );
            }
            
            $model->setCond(serialize($cond));
            
            $model->save();
            Mage::getSingleton('adminhtml/session')->setFormData(false);
            
            $msg = Mage::helper('amshopby')->__('Page has been successfully saved');
            Mage::getSingleton('adminhtml/session')->addSuccess($msg);
            if ($this->getRequest()->getParam('continue')){
                $this->_redirect('*/*/edit', array('id' => $model->getId()));
            }
            else {
                $this->_redirect('*/*');
            }
           
            
        } catch (Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            Mage::getSingleton('adminhtml/session')->setFormData($data);
            $this->_redirect('*/*/edit', array('id' => $id));
        }    
                    
        return;
    }
    
    //upload images
    $path = Mage::getBaseDir('media') . DS . 'amshopby' . DS;
    $imagesTypes = array('big', 'small', 'medium', 'small_hover', 'main');
    foreach ($imagesTypes as $type){
        $field = 'img_' . $type;
        
        $isRemove = isset($data['remove_' . $field]);
        $hasNew   = !empty($_FILES[$field]['name']);
        
        try {
            // remove the old file
            if ($isRemove || $hasNew){
                $oldName = $model->getData($field);
                if ($oldName){
                     @unlink($path . $oldName);
                     $data[$field] = '';
                }
            }

            // upload a new if any
            if (!$isRemove && $hasNew){
                $newName = $type . $id;
                $newName .= '.' . strtolower(substr(strrchr($_FILES[$field]['name'], '.'), 1)); 
           
                $uploader = new Varien_File_Uploader($field);
                $uploader->setFilesDispersion(false);
                $uploader->setAllowRenameFiles(false);
                $uploader->setAllowedExtensions(array('png','gif', 'jpg', 'jpeg'));
                $uploader->save($path, $newName);    
                 
                $data[$field] = $newName;            
            }   
        }
        
        catch (Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());    
        }
    }

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

Every other field on the page saves fine except the image upload (which you can see in the above section from the //upload images line onwards).

The following is what I have in my Form.php for this field (though I don't expect the issue to lie here):-

$fldUpload = $form->addFieldset('upload', array('legend'=> $hlp->__('Image Upload')));
$fldUpload->addField('img_main', 'file', array(
'label'     => $hlp->__('Image'),
'name'      => 'img_main',
'required'  => false,
'after_element_html' => $this->getImageHtml($model->getImgMain()), 
)); 
$fldUpload->addField('remove_img_main', 'checkbox', array(
    'label'     => $hlp->__('Remove Image'),
    'name'      => 'remove_img_main',
    'value'     => 1,
)); 

I've also added 'enctype' => 'multipart/form-data' to the _prepareForm function like so:-

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

I also use the function below to show the uploaded image on the admin page in the field section:-

private function getImageHtml($img)
{
    $html = '';
    if ($img){
        $html .= '<p style="margin-top: 5px">';
        $html .= '<img src="'.Mage::getBaseUrl('media') . 'amshopby/' . $img .'" />';
        $html .= '</p>';
    } 
    return $html;     
}

Once page is saved, the text next to the upload image button just says 'no file chosen' still (and can confirm that nothing is saved in the database nor image uploaded to /media/amshopby).

Have I missed something obvious in the controller? The same code is in use for multiple image uploads elsewhere in this extension and working without issue (but in a different controller).

Edit 18/06/2014

I am one step closer now having managed to get the image uploader in the form to work although I cannot get the preview of the image to show in the admin form – posted as a new question.

Best Answer

Sadly i didn't have time to go the scripts you have there line by line, BUT It could be that you haven't remember to alter the form to set the multipartbit that is necessary for the file upload.

$form = new Varien_Data_Form(array('enctype' => 'multipart/form-data', 'method' => 'post'));

But if it does have that then you have an issue with your codes and i'd suggest you to use Zend_Debug::dump($_FILES) to log out do you get the right data on the submission.

Or Mage::log($message) that should output the logs under /etc/logs/system.log

Related Topic