1

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.

2

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

9
  • Did you debug that you get the file info on the post? If you did and the post works then you have a flaw in the saving of the page data as after a quick snoop i noticed that there a $model->save(); save there. But no saving after the image bit. – Olli Tyynelä Jun 17 '14 at 13:04
  • I haven't really figured out what to try and log within the controller to be honest yet but I do think that the issue is something to do with the code relating to the upload images in the controller being in the wrong place. I think it needs to be inside the sections that includes $model->save(); - is this what you're suggesting also? Thanks. – zigojacko Jun 17 '14 at 16:10
  • That was it, I moved the code for image upload to below $model->setData($data)->setId($id); and it is now uploading the file (could see that as I also added logging from your answer Mage::log("Did we upload the file' . $newName", Zend_Log::INFO, 'img_main.log', true);. It isn't showing the image on the page though but getting closer now! – zigojacko Jun 17 '14 at 16:20
  • I posted a follow up question for the last part of this problem (getting the uploaded image to preview in the admin form). – zigojacko Jun 18 '14 at 6:57
  • 1
    Cool! Anyways as general tips on debugging: you can pass whole objects to the Mage::log or Zend_Debug::dump so no need to get single values. And also I'd suggest on dumping / logging always per line and after that just die() to prevent next steps from running and fix issues almost "per step basis". Eg. does this "if" work or does it go to the else. Also a pro tip (or not): you could run "tail -f file" on the console for the log file. It will follow the file updates and output them is it changes. – Olli Tyynelä Jun 18 '14 at 9:16
1

I managed to get the image upload to work in the form by placing the relevant code into the SaveAction() function before the prepareForSave($model) like so:-

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

    //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());    
        }
    }

        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');
            //log
            Mage::log("Did we upload the file' . $newName", Zend_Log::INFO, 'img_main.log', true);
            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;
    }

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.